PostgreSQL Source Code git master
Loading...
Searching...
No Matches
checkpointer.c File Reference
#include "postgres.h"
#include <sys/time.h>
#include "access/xlog.h"
#include "access/xlog_internal.h"
#include "access/xlogrecovery.h"
#include "catalog/pg_authid.h"
#include "commands/defrem.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "postmaster/auxprocess.h"
#include "postmaster/bgwriter.h"
#include "postmaster/interrupt.h"
#include "replication/syncrep.h"
#include "storage/aio_subsys.h"
#include "storage/bufmgr.h"
#include "storage/condition_variable.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/shmem.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "storage/subsystems.h"
#include "utils/acl.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/resowner.h"
#include "utils/wait_event.h"
Include dependency graph for checkpointer.c:

Go to the source code of this file.

Data Structures

struct  CheckpointerRequest
 
struct  CheckpointerShmemStruct
 

Macros

#define WRITES_PER_ABSORB   1000
 
#define CKPT_REQ_BATCH_SIZE   10000
 
#define MAX_CHECKPOINT_REQUESTS   10000000
 
#define MAX_SIGNAL_TRIES   600 /* max wait 60.0 sec */
 

Functions

static void CheckpointerShmemRequest (void *arg)
 
static void CheckpointerShmemInit (void *arg)
 
static void ProcessCheckpointerInterrupts (void)
 
static void CheckArchiveTimeout (void)
 
static bool IsCheckpointOnSchedule (double progress)
 
static bool FastCheckpointRequested (void)
 
static bool CompactCheckpointerRequestQueue (void)
 
static void UpdateSharedMemoryConfig (void)
 
static void ReqShutdownXLOG (SIGNAL_ARGS)
 
void CheckpointerMain (const void *startup_data, size_t startup_data_len)
 
void CheckpointWriteDelay (int flags, double progress)
 
void ExecCheckpoint (ParseState *pstate, CheckPointStmt *stmt)
 
void RequestCheckpoint (int flags)
 
bool ForwardSyncRequest (const FileTag *ftag, SyncRequestType type)
 
void AbsorbSyncRequests (void)
 
bool FirstCallSinceLastCheckpoint (void)
 
void WakeupCheckpointer (void)
 

Variables

static CheckpointerShmemStructCheckpointerShmem
 
const ShmemCallbacks CheckpointerShmemCallbacks
 
int CheckPointTimeout = 300
 
int CheckPointWarning = 30
 
double CheckPointCompletionTarget = 0.9
 
static bool ckpt_active = false
 
static volatile sig_atomic_t ShutdownXLOGPending = false
 
static pg_time_t ckpt_start_time
 
static XLogRecPtr ckpt_start_recptr
 
static double ckpt_cached_elapsed
 
static pg_time_t last_checkpoint_time
 
static pg_time_t last_xlog_switch_time
 

Macro Definition Documentation

◆ CKPT_REQ_BATCH_SIZE

#define CKPT_REQ_BATCH_SIZE   10000

Definition at line 160 of file checkpointer.c.

◆ MAX_CHECKPOINT_REQUESTS

#define MAX_CHECKPOINT_REQUESTS   10000000

Definition at line 163 of file checkpointer.c.

◆ MAX_SIGNAL_TRIES

#define MAX_SIGNAL_TRIES   600 /* max wait 60.0 sec */

◆ WRITES_PER_ABSORB

#define WRITES_PER_ABSORB   1000

Definition at line 157 of file checkpointer.c.

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1424 of file checkpointer.c.

1425{
1426 CheckpointerRequest *requests = NULL;
1428 int n,
1429 i;
1430 bool loop;
1431
1432 if (!AmCheckpointerProcess())
1433 return;
1434
1435 do
1436 {
1438
1439 /*---
1440 * We try to avoid holding the lock for a long time by:
1441 * 1. Copying the request array and processing the requests after
1442 * releasing the lock;
1443 * 2. Processing not the whole queue, but only batches of
1444 * CKPT_REQ_BATCH_SIZE at once.
1445 *
1446 * Once we have cleared the requests from shared memory, we must
1447 * PANIC if we then fail to absorb them (e.g., because our hashtable
1448 * runs out of memory). This is because the system cannot run safely
1449 * if we are unable to fsync what we have been told to fsync.
1450 * Fortunately, the hashtable is so small that the problem is quite
1451 * unlikely to arise in practice.
1452 *
1453 * Note: The maximum possible size of a ring buffer is
1454 * MAX_CHECKPOINT_REQUESTS entries, which fit into a maximum palloc
1455 * allocation size of 1Gb. Our maximum batch size,
1456 * CKPT_REQ_BATCH_SIZE, is even smaller.
1457 */
1459 if (n > 0)
1460 {
1461 if (!requests)
1462 requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1463
1464 for (i = 0; i < n; i++)
1465 {
1468 }
1469
1471
1472 }
1473
1475
1476 /* Are there any requests in the queue? If so, keep going. */
1478
1480
1481 for (request = requests; n > 0; request++, n--)
1482 RememberSyncRequest(&request->ftag, request->type);
1483
1485 } while (loop);
1486
1487 if (requests)
1488 pfree(requests);
1489}
#define Min(x, y)
Definition c.h:1131
#define CKPT_REQ_BATCH_SIZE
static CheckpointerShmemStruct * CheckpointerShmem
int i
Definition isn.c:77
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
@ LW_EXCLUSIVE
Definition lwlock.h:104
void pfree(void *pointer)
Definition mcxt.c:1619
void * palloc(Size size)
Definition mcxt.c:1390
#define AmCheckpointerProcess()
Definition miscadmin.h:395
#define START_CRIT_SECTION()
Definition miscadmin.h:152
#define END_CRIT_SECTION()
Definition miscadmin.h:154
static int fb(int x)
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition sync.c:488

References AmCheckpointerProcess, CheckpointerShmem, CKPT_REQ_BATCH_SIZE, END_CRIT_SECTION, fb(), CheckpointerShmemStruct::head, i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), CheckpointerShmemStruct::max_requests, Min, CheckpointerShmemStruct::num_requests, palloc(), pfree(), RememberSyncRequest(), CheckpointerShmemStruct::requests, and START_CRIT_SECTION.

Referenced by CheckpointerMain(), CheckpointWriteDelay(), CreateCheckPoint(), ProcessSyncRequests(), SyncPostCheckpoint(), and SyncPreCheckpoint().

