PostgreSQL Source Code git master
Data Structures | Macros | Functions | Variables
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 "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 "utils/acl.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/resowner.h"
Include dependency graph for checkpointer.c:

Go to the source code of this file.

Data Structures

 
 

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  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  CheckpointerShmemInit (void)
 
 
void  RequestCheckpoint (int flags)
 
 
void  AbsorbSyncRequests (void)
 
 

Variables

 
int  CheckPointTimeout = 300
 
int  CheckPointWarning = 30
 
 
static bool  ckpt_active = false
 
static volatile sig_atomic_t  ShutdownXLOGPending = false
 
 
 
static double  ckpt_cached_elapsed
 
 
 

Macro Definition Documentation

CKPT_REQ_BATCH_SIZE

#define CKPT_REQ_BATCH_SIZE   10000

Definition at line 149 of file checkpointer.c.

MAX_CHECKPOINT_REQUESTS

#define MAX_CHECKPOINT_REQUESTS   10000000

Definition at line 152 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 146 of file checkpointer.c.

Function Documentation

AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1429 of file checkpointer.c.

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

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

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

CheckArchiveTimeout()

static void CheckArchiveTimeout ( void  )
static

Definition at line 697 of file checkpointer.c.

698{
700 pg_time_t last_time;
701 XLogRecPtr last_switch_lsn;
702
704 return;
705
706 now = (pg_time_t) time(NULL);
707
708 /* First we do a quick check using possibly-stale local state. */
710 return;
711
712 /*
713 * Update local state ... note that last_xlog_switch_time is the last time
714 * a switch was performed *or requested*.
715 */
716 last_time = GetLastSegSwitchData(&last_switch_lsn);
717
719
720 /* Now we can do the real checks */
722 {
723 /*
724 * Switch segment only when "important" WAL has been logged since the
725 * last segment switch (last_switch_lsn points to end of segment
726 * switch occurred in).
727 */
728 if (GetLastImportantRecPtr() > last_switch_lsn)
729 {
730 XLogRecPtr switchpoint;
731
732 /* mark switch as unimportant, avoids triggering checkpoints */
733 switchpoint = RequestXLogSwitch(true);
734
735 /*
736 * If the returned pointer points exactly to a segment boundary,
737 * assume nothing happened.
738 */
739 if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
740 elog(DEBUG1, "write-ahead log switch forced (\"archive_timeout\"=%d)",
742 }
743
744 /*
745 * Update state in any case, so we don't retry constantly when the
746 * system is idle.
747 */
749 }
750}
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
#define Max(x, y)
Definition: c.h:997
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:173
#define DEBUG1
Definition: elog.h:30
#define elog(elevel,...)
Definition: elog.h:226
int64 pg_time_t
Definition: pgtime.h:23
bool RecoveryInProgress(void)
Definition: xlog.c:6386
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:8110
int wal_segment_size
Definition: xlog.c:144
int XLogArchiveTimeout
Definition: xlog.c:119
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
Definition: xlog.c:6637
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:6608
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
Definition: xlog_internal.h:106
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References DEBUG1, elog, 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 195 of file checkpointer.c.

196{
197 sigjmp_buf local_sigjmp_buf;
198 MemoryContext checkpointer_context;
199
200 Assert(startup_data_len == 0);
201
204
206
207 /*
208 * Properly accept or ignore signals the postmaster might send us
209 *
210 * Note: we deliberately ignore SIGTERM, because during a standard Unix
211 * system shutdown cycle, init will SIGTERM all processes at once. We
212 * want to wait for the backends to exit, whereupon the postmaster will
213 * tell us it's okay to shut down (via SIGUSR2).
214 */
216 pqsignal(SIGINT, ReqShutdownXLOG);
217 pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
218 /* SIGQUIT handler was already set up by InitPostmasterChild */
219 pqsignal(SIGALRM, SIG_IGN);
220 pqsignal(SIGPIPE, SIG_IGN);
223
224 /*
225 * Reset some signals that are accepted by postmaster but not here
226 */
227 pqsignal(SIGCHLD, SIG_DFL);
228
229 /*
230 * Initialize so that first time-driven event happens at the correct time.
231 */
233
234 /*
235 * Write out stats after shutdown. This needs to be called by exactly one
236 * process during a normal shutdown, and since checkpointer is shut down
237 * very late...
238 *
239 * While e.g. walsenders are active after the shutdown checkpoint has been
240 * written (and thus could produce more stats), checkpointer stays around
241 * after the shutdown checkpoint has been written. postmaster will only
242 * signal checkpointer to exit after all processes that could emit stats
243 * have been shut down.
244 */
246
247 /*
248 * Create a memory context that we will do all our work in. We do this so
249 * that we can reset the context during error recovery and thereby avoid
250 * possible memory leaks. Formerly this code just ran in
251 * TopMemoryContext, but resetting that would be a really bad idea.
252 */
253 checkpointer_context = AllocSetContextCreate(TopMemoryContext,
254 "Checkpointer",
256 MemoryContextSwitchTo(checkpointer_context);
257
258 /*
259 * If an exception is encountered, processing resumes here.
260 *
261 * You might wonder why this isn't coded as an infinite loop around a
262 * PG_TRY construct. The reason is that this is the bottom of the
263 * exception stack, and so with PG_TRY there would be no exception handler
264 * in force at all during the CATCH part. By leaving the outermost setjmp
265 * always active, we have at least some chance of recovering from an error
266 * during error recovery. (If we get into an infinite loop thereby, it
267 * will soon be stopped by overflow of elog.c's internal state stack.)
268 *
269 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
270 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
271 * signals other than SIGQUIT will be blocked until we complete error
272 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
273 * call redundant, but it is not since InterruptPending might be set
274 * already.
275 */
276 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
277 {
278 /* Since not using PG_TRY, must reset error stack by hand */
279 error_context_stack = NULL;
280
281 /* Prevent interrupts while cleaning up */
283
284 /* Report the error to the server log */
286
287 /*
288 * These operations are really just a minimal subset of
289 * AbortTransaction(). We don't have very many resources to worry
290 * about in checkpointer, but we do have LWLocks, buffers, and temp
291 * files.
292 */
299 AtEOXact_Buffers(false);
301 AtEOXact_Files(false);
302 AtEOXact_HashTables(false);
303
304 /* Warn any waiting backends that the checkpoint failed. */
305 if (ckpt_active)
306 {
311
313
314 ckpt_active = false;
315 }
316
317 /*
318 * Now return to normal top-level context and clear ErrorContext for
319 * next time.
320 */
321 MemoryContextSwitchTo(checkpointer_context);
323
324 /* Flush any leaked data in the top-level context */
325 MemoryContextReset(checkpointer_context);
326
327 /* Now we can allow interrupts again */
329
330 /*
331 * Sleep at least 1 second after any error. A write error is likely
332 * to be repeated, and we don't want to be filling the error logs as
333 * fast as we can.
334 */
335 pg_usleep(1000000L);
336 }
337
338 /* We can now handle ereport(ERROR) */
339 PG_exception_stack = &local_sigjmp_buf;
340
341 /*
342 * Unblock signals (they were blocked when the postmaster forked us)
343 */
344 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
345
346 /*
347 * Ensure all shared memory values are set correctly for the config. Doing
348 * this here ensures no race conditions from other concurrent updaters.
349 */
351
352 /*
353 * Advertise our proc number that backends can use to wake us up while
354 * we're sleeping.
355 */
357
358 /*
359 * Loop until we've been asked to write the shutdown checkpoint or
360 * terminate.
361 */
362 for (;;)
363 {
364 bool do_checkpoint = false;
365 int flags = 0;
367 int elapsed_secs;
368 int cur_timeout;
369 bool chkpt_or_rstpt_requested = false;
370 bool chkpt_or_rstpt_timed = false;
371
372 /* Clear any already-pending wakeups */
374
375 /*
376 * Process any requests or signals received recently.
377 */
379
382 break;
383
384 /*
385 * Detect a pending checkpoint request by checking whether the flags
386 * word in shared memory is nonzero. We shouldn't need to acquire the
387 * ckpt_lck for this.
388 */
389 if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
390 {
391 do_checkpoint = true;
392 chkpt_or_rstpt_requested = true;
393 }
394
395 /*
396 * Force a checkpoint if too much time has elapsed since the last one.
397 * Note that we count a timed checkpoint in stats only when this
398 * occurs without an external request, but we set the CAUSE_TIME flag
399 * bit even if there is also an external request.
400 */
401 now = (pg_time_t) time(NULL);
402 elapsed_secs = now - last_checkpoint_time;
403 if (elapsed_secs >= CheckPointTimeout)
404 {
405 if (!do_checkpoint)
406 chkpt_or_rstpt_timed = true;
407 do_checkpoint = true;
408 flags |= CHECKPOINT_CAUSE_TIME;
409 }
410
411 /*
412 * Do a checkpoint if requested.
413 */
414 if (do_checkpoint)
415 {
416 bool ckpt_performed = false;
417 bool do_restartpoint;
418
419 /* Check if we should perform a checkpoint or a restartpoint. */
420 do_restartpoint = RecoveryInProgress();
421
422 /*
423 * Atomically fetch the request flags to figure out what kind of a
424 * checkpoint we should perform, and increase the started-counter
425 * to acknowledge that we've started a new checkpoint.
426 */
432
434
435 /*
436 * The end-of-recovery checkpoint is a real checkpoint that's
437 * performed while we're still in recovery.
438 */
439 if (flags & CHECKPOINT_END_OF_RECOVERY)
440 do_restartpoint = false;
441
442 if (chkpt_or_rstpt_timed)
443 {
444 chkpt_or_rstpt_timed = false;
445 if (do_restartpoint)
447 else
449 }
450
451 if (chkpt_or_rstpt_requested)
452 {
453 chkpt_or_rstpt_requested = false;
454 if (do_restartpoint)
456 else
458 }
459
460 /*
461 * We will warn if (a) too soon since last checkpoint (whatever
462 * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
463 * since the last checkpoint start. Note in particular that this
464 * implementation will not generate warnings caused by
465 * CheckPointTimeout < CheckPointWarning.
466 */
467 if (!do_restartpoint &&
468 (flags & CHECKPOINT_CAUSE_XLOG) &&
469 elapsed_secs < CheckPointWarning)
470 ereport(LOG,
471 (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
472 "checkpoints are occurring too frequently (%d seconds apart)",
473 elapsed_secs,
474 elapsed_secs),
475 errhint("Consider increasing the configuration parameter \"%s\".", "max_wal_size")));
476
477 /*
478 * Initialize checkpointer-private variables used during
479 * checkpoint.
480 */
481 ckpt_active = true;
482 if (do_restartpoint)
484 else
488
489 /*
490 * Do the checkpoint.
491 */
492 if (!do_restartpoint)
493 ckpt_performed = CreateCheckPoint(flags);
494 else
495 ckpt_performed = CreateRestartPoint(flags);
496
497 /*
498 * After any checkpoint, free all smgr objects. Otherwise we
499 * would never do so for dropped relations, as the checkpointer
500 * does not process shared invalidation messages or call
501 * AtEOXact_SMgr().
502 */
504
505 /*
506 * Indicate checkpoint completion to any waiting backends.
507 */
511
513
514 if (!do_restartpoint)
515 {
516 /*
517 * Note we record the checkpoint start time not end time as
518 * last_checkpoint_time. This is so that time-driven
519 * checkpoints happen at a predictable spacing.
520 */
522
523 if (ckpt_performed)
525 }
526 else
527 {
528 if (ckpt_performed)
529 {
530 /*
531 * The same as for checkpoint. Please see the
532 * corresponding comment.
533 */
535
537 }
538 else
539 {
540 /*
541 * We were not able to perform the restartpoint
542 * (checkpoints throw an ERROR in case of error). Most
543 * likely because we have not received any new checkpoint
544 * WAL records since the last restartpoint. Try again in
545 * 15 s.
546 */
548 }
549 }
550
551 ckpt_active = false;
552
553 /*
554 * We may have received an interrupt during the checkpoint and the
555 * latch might have been reset (e.g. in CheckpointWriteDelay).
556 */
559 break;
560 }
561
562 /* Check for archive_timeout and switch xlog files if necessary. */
564
565 /* Report pending statistics to the cumulative stats system */
567 pgstat_report_wal(true);
568
569 /*
570 * If any checkpoint flags have been set, redo the loop to handle the
571 * checkpoint without sleeping.
572 */
573 if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
574 continue;
575
576 /*
577 * Sleep until we are signaled or it's time for another checkpoint or
578 * xlog file switch.
579 */
580 now = (pg_time_t) time(NULL);
581 elapsed_secs = now - last_checkpoint_time;
582 if (elapsed_secs >= CheckPointTimeout)
583 continue; /* no sleep for us ... */
584 cur_timeout = CheckPointTimeout - elapsed_secs;
586 {
587 elapsed_secs = now - last_xlog_switch_time;
588 if (elapsed_secs >= XLogArchiveTimeout)
589 continue; /* no sleep for us ... */
590 cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
591 }
592
593 (void) WaitLatch(MyLatch,
595 cur_timeout * 1000L /* convert to ms */ ,
596 WAIT_EVENT_CHECKPOINTER_MAIN);
597 }
598
599 /*
600 * From here on, elog(ERROR) should end with exit(1), not send control
601 * back to the sigsetjmp block above.
602 */
603 ExitOnAnyError = true;
604
606 {
607 /*
608 * Close down the database.
609 *
610 * Since ShutdownXLOG() creates restartpoint or checkpoint, and
611 * updates the statistics, increment the checkpoint request and flush
612 * out pending statistic.
613 */
615 ShutdownXLOG(0, 0);
617 pgstat_report_wal(true);
618
619 /*
620 * Tell postmaster that we're done.
621 */
623 ShutdownXLOGPending = false;
624 }
625
626 /*
627 * Wait until we're asked to shut down. By separating the writing of the
628 * shutdown checkpoint from checkpointer exiting, checkpointer can perform
629 * some should-be-as-late-as-possible work like writing out stats.
630 */
631 for (;;)
632 {
633 /* Clear any already-pending wakeups */
635
637
639 break;
640
641 (void) WaitLatch(MyLatch,
643 0,
644 WAIT_EVENT_CHECKPOINTER_SHUTDOWN);
645 }
646
647 /* Normal exit from the checkpointer is here */
648 proc_exit(0); /* done */
649}
void pgaio_error_cleanup(void)
Definition: aio.c:1162
void AuxiliaryProcessMainCommon(void)
Definition: auxprocess.c:39
sigset_t UnBlockSig
Definition: pqsignal.c:22
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:3965
void UnlockBuffers(void)
Definition: bufmgr.c:5544
static void UpdateSharedMemoryConfig(void)
Definition: checkpointer.c:1500
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:169
static void ReqShutdownXLOG(SIGNAL_ARGS)
Definition: checkpointer.c:934
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:697
static double ckpt_cached_elapsed
Definition: checkpointer.c:170
static bool ckpt_active
Definition: checkpointer.c:164
static void ProcessCheckpointerInterrupts(void)
Definition: checkpointer.c:655
static volatile sig_atomic_t ShutdownXLOGPending
Definition: checkpointer.c:165
void AbsorbSyncRequests(void)
Definition: checkpointer.c:1429
int CheckPointWarning
Definition: checkpointer.c:158
int CheckPointTimeout
Definition: checkpointer.c:157
static pg_time_t last_checkpoint_time
Definition: checkpointer.c:172
static pg_time_t ckpt_start_time
Definition: checkpointer.c:168
bool ConditionVariableCancelSleep(void)
void ConditionVariableBroadcast(ConditionVariable *cv)
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1931
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1184
void EmitErrorReport(void)
Definition: elog.c:1695
ErrorContextCallback * error_context_stack
Definition: elog.c:95
void FlushErrorState(void)
Definition: elog.c:1875
int errhint(const char *fmt,...)
Definition: elog.c:1321
sigjmp_buf * PG_exception_stack
Definition: elog.c:97
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:150
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3226
int MyProcPid
Definition: globals.c:47
ProcNumber MyProcNumber
Definition: globals.c:90
bool ExitOnAnyError
Definition: globals.c:123
struct Latch * MyLatch
Definition: globals.c:63
Assert(PointerIsAligned(start, uint64))
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:337
void proc_exit(int code)
Definition: ipc.c:104
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 LWLockReleaseAll(void)
Definition: lwlock.c:1945
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:400
MemoryContext TopMemoryContext
Definition: mcxt.c:166
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
@ B_CHECKPOINTER
Definition: miscadmin.h:362
BackendType MyBackendType
Definition: miscinit.c:64
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:560
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:165
@ PMSIGNAL_XLOG_IS_SHUTDOWN
Definition: pmsignal.h:44
#define pqsignal
Definition: port.h:531
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:674
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:1016
void pg_usleep(long microsec)
Definition: signal.c:53
void smgrdestroyall(void)
Definition: smgr.c:386
void AtEOXact_SMgr(void)
Definition: smgr.c:1008
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
PROC_HDR * ProcGlobal
Definition: proc.c:78
ConditionVariable done_cv
Definition: checkpointer.c:129
ConditionVariable start_cv
Definition: checkpointer.c:128
ProcNumber checkpointerProc
Definition: proc.h:425
PgStat_Counter restartpoints_requested
Definition: pgstat.h:260
PgStat_Counter num_requested
Definition: pgstat.h:257
PgStat_Counter num_performed
Definition: pgstat.h:258
PgStat_Counter restartpoints_timed
Definition: pgstat.h:259
PgStat_Counter num_timed
Definition: pgstat.h:256
PgStat_Counter restartpoints_performed
Definition: pgstat.h:261
static void pgstat_report_wait_end(void)
Definition: wait_event.h:85
#define WL_TIMEOUT
Definition: waiteventset.h:37
#define WL_EXIT_ON_PM_DEATH
Definition: waiteventset.h:39
#define WL_LATCH_SET
Definition: waiteventset.h:34
#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:7639
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:6534
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6654
bool CreateCheckPoint(int flags)
Definition: xlog.c:6941
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:148
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:140
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:149
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlogrecovery.c:4561

References AbsorbSyncRequests(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), AuxiliaryProcessMainCommon(), B_CHECKPOINTER, before_shmem_exit(), CheckArchiveTimeout(), CHECKPOINT_CAUSE_TIME, CHECKPOINT_CAUSE_XLOG, CHECKPOINT_END_OF_RECOVERY, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerProc, 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(), CheckpointerShmemStruct::done_cv, EmitErrorReport(), ereport, errhint(), errmsg_plural(), error_context_stack, ExitOnAnyError, FlushErrorState(), GetInsertRecPtr(), GetXLogReplayRecPtr(), HOLD_INTERRUPTS, last_checkpoint_time, last_xlog_switch_time, LOG, LWLockReleaseAll(), MemoryContextReset(), MemoryContextSwitchTo(), Min, MyBackendType, MyLatch, MyProcNumber, MyProcPid, now(), PgStat_CheckpointerStats::num_performed, PgStat_CheckpointerStats::num_requested, PgStat_CheckpointerStats::num_timed, PendingCheckpointerStats, PG_exception_stack, 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(), ProcGlobal, 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()

void CheckpointerShmemInit ( void  )

Definition at line 973 of file checkpointer.c.

974{
976 bool found;
977
979 ShmemInitStruct("Checkpointer Data",
980 size,
981 &found);
982
983 if (!found)
984 {
985 /*
986 * First time through, so initialize. Note that we zero the whole
987 * requests array; this is so that CompactCheckpointerRequestQueue can
988 * assume that any pad bytes in the request structs are zeroes.
989 */
990 MemSet(CheckpointerShmem, 0, size);
996 }
997}
#define MemSet(start, val, len)
Definition: c.h:1019
size_t Size
Definition: c.h:610
#define MAX_CHECKPOINT_REQUESTS
Definition: checkpointer.c:152
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:951
void ConditionVariableInit(ConditionVariable *cv)
int NBuffers
Definition: globals.c:142
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
#define SpinLockInit(lock)
Definition: spin.h:57

References CheckpointerShmem, CheckpointerShmemSize(), CheckpointerShmemStruct::ckpt_lck, ConditionVariableInit(), CheckpointerShmemStruct::done_cv, CheckpointerShmemStruct::head, MAX_CHECKPOINT_REQUESTS, CheckpointerShmemStruct::max_requests, MemSet, Min, NBuffers, ShmemInitStruct(), SpinLockInit, CheckpointerShmemStruct::start_cv, and CheckpointerShmemStruct::tail.

Referenced by CreateOrAttachShmemStructs().

CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 951 of file checkpointer.c.

952{
953 Size size;
954
955 /*
956 * The size of the requests[] array is arbitrarily set equal to NBuffers.
957 * But there is a cap of MAX_CHECKPOINT_REQUESTS to prevent accumulating
958 * too many checkpoint requests in the ring buffer.
959 */
960 size = offsetof(CheckpointerShmemStruct, requests);
961 size = add_size(size, mul_size(Min(NBuffers,
963 sizeof(CheckpointerRequest)));
964
965 return size;
966}
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510

References add_size(), MAX_CHECKPOINT_REQUESTS, Min, mul_size(), and NBuffers.

Referenced by CalculateShmemSize(), and CheckpointerShmemInit().

CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 785 of file checkpointer.c.

786{
787 static int absorb_counter = WRITES_PER_ABSORB;
788
789 /* Do nothing if checkpoint is being executed by non-checkpointer process */
791 return;
792
793 /*
794 * Perform the usual duties and take a nap, unless we're behind schedule,
795 * in which case we just try to catch up as quickly as possible.
796 */
797 if (!(flags & CHECKPOINT_FAST) &&
802 {
804 {
805 ConfigReloadPending = false;
807 /* update shmem copies of config variables */
809 }
810
812 absorb_counter = WRITES_PER_ABSORB;
813
815
816 /* Report interim statistics to the cumulative stats system */
818
819 /*
820 * This sleep used to be connected to bgwriter_delay, typically 200ms.
821 * That resulted in more frequent wakeups if not much work to do.
822 * Checkpointer and bgwriter are no longer related so take the Big
823 * Sleep.
824 */
826 100,
827 WAIT_EVENT_CHECKPOINT_WRITE_DELAY);
829 }
830 else if (--absorb_counter <= 0)
831 {
832 /*
833 * Absorb pending fsync requests after each WRITES_PER_ABSORB write
834 * operations even when we don't sleep, to prevent overflow of the
835 * fsync request queue.
836 */
838 absorb_counter = WRITES_PER_ABSORB;
839 }
840
841 /* Check for barrier events. */
844}
static bool FastCheckpointRequested(void)
Definition: checkpointer.c:758
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:855
#define WRITES_PER_ABSORB
Definition: checkpointer.c:146
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:499
#define CHECKPOINT_FAST
Definition: xlog.h:141

References AbsorbSyncRequests(), AmCheckpointerProcess, CheckArchiveTimeout(), CHECKPOINT_FAST, ConfigReloadPending, FastCheckpointRequested(), 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 1289 of file checkpointer.c.

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

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

Referenced by ForwardSyncRequest().

ExecCheckpoint()

void ExecCheckpoint ( ParseStatepstate,
CheckPointStmtstmt 
)

Definition at line 1006 of file checkpointer.c.

1007{
1008 bool fast = true;
1009 bool unlogged = false;
1010
1011 foreach_ptr(DefElem, opt, stmt->options)
1012 {
1013 if (strcmp(opt->defname, "mode") == 0)
1014 {
1015 char *mode = defGetString(opt);
1016
1017 if (strcmp(mode, "spread") == 0)
1018 fast = false;
1019 else if (strcmp(mode, "fast") != 0)
1020 ereport(ERROR,
1021 (errcode(ERRCODE_SYNTAX_ERROR),
1022 errmsg("unrecognized MODE option \"%s\"", mode),
1023 parser_errposition(pstate, opt->location)));
1024 }
1025 else if (strcmp(opt->defname, "flush_unlogged") == 0)
1026 unlogged = defGetBoolean(opt);
1027 else
1028 ereport(ERROR,
1029 (errcode(ERRCODE_SYNTAX_ERROR),
1030 errmsg("unrecognized CHECKPOINT option \"%s\"", opt->defname),
1031 parser_errposition(pstate, opt->location)));
1032 }
1033
1034 if (!has_privs_of_role(GetUserId(), ROLE_PG_CHECKPOINT))
1035 ereport(ERROR,
1036 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1037 /* translator: %s is name of an SQL command (e.g., CHECKPOINT) */
1038 errmsg("permission denied to execute %s command",
1039 "CHECKPOINT"),
1040 errdetail("Only roles with privileges of the \"%s\" role may execute this command.",
1041 "pg_checkpoint")));
1042
1044 (fast ? CHECKPOINT_FAST : 0) |
1045 (unlogged ? CHECKPOINT_FLUSH_UNLOGGED : 0) |
1047}
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5284
void RequestCheckpoint(int flags)
Definition: checkpointer.c:1067
char * defGetString(DefElem *def)
Definition: define.c:35
bool defGetBoolean(DefElem *def)
Definition: define.c:94
int errdetail(const char *fmt,...)
Definition: elog.c:1207
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define stmt
Definition: indent_codes.h:59
Oid GetUserId(void)
Definition: miscinit.c:469
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
static PgChecksumMode mode
Definition: pg_checksums.c:55
#define foreach_ptr(type, var, lst)
Definition: pg_list.h:469
#define CHECKPOINT_FLUSH_UNLOGGED
Definition: xlog.h:143
#define CHECKPOINT_FORCE
Definition: xlog.h:142
#define CHECKPOINT_WAIT
Definition: xlog.h:145

References CHECKPOINT_FAST, CHECKPOINT_FLUSH_UNLOGGED, CHECKPOINT_FORCE, CHECKPOINT_WAIT, defGetBoolean(), defGetString(), ereport, errcode(), errdetail(), errmsg(), ERROR, 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 758 of file checkpointer.c.

759{
761
762 /*
763 * We don't need to acquire the ckpt_lck in this case because we're only
764 * looking at a single flag bit.
765 */
766 if (cps->ckpt_flags & CHECKPOINT_FAST)
767 return true;
768 return false;
769}

References CHECKPOINT_FAST, CheckpointerShmem, and CheckpointerShmemStruct::ckpt_flags.

Referenced by CheckpointWriteDelay().

FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1519 of file checkpointer.c.

1520{
1521 static int ckpt_done = 0;
1522 int new_done;
1523 bool FirstCall = false;
1524
1526 new_done = CheckpointerShmem->ckpt_done;
1528
1529 if (new_done != ckpt_done)
1530 FirstCall = true;
1531
1532 ckpt_done = new_done;
1533
1534 return FirstCall;
1535}

References CheckpointerShmem, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_lck, SpinLockAcquire, and SpinLockRelease.

Referenced by BackgroundWriterMain().

ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTagftag,
SyncRequestType  type 
)