◆ CheckArchiveTimeout()

static void CheckArchiveTimeout ( void  )
static

Definition at line 707 of file checkpointer.c.

708{
712
714 return;
715
716 now = (pg_time_t) time(NULL);
717
718 /* First we do a quick check using possibly-stale local state. */
720 return;
721
722 /*
723 * Update local state ... note that last_xlog_switch_time is the last time
724 * a switch was performed *or requested*.
725 */
727
729
730 /* Now we can do the real checks */
732 {
733 /*
734 * Switch segment only when "important" WAL has been logged since the
735 * last segment switch (last_switch_lsn points to end of segment
736 * switch occurred in).
737 */
739 {
741
742 /* mark switch as unimportant, avoids triggering checkpoints */
744
745 /*
746 * If the returned pointer points exactly to a segment boundary,
747 * assume nothing happened.
748 */
750 elog(DEBUG1, "write-ahead log switch forced (\"archive_timeout\"=%d)",
752 }
753
754 /*
755 * Update state in any case, so we don't retry constantly when the
756 * system is idle.
757 */
759 }
760}
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1613
#define Max(x, y)
Definition c.h:1125
static pg_time_t last_xlog_switch_time
#define DEBUG1
Definition elog.h:31
#define elog(elevel,...)
Definition elog.h:228
int64 pg_time_t
Definition pgtime.h:23
bool RecoveryInProgress(void)
Definition xlog.c:6835
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition xlog.c:8607
int wal_segment_size
Definition xlog.c:150
int XLogArchiveTimeout
Definition xlog.c:125
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
Definition xlog.c:7086
XLogRecPtr GetLastImportantRecPtr(void)
Definition xlog.c:7057
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
uint64 XLogRecPtr
Definition xlogdefs.h:21

References DEBUG1, elog, fb(), GetLastImportantRecPtr(), GetLastSegSwitchData(), last_xlog_switch_time, Max, now(), RecoveryInProgress(), RequestXLogSwitch(), wal_segment_size, XLogArchiveTimeout, and XLogSegmentOffset.

Referenced by CheckpointerMain(), and CheckpointWriteDelay().

◆ CheckpointerMain()

void CheckpointerMain ( const void startup_data,
size_t  startup_data_len 
)

Definition at line 206 of file checkpointer.c.

207{
210
212
214
216
217 /*
218 * Properly accept or ignore signals the postmaster might send us
219 *
220 * Note: we deliberately ignore SIGTERM, because during a standard Unix
221 * system shutdown cycle, init will SIGTERM all processes at once. We
222 * want to wait for the backends to exit, whereupon the postmaster will
223 * tell us it's okay to shut down (via SIGUSR2).
224 */
227 pqsignal(SIGTERM, PG_SIG_IGN); /* ignore SIGTERM */
228 /* SIGQUIT handler was already set up by InitPostmasterChild */
233
234 /*
235 * Reset some signals that are accepted by postmaster but not here
236 */
238
239 /*
240 * Initialize so that first time-driven event happens at the correct time.
241 */
243
244 /*
245 * Write out stats after shutdown. This needs to be called by exactly one
246 * process during a normal shutdown, and since checkpointer is shut down
247 * very late...
248 *
249 * While e.g. walsenders are active after the shutdown checkpoint has been
250 * written (and thus could produce more stats), checkpointer stays around
251 * after the shutdown checkpoint has been written. postmaster will only
252 * signal checkpointer to exit after all processes that could emit stats
253 * have been shut down.
254 */
256
257 /*
258 * Create a memory context that we will do all our work in. We do this so
259 * that we can reset the context during error recovery and thereby avoid
260 * possible memory leaks. Formerly this code just ran in
261 * TopMemoryContext, but resetting that would be a really bad idea.
262 */
264 "Checkpointer",
267
268 /*
269 * If an exception is encountered, processing resumes here.
270 *
271 * You might wonder why this isn't coded as an infinite loop around a
272 * PG_TRY construct. The reason is that this is the bottom of the
273 * exception stack, and so with PG_TRY there would be no exception handler
274 * in force at all during the CATCH part. By leaving the outermost setjmp
275 * always active, we have at least some chance of recovering from an error
276 * during error recovery. (If we get into an infinite loop thereby, it
277 * will soon be stopped by overflow of elog.c's internal state stack.)
278 *
279 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
280 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
281 * signals other than SIGQUIT will be blocked until we complete error
282 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
283 * call redundant, but it is not since InterruptPending might be set
284 * already.
285 */
286 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
287 {
288 /* Since not using PG_TRY, must reset error stack by hand */
290
291 /* Prevent interrupts while cleaning up */
293
294 /* Report the error to the server log */
296
297 /*
298 * These operations are really just a minimal subset of
299 * AbortTransaction(). We don't have very many resources to worry
300 * about in checkpointer, but we do have LWLocks, buffers, and temp
301 * files.
302 */
309 AtEOXact_Buffers(false);
311 AtEOXact_Files(false);
312 AtEOXact_HashTables(false);
313
314 /* Warn any waiting backends that the checkpoint failed. */
315 if (ckpt_active)
316 {
321
323
324 ckpt_active = false;
325 }
326
327 /*
328 * Now return to normal top-level context and clear ErrorContext for
329 * next time.
330 */
333
334 /* Flush any leaked data in the top-level context */
336
337 /* Now we can allow interrupts again */
339
340 /*
341 * Sleep at least 1 second after any error. A write error is likely
342 * to be repeated, and we don't want to be filling the error logs as
343 * fast as we can.
344 */
345 pg_usleep(1000000L);
346 }
347
348 /* We can now handle ereport(ERROR) */
350
351 /*
352 * Unblock signals (they were blocked when the postmaster forked us)
353 */
355
356 /*
357 * Ensure all shared memory values are set correctly for the config. Doing
358 * this here ensures no race conditions from other concurrent updaters.
359 */
361
362 /*
363 * Loop until we've been asked to write the shutdown checkpoint or
364 * terminate.
365 */
366 for (;;)
367 {
368 bool do_checkpoint = false;
369 int flags = 0;
371 int elapsed_secs;
372 int cur_timeout;
373 bool chkpt_or_rstpt_requested = false;
374 bool chkpt_or_rstpt_timed = false;
375
376 /* Clear any already-pending wakeups */
378
379 /*
380 * Process any requests or signals received recently.
381 */
383
386 break;
387
388 /*
389 * Detect a pending checkpoint request by checking whether the flags
390 * word in shared memory is nonzero. We shouldn't need to acquire the
391 * ckpt_lck for this.
392 */
393 if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
394 {
395 do_checkpoint = true;
397 }
398
399 /*
400 * Force a checkpoint if too much time has elapsed since the last one.
401 * Note that we count a timed checkpoint in stats only when this
402 * occurs without an external request, but we set the CAUSE_TIME flag
403 * bit even if there is also an external request.
404 */
405 now = (pg_time_t) time(NULL);
408 {
409 if (!do_checkpoint)
411 do_checkpoint = true;
412 flags |= CHECKPOINT_CAUSE_TIME;
413 }
414
415 /*
416 * Do a checkpoint if requested.
417 */
418 if (do_checkpoint)
419 {
420 bool ckpt_performed = false;
421 bool do_restartpoint;
422
423 /* Check if we should perform a checkpoint or a restartpoint. */
425
426 /*
427 * Atomically fetch the request flags to figure out what kind of a
428 * checkpoint we should perform, and increase the started-counter
429 * to acknowledge that we've started a new checkpoint.
430 */
436
438
439 /*
440 * The end-of-recovery checkpoint is a real checkpoint that's
441 * performed while we're still in recovery.
442 */
443 if (flags & CHECKPOINT_END_OF_RECOVERY)
444 do_restartpoint = false;
445
447 {
448 chkpt_or_rstpt_timed = false;
449 if (do_restartpoint)
451 else
453 }
454
456 {
458 if (do_restartpoint)
460 else
462 }
463
464 /*
465 * We will warn if (a) too soon since last checkpoint (whatever
466 * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
467 * since the last checkpoint start. Note in particular that this
468 * implementation will not generate warnings caused by
469 * CheckPointTimeout < CheckPointWarning.
470 */
471 if (!do_restartpoint &&
472 (flags & CHECKPOINT_CAUSE_XLOG) &&
474 ereport(LOG,
475 (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
476 "checkpoints are occurring too frequently (%d seconds apart)",
479 errhint("Consider increasing the configuration parameter \"%s\".", "max_wal_size")));
480
481 /*
482 * Initialize checkpointer-private variables used during
483 * checkpoint.
484 */
485 ckpt_active = true;
486 if (do_restartpoint)
488 else
492
493 /*
494 * Do the checkpoint.
495 */
496 if (!do_restartpoint)
498 else
500
501 /*
502 * After any checkpoint, free all smgr objects. Otherwise we
503 * would never do so for dropped relations, as the checkpointer
504 * does not process shared invalidation messages or call
505 * AtEOXact_SMgr().
506 */
508
509 /*
510 * Indicate checkpoint completion to any waiting backends.
511 */
515
517
518 if (!do_restartpoint)
519 {
520 /*
521 * Note we record the checkpoint start time not end time as
522 * last_checkpoint_time. This is so that time-driven
523 * checkpoints happen at a predictable spacing.
524 */
526
527 if (ckpt_performed)
529 }
530 else
531 {
532 if (ckpt_performed)
533 {
534 /*
535 * The same as for checkpoint. Please see the
536 * corresponding comment.
537 */
539
541 }
542 else
543 {
544 /*
545 * We were not able to perform the restartpoint
546 * (checkpoints throw an ERROR in case of error). Most
547 * likely because we have not received any new checkpoint
548 * WAL records since the last restartpoint. Try again in
549 * 15 s.
550 */
552 }
553 }
554
555 ckpt_active = false;
556
557 /*
558 * We may have received an interrupt during the checkpoint and the
559 * latch might have been reset (e.g. in CheckpointWriteDelay).
560 */
563 break;
564 }
565
566 /*
567 * Disable logical decoding if someone requested it. See comments atop
568 * logicalctl.c.
569 */
571
572 /* Check for archive_timeout and switch xlog files if necessary. */
574
575 /* Report pending statistics to the cumulative stats system */
577 pgstat_report_wal(true);
578
579 /*
580 * If any checkpoint flags have been set, redo the loop to handle the
581 * checkpoint without sleeping.
582 */
583 if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
584 continue;
585
586 /*
587 * Sleep until we are signaled or it's time for another checkpoint or
588 * xlog file switch.
589 */
590 now = (pg_time_t) time(NULL);
593 continue; /* no sleep for us ... */
596 {
599 continue; /* no sleep for us ... */
601 }
602
605 cur_timeout * 1000L /* convert to ms */ ,
607 }
608
609 /*
610 * From here on, elog(ERROR) should end with exit(1), not send control
611 * back to the sigsetjmp block above.
612 */
613 ExitOnAnyError = true;
614
616 {
617 /*
618 * Close down the database.
619 *
620 * Since ShutdownXLOG() creates restartpoint or checkpoint, and
621 * updates the statistics, increment the checkpoint request and flush
622 * out pending statistic.
623 */
625 ShutdownXLOG(0, 0);
627 pgstat_report_wal(true);
628
629 /*
630 * Tell postmaster that we're done.
631 */
633 ShutdownXLOGPending = false;
634 }
635
636 /*
637 * Wait until we're asked to shut down. By separating the writing of the
638 * shutdown checkpoint from checkpointer exiting, checkpointer can perform
639 * some should-be-as-late-as-possible work like writing out stats.
640 */
641 for (;;)
642 {
643 /* Clear any already-pending wakeups */
645
647
649 break;
650
653 0,
655 }
656
657 /* Normal exit from the checkpointer is here */
658 proc_exit(0); /* done */
659}
void pgaio_error_cleanup(void)
Definition aio.c:1175
void AuxiliaryProcessMainCommon(void)
Definition auxprocess.c:41
sigset_t UnBlockSig
Definition pqsignal.c:22
void AtEOXact_Buffers(bool isCommit)
Definition bufmgr.c:4222
void UnlockBuffers(void)
Definition bufmgr.c:5875
#define Assert(condition)
Definition c.h:1002
static void UpdateSharedMemoryConfig(void)
static XLogRecPtr ckpt_start_recptr
static void ReqShutdownXLOG(SIGNAL_ARGS)
static void CheckArchiveTimeout(void)
static double ckpt_cached_elapsed
static bool ckpt_active
static void ProcessCheckpointerInterrupts(void)
static volatile sig_atomic_t ShutdownXLOGPending
void AbsorbSyncRequests(void)
int CheckPointWarning
int CheckPointTimeout
static pg_time_t last_checkpoint_time
static pg_time_t ckpt_start_time
bool ConditionVariableCancelSleep(void)
void ConditionVariableBroadcast(ConditionVariable *cv)
void AtEOXact_HashTables(bool isCommit)
Definition dynahash.c:1864
void EmitErrorReport(void)
Definition elog.c:1883
ErrorContextCallback * error_context_stack
Definition elog.c:100
void FlushErrorState(void)
Definition elog.c:2063
sigjmp_buf * PG_exception_stack
Definition elog.c:102
#define LOG
Definition elog.h:32
int errhint(const char *fmt,...) pg_attribute_printf(1
int int int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
#define ereport(elevel,...)
Definition elog.h:152
void AtEOXact_Files(bool isCommit)
Definition fd.c:3212
int MyProcPid
Definition globals.c:49
bool ExitOnAnyError
Definition globals.c:125
struct Latch * MyLatch
Definition globals.c:65
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition interrupt.c:104
volatile sig_atomic_t ShutdownRequestPending
Definition interrupt.c:28
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition interrupt.c:61
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
void proc_exit(int code)
Definition ipc.c:105
void ResetLatch(Latch *latch)
Definition latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition latch.c:172
void DisableLogicalDecodingIfNecessary(void)
Definition logicalctl.c:450
void LWLockReleaseAll(void)
Definition lwlock.c:1866
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
MemoryContext TopMemoryContext
Definition mcxt.c:167
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h:138
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
void pgstat_before_server_shutdown(int code, Datum arg)
Definition pgstat.c:590
void pgstat_report_checkpointer(void)
PgStat_CheckpointerStats PendingCheckpointerStats
void pgstat_report_wal(bool force)
Definition pgstat_wal.c:46
void SendPostmasterSignal(PMSignalReason reason)
Definition pmsignal.c:164
@ PMSIGNAL_XLOG_IS_SHUTDOWN
Definition pmsignal.h:45
#define pqsignal
Definition port.h:548
#define PG_SIG_IGN
Definition port.h:552
#define PG_SIG_DFL
Definition port.h:551
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:696
void ReleaseAuxProcessResources(bool isCommit)
Definition resowner.c:1026
void pg_usleep(long microsec)
Definition signal.c:53
void smgrdestroyall(void)
Definition smgr.c:386
void AtEOXact_SMgr(void)
Definition smgr.c:1017
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56
ConditionVariable done_cv
ConditionVariable start_cv
PgStat_Counter restartpoints_requested
Definition pgstat.h:266
PgStat_Counter num_requested
Definition pgstat.h:263
PgStat_Counter num_performed
Definition pgstat.h:264
PgStat_Counter restartpoints_timed
Definition pgstat.h:265
PgStat_Counter num_timed
Definition pgstat.h:262
PgStat_Counter restartpoints_performed
Definition pgstat.h:267
static void pgstat_report_wait_end(void)
Definition wait_event.h:83
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET
#define SIGCHLD
Definition win32_port.h:168
#define SIGHUP
Definition win32_port.h:158
#define SIGPIPE
Definition win32_port.h:163
#define SIGUSR1
Definition win32_port.h:170
#define SIGALRM
Definition win32_port.h:164
#define SIGUSR2
Definition win32_port.h:171
bool CreateRestartPoint(int flags)
Definition xlog.c:8129
XLogRecPtr GetInsertRecPtr(void)
Definition xlog.c:6983
void ShutdownXLOG(int code, Datum arg)
Definition xlog.c:7103
bool CreateCheckPoint(int flags)
Definition xlog.c:7400
#define CHECKPOINT_CAUSE_XLOG
Definition xlog.h:160
#define CHECKPOINT_END_OF_RECOVERY
Definition xlog.h:152
#define CHECKPOINT_CAUSE_TIME
Definition xlog.h:161
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)

References AbsorbSyncRequests(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), AuxiliaryProcessMainCommon(), before_shmem_exit(), CheckArchiveTimeout(), CHECKPOINT_CAUSE_TIME, CHECKPOINT_CAUSE_XLOG, CHECKPOINT_END_OF_RECOVERY, CheckpointerShmemStruct::checkpointer_pid, CheckpointerShmem, CheckPointTimeout, CheckPointWarning, ckpt_active, ckpt_cached_elapsed, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_failed, CheckpointerShmemStruct::ckpt_flags, CheckpointerShmemStruct::ckpt_lck, ckpt_start_recptr, ckpt_start_time, CheckpointerShmemStruct::ckpt_started, ConditionVariableBroadcast(), ConditionVariableCancelSleep(), CreateCheckPoint(), CreateRestartPoint(), DisableLogicalDecodingIfNecessary(), CheckpointerShmemStruct::done_cv, EmitErrorReport(), ereport, errhint(), errmsg_plural(), error_context_stack, ExitOnAnyError, fb(), FlushErrorState(), GetInsertRecPtr(), GetXLogReplayRecPtr(), HOLD_INTERRUPTS, last_checkpoint_time, last_xlog_switch_time, LOG, LWLockReleaseAll(), MemoryContextReset(), MemoryContextSwitchTo(), Min, MyLatch, MyProcPid, now(), PgStat_CheckpointerStats::num_performed, PgStat_CheckpointerStats::num_requested, PgStat_CheckpointerStats::num_timed, PendingCheckpointerStats, PG_exception_stack, PG_SIG_DFL, PG_SIG_IGN, pg_usleep(), pgaio_error_cleanup(), pgstat_before_server_shutdown(), pgstat_report_checkpointer(), pgstat_report_wait_end(), pgstat_report_wal(), PMSIGNAL_XLOG_IS_SHUTDOWN, pqsignal, proc_exit(), ProcessCheckpointerInterrupts(), procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ReqShutdownXLOG(), ResetLatch(), PgStat_CheckpointerStats::restartpoints_performed, PgStat_CheckpointerStats::restartpoints_requested, PgStat_CheckpointerStats::restartpoints_timed, RESUME_INTERRUPTS, SendPostmasterSignal(), ShutdownRequestPending, ShutdownXLOG(), ShutdownXLOGPending, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrdestroyall(), SpinLockAcquire(), SpinLockRelease(), CheckpointerShmemStruct::start_cv, TopMemoryContext, UnBlockSig, UnlockBuffers(), UpdateSharedMemoryConfig(), WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, and XLogArchiveTimeout.

◆ CheckpointerShmemInit()

◆ CheckpointerShmemRequest()

static void CheckpointerShmemRequest ( void arg)
static

Definition at line 961 of file checkpointer.c.

962{
963 Size size;
964
965 /*
966 * The size of the requests[] array is arbitrarily set equal to NBuffers.
967 * But there is a cap of MAX_CHECKPOINT_REQUESTS to prevent accumulating
968 * too many checkpoint requests in the ring buffer.
969 */
970 size = offsetof(CheckpointerShmemStruct, requests);
971 size = add_size(size, mul_size(Min(NBuffers,
973 sizeof(CheckpointerRequest)));
974 ShmemRequestStruct(.name = "Checkpointer Data",
975 .size = size,
976 .ptr = (void **) &CheckpointerShmem,
977 );
978}
size_t Size
Definition c.h:748
Size add_size(Size s1, Size s2)
Definition mcxt.c:1733
Size mul_size(Size s1, Size s2)
Definition mcxt.c:1752
#define ShmemRequestStruct(...)
Definition shmem.h:176
const char * name

References add_size(), CheckpointerShmem, fb(), MAX_CHECKPOINT_REQUESTS, Min, mul_size(), name, NBuffers, and ShmemRequestStruct.

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 795 of file checkpointer.c.

796{
798
799 /* Do nothing if checkpoint is being executed by non-checkpointer process */
801 return;
802
803 /*
804 * Perform the usual duties and take a nap, unless we're behind schedule,
805 * in which case we just try to catch up as quickly as possible.
806 */
807 if (!(flags & CHECKPOINT_FAST) &&
812 {
814 {
815 ConfigReloadPending = false;
817 /* update shmem copies of config variables */
819 }
820
823
825
826 /* Report interim statistics to the cumulative stats system */
828
829 /*
830 * This sleep used to be connected to bgwriter_delay, typically 200ms.
831 * That resulted in more frequent wakeups if not much work to do.
832 * Checkpointer and bgwriter are no longer related so take the Big
833 * Sleep.
834 */
836 100,
839 }
840 else if (--absorb_counter <= 0)
841 {
842 /*
843 * Absorb pending fsync requests after each WRITES_PER_ABSORB write
844 * operations even when we don't sleep, to prevent overflow of the
845 * fsync request queue.
846 */
849 }
850
851 /* Check for barrier events. */
854}
static bool FastCheckpointRequested(void)
static bool IsCheckpointOnSchedule(double progress)
#define WRITES_PER_ABSORB
volatile sig_atomic_t ProcSignalBarrierPending
Definition globals.c:40
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
@ PGC_SIGHUP
Definition guc.h:75
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
static int progress
Definition pgbench.c:262
void ProcessProcSignalBarrier(void)
Definition procsignal.c:511
#define CHECKPOINT_FAST
Definition xlog.h:153

References AbsorbSyncRequests(), AmCheckpointerProcess, CheckArchiveTimeout(), CHECKPOINT_FAST, ConfigReloadPending, FastCheckpointRequested(), fb(), IsCheckpointOnSchedule(), MyLatch, PGC_SIGHUP, pgstat_report_checkpointer(), ProcessConfigFile(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, progress, ResetLatch(), ShutdownRequestPending, ShutdownXLOGPending, UpdateSharedMemoryConfig(), WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, and WRITES_PER_ABSORB.

Referenced by BufferSync().

◆ CompactCheckpointerRequestQueue()

static bool CompactCheckpointerRequestQueue ( void  )
static

Definition at line 1284 of file checkpointer.c.

1285{
1287 {
1289 int ring_idx;
1290 };
1291
1292 int n;
1293 int num_skipped = 0;
1294 int head;
1295 int max_requests;
1296 int num_requests;
1297 int read_idx,
1298 write_idx;
1299 HASHCTL ctl;
1300 HTAB *htab;
1301 bool *skip_slot;
1302
1303 /* must hold CheckpointerCommLock in exclusive mode */
1305
1306 /* Avoid memory allocations in a critical section. */
1307 if (CritSectionCount > 0)
1308 return false;
1309
1310 max_requests = CheckpointerShmem->max_requests;
1311 num_requests = CheckpointerShmem->num_requests;
1312
1313 /* Initialize skip_slot array */
1314 skip_slot = palloc0_array(bool, max_requests);
1315
1316 head = CheckpointerShmem->head;
1317
1318 /* Initialize temporary hash table */
1319 ctl.keysize = sizeof(CheckpointerRequest);
1320 ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
1322
1323 htab = hash_create("CompactCheckpointerRequestQueue",
1325 &ctl,
1327
1328 /*
1329 * The basic idea here is that a request can be skipped if it's followed
1330 * by a later, identical request. It might seem more sensible to work
1331 * backwards from the end of the queue and check whether a request is
1332 * *preceded* by an earlier, identical request, in the hopes of doing less
1333 * copying. But that might change the semantics, if there's an
1334 * intervening SYNC_FORGET_REQUEST or SYNC_FILTER_REQUEST, so we do it
1335 * this way. It would be possible to be even smarter if we made the code
1336 * below understand the specific semantics of such requests (it could blow
1337 * away preceding entries that would end up being canceled anyhow), but
1338 * it's not clear that the extra complexity would buy us anything.
1339 */
1340 read_idx = head;
1341 for (n = 0; n < num_requests; n++)
1342 {
1345 bool found;
1346
1347 /*
1348 * We use the request struct directly as a hashtable key. This
1349 * assumes that any padding bytes in the structs are consistently the
1350 * same, which should be okay because we zeroed them in
1351 * CheckpointerShmemInit. Note also that RelFileLocator had better
1352 * contain no pad bytes.
1353 */
1356 if (found)
1357 {
1358 /* Duplicate, so mark the previous occurrence as skippable */
1359 skip_slot[slotmap->ring_idx] = true;
1360 num_skipped++;
1361 }
1362 /* Remember slot containing latest occurrence of this request value */
1363 slotmap->ring_idx = read_idx;
1364
1365 /* Move to the next request in the ring buffer */
1366 read_idx = (read_idx + 1) % max_requests;
1367 }
1368
1369 /* Done with the hash table. */
1371
1372 /* If no duplicates, we're out of luck. */
1373 if (!num_skipped)
1374 {
1376 return false;
1377 }
1378
1379 /* We found some duplicates; remove them. */
1380 read_idx = write_idx = head;
1381 for (n = 0; n < num_requests; n++)
1382 {
1383 /* If this slot is NOT skipped, keep it */
1384 if (!skip_slot[read_idx])
1385 {
1386 /* If the read and write positions are different, copy the request */
1387 if (write_idx != read_idx)
1390
1391 /* Advance the write position */
1392 write_idx = (write_idx + 1) % max_requests;
1393 }
1394
1395 read_idx = (read_idx + 1) % max_requests;
1396 }
1397
1398 /*
1399 * Update ring buffer state: head remains the same, tail moves, count
1400 * decreases
1401 */
1404
1406 (errmsg_internal("compacted fsync request queue from %d entries to %d entries",
1407 num_requests, CheckpointerShmem->num_requests)));
1408
1409 /* Cleanup. */
1411 return true;
1412}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define palloc0_array(type, count)
Definition fe_memutils.h:92
volatile uint32 CritSectionCount
Definition globals.c:45
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
bool LWLockHeldByMe(LWLock *lock)
Definition lwlock.c:1885
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
tree ctl
Definition radixtree.h:1838

References Assert, CheckpointerShmem, CritSectionCount, ctl, CurrentMemoryContext, DEBUG1, ereport, errmsg_internal(), fb(), HASH_BLOBS, HASH_CONTEXT, hash_create(), hash_destroy(), HASH_ELEM, HASH_ENTER, hash_search(), CheckpointerShmemStruct::head, LWLockHeldByMe(), CheckpointerShmemStruct::max_requests, CheckpointerShmemStruct::num_requests, palloc0_array, pfree(), CheckpointerShmemStruct::requests, and CheckpointerShmemStruct::tail.

Referenced by ForwardSyncRequest().

◆ ExecCheckpoint()

void ExecCheckpoint ( ParseState pstate,
CheckPointStmt stmt 
)

Definition at line 1001 of file checkpointer.c.

1002{
1003 bool fast = true;
1004 bool unlogged = false;
1005
1006 foreach_ptr(DefElem, opt, stmt->options)
1007 {
1008 if (strcmp(opt->defname, "mode") == 0)
1009 {
1010 char *mode = defGetString(opt);
1011
1012 if (strcmp(mode, "spread") == 0)
1013 fast = false;
1014 else if (strcmp(mode, "fast") != 0)
1015 ereport(ERROR,
1017 errmsg("unrecognized value for %s option \"%s\": \"%s\"",
1018 "CHECKPOINT", "mode", mode),
1019 parser_errposition(pstate, opt->location)));
1020 }
1021 else if (strcmp(opt->defname, "flush_unlogged") == 0)
1022 unlogged = defGetBoolean(opt);
1023 else
1024 ereport(ERROR,
1026 errmsg("unrecognized %s option \"%s\"",
1027 "CHECKPOINT", opt->defname),
1028 parser_errposition(pstate, opt->location)));
1029 }
1030
1032 ereport(ERROR,
1034 /* translator: %s is name of an SQL command (e.g., CHECKPOINT) */
1035 errmsg("permission denied to execute %s command",
1036 "CHECKPOINT"),
1037 errdetail("Only roles with privileges of the \"%s\" role may execute this command.",
1038 "pg_checkpoint")));
1039
1041 (fast ? CHECKPOINT_FAST : 0) |
1044}
bool has_privs_of_role(Oid member, Oid role)
Definition acl.c:5317
void RequestCheckpoint(int flags)
char * defGetString(DefElem *def)
Definition define.c:34
bool defGetBoolean(DefElem *def)
Definition define.c:93
int errcode(int sqlerrcode)
Definition elog.c:875
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define stmt
Oid GetUserId(void)
Definition miscinit.c:470
static char * errmsg
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
static PgChecksumMode mode
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
#define CHECKPOINT_FLUSH_UNLOGGED
Definition xlog.h:155
#define CHECKPOINT_FORCE
Definition xlog.h:154
#define CHECKPOINT_WAIT
Definition xlog.h:157

References CHECKPOINT_FAST, CHECKPOINT_FLUSH_UNLOGGED, CHECKPOINT_FORCE, CHECKPOINT_WAIT, defGetBoolean(), defGetString(), ereport, errcode(), errdetail(), errmsg, ERROR, fb(), foreach_ptr, GetUserId(), has_privs_of_role(), mode, parser_errposition(), RecoveryInProgress(), RequestCheckpoint(), and stmt.

Referenced by standard_ProcessUtility().

◆ FastCheckpointRequested()

static bool FastCheckpointRequested ( void  )
static

Definition at line 768 of file checkpointer.c.

769{
771
772 /*
773 * We don't need to acquire the ckpt_lck in this case because we're only
774 * looking at a single flag bit.
775 */
776 if (cps->ckpt_flags & CHECKPOINT_FAST)
777 return true;
778 return false;
779}

References CHECKPOINT_FAST, CheckpointerShmem, and fb().

Referenced by CheckpointWriteDelay().

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1514 of file checkpointer.c.

1515{
1516 static int ckpt_done = 0;
1517 int new_done;
1518 bool FirstCall = false;
1519
1523
1524 if (new_done != ckpt_done)
1525 FirstCall = true;
1526
1527 ckpt_done = new_done;
1528
1529 return FirstCall;
1530}

References CheckpointerShmem, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_lck, fb(), SpinLockAcquire(), and SpinLockRelease().

Referenced by BackgroundWriterMain().

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)

Definition at line 1213 of file checkpointer.c.

1214{
1216 bool too_full;
1217 int insert_pos;
1218
1219 if (!IsUnderPostmaster)
1220 return false; /* probably shouldn't even get here */
1221
1223 elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1224
1226
1227 /*
1228 * If the checkpointer isn't running or the request queue is full, the
1229 * backend will have to perform its own fsync request. But before forcing
1230 * that to happen, we can try to compact the request queue.
1231 */
1235 {
1237 return false;
1238 }
1239
1240 /* OK, insert request */
1243 request->ftag = *ftag;
1244 request->type = type;
1245
1248
1249 /* If queue is more than half full, nudge the checkpointer to empty it */
1252
1254
1255 /* ... but not till after we release the lock */
1256 if (too_full)
1257 {
1259
1260 if (checkpointerProc != INVALID_PROC_NUMBER)
1261 SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1262 }
1263
1264 return true;
1265}
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:232
static bool CompactCheckpointerRequestQueue(void)
bool IsUnderPostmaster
Definition globals.c:122
void SetLatch(Latch *latch)
Definition latch.c:290
#define GetPGProcByNumber(n)
Definition proc.h:506
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
int ProcNumber
Definition procnumber.h:24
PROC_HDR * ProcGlobal
Definition proc.c:74
pg_atomic_uint32 checkpointerProc
Definition proc.h:489
const char * type

References AmCheckpointerProcess, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerProc, CheckpointerShmem, CompactCheckpointerRequestQueue(), elog, ERROR, fb(), CheckpointerRequest::ftag, GetPGProcByNumber, INVALID_PROC_NUMBER, IsUnderPostmaster, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), CheckpointerShmemStruct::max_requests, CheckpointerShmemStruct::num_requests, pg_atomic_read_u32(), ProcGlobal, CheckpointerShmemStruct::requests, SetLatch(), CheckpointerShmemStruct::tail, and type.

Referenced by RegisterSyncRequest().

◆ IsCheckpointOnSchedule()

static bool IsCheckpointOnSchedule ( double  progress)
static

Definition at line 865 of file checkpointer.c.

866{
868 struct timeval now;
869 double elapsed_xlogs,
871
873
874 /* Scale progress according to checkpoint_completion_target. */
876
877 /*
878 * Check against the cached value first. Only do the more expensive
879 * calculations once we reach the target previously calculated. Since
880 * neither time or WAL insert pointer moves backwards, a freshly
881 * calculated value can only be greater than or equal to the cached value.
882 */
884 return false;
885
886 /*
887 * Check progress against WAL segments written and CheckPointSegments.
888 *
889 * We compare the current WAL insert location against the location
890 * computed before calling CreateCheckPoint. The code in XLogInsert that
891 * actually triggers a checkpoint when CheckPointSegments is exceeded
892 * compares against RedoRecPtr, so this is not completely accurate.
893 * However, it's good enough for our purposes, we're only calculating an
894 * estimate anyway.
895 *
896 * During recovery, we compare last replayed WAL record's location with
897 * the location computed before calling CreateRestartPoint. That maintains
898 * the same pacing as we have during checkpoints in normal operation, but
899 * we might exceed max_wal_size by a fair amount. That's because there can
900 * be a large gap between a checkpoint's redo-pointer and the checkpoint
901 * record itself, and we only start the restartpoint after we've seen the
902 * checkpoint record. (The gap is typically up to CheckPointSegments *
903 * checkpoint_completion_target where checkpoint_completion_target is the
904 * value that was in effect when the WAL was generated).
905 */
906 if (RecoveryInProgress())
908 else
912
914 {
916 return false;
917 }
918
919 /*
920 * Check progress against time elapsed and checkpoint_timeout.
921 */
924 now.tv_usec / 1000000.0) / CheckPointTimeout;
925
927 {
929 return false;
930 }
931
932 /* It looks like we're on schedule. */
933 return true;
934}
double CheckPointCompletionTarget
static double elapsed_time(instr_time *starttime)
Definition explain.c:1171
int gettimeofday(struct timeval *tp, void *tzp)
int CheckPointSegments
Definition xlog.c:163