Definition at line 1217 of file checkpointer.c.

1218{
1219 CheckpointerRequest *request;
1220 bool too_full;
1221 int insert_pos;
1222
1223 if (!IsUnderPostmaster)
1224 return false; /* probably shouldn't even get here */
1225
1227 elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1228
1229 LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1230
1231 /*
1232 * If the checkpointer isn't running or the request queue is full, the
1233 * backend will have to perform its own fsync request. But before forcing
1234 * that to happen, we can try to compact the request queue.
1235 */
1239 {
1240 LWLockRelease(CheckpointerCommLock);
1241 return false;
1242 }
1243
1244 /* OK, insert request */
1245 insert_pos = CheckpointerShmem->tail;
1246 request = &CheckpointerShmem->requests[insert_pos];
1247 request->ftag = *ftag;
1248 request->type = type;
1249
1252
1253 /* If queue is more than half full, nudge the checkpointer to empty it */
1254 too_full = (CheckpointerShmem->num_requests >=
1256
1257 LWLockRelease(CheckpointerCommLock);
1258
1259 /* ... but not till after we release the lock */
1260 if (too_full)
1261 {
1262 volatile PROC_HDR *procglobal = ProcGlobal;
1263 ProcNumber checkpointerProc = procglobal->checkpointerProc;
1264
1265 if (checkpointerProc != INVALID_PROC_NUMBER)
1266 SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1267 }
1268
1269 return true;
1270}
static bool CompactCheckpointerRequestQueue(void)
Definition: checkpointer.c:1289
bool IsUnderPostmaster
Definition: globals.c:120
void SetLatch(Latch *latch)
Definition: latch.c:290
#define GetPGProcByNumber(n)
Definition: proc.h:440
#define INVALID_PROC_NUMBER
Definition: procnumber.h:26
int ProcNumber
Definition: procnumber.h:24
Definition: proc.h:386
const char * type

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

Referenced by RegisterSyncRequest().

IsCheckpointOnSchedule()

static bool IsCheckpointOnSchedule ( double  progress )
static

Definition at line 855 of file checkpointer.c.

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

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

Referenced by CheckpointWriteDelay().

ProcessCheckpointerInterrupts()

static void ProcessCheckpointerInterrupts ( void  )
static

Definition at line 655 of file checkpointer.c.

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

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

Referenced by CheckpointerMain().

ReqShutdownXLOG()

static void ReqShutdownXLOG ( SIGNAL_ARGS  )
static

Definition at line 934 of file checkpointer.c.

935{
936 ShutdownXLOGPending = true;
938}

References MyLatch, SetLatch(), and ShutdownXLOGPending.

Referenced by CheckpointerMain().

RequestCheckpoint()

void RequestCheckpoint ( int  flags )

Definition at line 1067 of file checkpointer.c.

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

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, GetPGProcByNumber, INVALID_PROC_NUMBER, IsPostmasterEnvironment, LOG, MAX_SIGNAL_TRIES, pg_usleep(), ProcGlobal, SetLatch(), smgrdestroyall(), SpinLockAcquire, SpinLockRelease, and CheckpointerShmemStruct::start_cv.

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

UpdateSharedMemoryConfig()

static void UpdateSharedMemoryConfig ( void  )
static

Definition at line 1500 of file checkpointer.c.

1501{
1502 /* update global shmem state for sync rep */
1504
1505 /*
1506 * If full_page_writes has been changed by SIGHUP, we update it in shared
1507 * memory and write an XLOG_FPW_CHANGE record.
1508 */
1510
1511 elog(DEBUG2, "checkpointer updated shared memory configuration values");
1512}
#define DEBUG2
Definition: elog.h:29
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:964
void UpdateFullPageWrites(void)
Definition: xlog.c:8216

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

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

Variable Documentation

CheckPointCompletionTarget

double CheckPointCompletionTarget = 0.9

Definition at line 159 of file checkpointer.c.

Referenced by assign_checkpoint_completion_target(), CalculateCheckpointSegments(), IsCheckpointOnSchedule(), and XLOGfileslop().

CheckpointerShmem

CheckpointerShmemStruct* CheckpointerShmem
static

Definition at line 143 of file checkpointer.c.

Referenced by AbsorbSyncRequests(), CheckpointerMain(), CheckpointerShmemInit(), CompactCheckpointerRequestQueue(), FastCheckpointRequested(), FirstCallSinceLastCheckpoint(), ForwardSyncRequest(), and RequestCheckpoint().

CheckPointTimeout

int CheckPointTimeout = 300

Definition at line 157 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

CheckPointWarning

int CheckPointWarning = 30

Definition at line 158 of file checkpointer.c.

Referenced by CheckpointerMain().

ckpt_active

bool ckpt_active = false
static

Definition at line 164 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

ckpt_cached_elapsed

double ckpt_cached_elapsed
static

Definition at line 170 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

ckpt_start_recptr

XLogRecPtr ckpt_start_recptr
static

Definition at line 169 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

ckpt_start_time

pg_time_t ckpt_start_time
static

Definition at line 168 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

last_checkpoint_time

pg_time_t last_checkpoint_time
static

Definition at line 172 of file checkpointer.c.

Referenced by CheckpointerMain().

last_xlog_switch_time

pg_time_t last_xlog_switch_time
static

Definition at line 173 of file checkpointer.c.

Referenced by CheckArchiveTimeout(), and CheckpointerMain().

ShutdownXLOGPending

volatile sig_atomic_t ShutdownXLOGPending = false
static

Definition at line 165 of file checkpointer.c.

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

AltStyle によって変換されたページ (->オリジナル) /