References Assert, CheckPointCompletionTarget, CheckPointSegments, CheckPointTimeout, ckpt_active, ckpt_cached_elapsed, ckpt_start_recptr, ckpt_start_time, elapsed_time(), fb(), GetInsertRecPtr(), gettimeofday(), GetXLogReplayRecPtr(), now(), progress, RecoveryInProgress(), and wal_segment_size.

Referenced by CheckpointWriteDelay().

◆ ProcessCheckpointerInterrupts()

static void ProcessCheckpointerInterrupts ( void  )
static

Definition at line 665 of file checkpointer.c.

666{
669
671 {
672 ConfigReloadPending = false;
674
675 /*
676 * Checkpointer is the last process to shut down, so we ask it to hold
677 * the keys for a range of other tasks required most of which have
678 * nothing to do with checkpointing at all.
679 *
680 * For various reasons, some config values can change dynamically so
681 * the primary copy of them is held in shared memory to make sure all
682 * backends see the same value. We make Checkpointer responsible for
683 * updating the shared memory copy if the parameter setting changes
684 * because of SIGHUP.
685 */
687 }
688
689 /* Perform logging of memory contexts of this process */
692}
volatile sig_atomic_t LogMemoryContextPending
Definition globals.c:41
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1343

References ConfigReloadPending, LogMemoryContextPending, PGC_SIGHUP, ProcessConfigFile(), ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, and UpdateSharedMemoryConfig().

Referenced by CheckpointerMain().

◆ ReqShutdownXLOG()

static void ReqShutdownXLOG ( SIGNAL_ARGS  )
static

Definition at line 944 of file checkpointer.c.

945{
946 ShutdownXLOGPending = true;
948}

References MyLatch, SetLatch(), and ShutdownXLOGPending.

Referenced by CheckpointerMain().

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 1064 of file checkpointer.c.

1065{
1066 int ntries;
1067 int old_failed,
1069
1070 /*
1071 * If in a standalone backend, just do it ourselves.
1072 */
1074 {
1075 /*
1076 * There's no point in doing slow checkpoints in a standalone backend,
1077 * because there's no other backends the checkpoint could disrupt.
1078 */
1080
1081 /* Free all smgr objects, as CheckpointerMain() normally would. */
1083
1084 return;
1085 }
1086
1087 /*
1088 * Atomically set the request flags, and take a snapshot of the counters.
1089 * When we see ckpt_started > old_started, we know the flags we set here
1090 * have been seen by checkpointer.
1091 *
1092 * Note that we OR the flags with any existing flags, to avoid overriding
1093 * a "stronger" request by another backend. The flag senses must be
1094 * chosen to make this work!
1095 */
1097
1101
1103
1104 /*
1105 * Set checkpointer's latch to request checkpoint. It's possible that the
1106 * checkpointer hasn't started yet, so we will retry a few times if
1107 * needed. (Actually, more than a few times, since on slow or overloaded
1108 * buildfarm machines, it's been observed that the checkpointer can take
1109 * several seconds to start.) However, if not told to wait for the
1110 * checkpoint to occur, we consider failure to set the latch to be
1111 * nonfatal and merely LOG it. The checkpointer should see the request
1112 * when it does start, with or without the SetLatch().
1113 */
1114#define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
1115 for (ntries = 0;; ntries++)
1116 {
1118
1119 if (checkpointerProc == INVALID_PROC_NUMBER)
1120 {
1121 if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
1122 {
1123 elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
1124 "could not notify checkpoint: checkpointer is not running");
1125 break;
1126 }
1127 }
1128 else
1129 {
1130 SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1131 /* notified successfully */
1132 break;
1133 }
1134
1136 pg_usleep(100000L); /* wait 0.1 sec, then retry */
1137 }
1138
1139 /*
1140 * If requested, wait for completion. We detect completion according to
1141 * the algorithm given above.
1142 */
1143 if (flags & CHECKPOINT_WAIT)
1144 {
1145 int new_started,
1146 new_failed;
1147
1148 /* Wait for a new checkpoint to start. */
1150 for (;;)
1151 {
1155
1156 if (new_started != old_started)
1157 break;
1158
1161 }
1163
1164 /*
1165 * We are waiting for ckpt_done >= new_started, in a modulo sense.
1166 */
1168 for (;;)
1169 {
1170 int new_done;
1171
1176
1177 if (new_done - new_started >= 0)
1178 break;
1179
1182 }
1184
1185 if (new_failed != old_failed)
1186 ereport(ERROR,
1187 (errmsg("checkpoint request failed"),
1188 errhint("Consult recent messages in the server log for details.")));
1189 }
1190}
#define MAX_SIGNAL_TRIES
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
bool IsPostmasterEnvironment
Definition globals.c:121
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define CHECKPOINT_REQUESTED
Definition xlog.h:158

References CHECK_FOR_INTERRUPTS, CHECKPOINT_FAST, CHECKPOINT_REQUESTED, CHECKPOINT_WAIT, PROC_HDR::checkpointerProc, CheckpointerShmem, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_failed, CheckpointerShmemStruct::ckpt_flags, CheckpointerShmemStruct::ckpt_lck, CheckpointerShmemStruct::ckpt_started, ConditionVariableCancelSleep(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), CreateCheckPoint(), CheckpointerShmemStruct::done_cv, elog, ereport, errhint(), errmsg, ERROR, fb(), GetPGProcByNumber, INVALID_PROC_NUMBER, IsPostmasterEnvironment, LOG, MAX_SIGNAL_TRIES, pg_atomic_read_u32(), pg_usleep(), ProcGlobal, SetLatch(), smgrdestroyall(), SpinLockAcquire(), SpinLockRelease(), and CheckpointerShmemStruct::start_cv.

Referenced by CreateDatabaseUsingFileCopy(), do_pg_backup_start(), dropdb(), DropTableSpace(), ExecCheckpoint(), movedb(), PerformRecoveryXLogAction(), SetDataChecksumsOff(), SetDataChecksumsOn(), StartupXLOG(), XLogPageRead(), and XLogWrite().

◆ UpdateSharedMemoryConfig()

static void UpdateSharedMemoryConfig ( void  )
static

Definition at line 1495 of file checkpointer.c.

1496{
1497 /* update global shmem state for sync rep */
1499
1500 /*
1501 * If full_page_writes has been changed by SIGHUP, we update it in shared
1502 * memory and write an XLOG_FPW_CHANGE record.
1503 */
1505
1506 elog(DEBUG2, "checkpointer updated shared memory configuration values");
1507}
#define DEBUG2
Definition elog.h:30
void SyncRepUpdateSyncStandbysDefined(void)
Definition syncrep.c:970
void UpdateFullPageWrites(void)
Definition xlog.c:8755

References DEBUG2, elog, SyncRepUpdateSyncStandbysDefined(), and UpdateFullPageWrites().

Referenced by CheckpointerMain(), CheckpointWriteDelay(), and ProcessCheckpointerInterrupts().

◆ WakeupCheckpointer()

void WakeupCheckpointer ( void  )

Definition at line 1536 of file checkpointer.c.

1537{
1539
1540 if (checkpointerProc != INVALID_PROC_NUMBER)
1541 SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1542}

References PROC_HDR::checkpointerProc, GetPGProcByNumber, INVALID_PROC_NUMBER, pg_atomic_read_u32(), ProcGlobal, and SetLatch().

Referenced by RequestDisableLogicalDecoding(), and StartupXLOG().

Variable Documentation

◆ CheckPointCompletionTarget

double CheckPointCompletionTarget = 0.9

◆ CheckpointerShmem

◆ CheckpointerShmemCallbacks

const ShmemCallbacks CheckpointerShmemCallbacks
Initial value:
= {
.request_fn = CheckpointerShmemRequest,
}
static void CheckpointerShmemRequest(void *arg)
static void CheckpointerShmemInit(void *arg)

Definition at line 151 of file checkpointer.c.

151 {
152 .request_fn = CheckpointerShmemRequest,
153 .init_fn = CheckpointerShmemInit,
154};

◆ CheckPointTimeout

int CheckPointTimeout = 300

Definition at line 168 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

int CheckPointWarning = 30

Definition at line 169 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ ckpt_active

bool ckpt_active = false
static

Definition at line 175 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_cached_elapsed

double ckpt_cached_elapsed
static

Definition at line 181 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_recptr

XLogRecPtr ckpt_start_recptr
static

Definition at line 180 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_time

pg_time_t ckpt_start_time
static

Definition at line 179 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ last_checkpoint_time

pg_time_t last_checkpoint_time
static

Definition at line 183 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ last_xlog_switch_time

pg_time_t last_xlog_switch_time
static

Definition at line 184 of file checkpointer.c.

Referenced by CheckArchiveTimeout(), and CheckpointerMain().

◆ ShutdownXLOGPending

volatile sig_atomic_t ShutdownXLOGPending = false
static

Definition at line 176 of file checkpointer.c.

Referenced by CheckpointerMain(), CheckpointWriteDelay(), and ReqShutdownXLOG().