PostgreSQL Source Code git master
Loading...
Searching...
No Matches
bgwriter.h File Reference
#include "parser/parse_node.h"
#include "storage/block.h"
#include "storage/relfilelocator.h"
#include "storage/smgr.h"
#include "storage/sync.h"
Include dependency graph for bgwriter.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

pg_noreturn void BackgroundWriterMain (const void *startup_data, size_t startup_data_len)
 
pg_noreturn void CheckpointerMain (const void *startup_data, size_t startup_data_len)
 
void ExecCheckpoint (ParseState *pstate, CheckPointStmt *stmt)
 
void RequestCheckpoint (int flags)
 
void CheckpointWriteDelay (int flags, double progress)
 
bool ForwardSyncRequest (const FileTag *ftag, SyncRequestType type)
 
void AbsorbSyncRequests (void)
 
bool FirstCallSinceLastCheckpoint (void)
 

Variables

PGDLLIMPORT int BgWriterDelay
 
PGDLLIMPORT int CheckPointTimeout
 
PGDLLIMPORT int CheckPointWarning
 
PGDLLIMPORT double CheckPointCompletionTarget
 

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )
extern

Definition at line 1431 of file checkpointer.c.

1432{
1433 CheckpointerRequest *requests = NULL;
1435 int n,
1436 i;
1437 bool loop;
1438
1439 if (!AmCheckpointerProcess())
1440 return;
1441
1442 do
1443 {
1445
1446 /*---
1447 * We try to avoid holding the lock for a long time by:
1448 * 1. Copying the request array and processing the requests after
1449 * releasing the lock;
1450 * 2. Processing not the whole queue, but only batches of
1451 * CKPT_REQ_BATCH_SIZE at once.
1452 *
1453 * Once we have cleared the requests from shared memory, we must
1454 * PANIC if we then fail to absorb them (e.g., because our hashtable
1455 * runs out of memory). This is because the system cannot run safely
1456 * if we are unable to fsync what we have been told to fsync.
1457 * Fortunately, the hashtable is so small that the problem is quite
1458 * unlikely to arise in practice.
1459 *
1460 * Note: The maximum possible size of a ring buffer is
1461 * MAX_CHECKPOINT_REQUESTS entries, which fit into a maximum palloc
1462 * allocation size of 1Gb. Our maximum batch size,
1463 * CKPT_REQ_BATCH_SIZE, is even smaller.
1464 */
1466 if (n > 0)
1467 {
1468 if (!requests)
1469 requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1470
1471 for (i = 0; i < n; i++)
1472 {
1475 }
1476
1478
1479 }
1480
1482
1483 /* Are there any requests in the queue? If so, keep going. */
1485
1487
1488 for (request = requests; n > 0; request++, n--)
1489 RememberSyncRequest(&request->ftag, request->type);
1490
1492 } while (loop);
1493
1494 if (requests)
1495 pfree(requests);
1496}
#define Min(x, y)
Definition c.h:1091
#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:1616
void * palloc(Size size)
Definition mcxt.c:1387
#define AmCheckpointerProcess()
Definition miscadmin.h:404
#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().

◆ BackgroundWriterMain()

pg_noreturn void BackgroundWriterMain ( const void startup_data,
size_t  startup_data_len 
)
extern

Definition at line 89 of file bgwriter.c.

90{
93 bool prev_hibernate;
95
97
99
100 /*
101 * Properly accept or ignore signals that might be sent to us.
102 */
106 /* SIGQUIT handler was already set up by InitPostmasterChild */
111
112 /*
113 * Reset some signals that are accepted by postmaster but not here
114 */
116
117 /*
118 * We just started, assume there has been either a shutdown or
119 * end-of-recovery snapshot.
120 */
122
123 /*
124 * Create a memory context that we will do all our work in. We do this so
125 * that we can reset the context during error recovery and thereby avoid
126 * possible memory leaks. Formerly this code just ran in
127 * TopMemoryContext, but resetting that would be a really bad idea.
128 */
130 "Background Writer",
133
135
136 /*
137 * If an exception is encountered, processing resumes here.
138 *
139 * You might wonder why this isn't coded as an infinite loop around a
140 * PG_TRY construct. The reason is that this is the bottom of the
141 * exception stack, and so with PG_TRY there would be no exception handler
142 * in force at all during the CATCH part. By leaving the outermost setjmp
143 * always active, we have at least some chance of recovering from an error
144 * during error recovery. (If we get into an infinite loop thereby, it
145 * will soon be stopped by overflow of elog.c's internal state stack.)
146 *
147 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
148 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
149 * signals other than SIGQUIT will be blocked until we complete error
150 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
151 * call redundant, but it is not since InterruptPending might be set
152 * already.
153 */
154 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
155 {
156 /* Since not using PG_TRY, must reset error stack by hand */
158
159 /* Prevent interrupts while cleaning up */
161
162 /* Report the error to the server log */
164
165 /*
166 * These operations are really just a minimal subset of
167 * AbortTransaction(). We don't have very many resources to worry
168 * about in bgwriter, but we do have LWLocks, buffers, and temp files.
169 */
175 AtEOXact_Buffers(false);
177 AtEOXact_Files(false);
178 AtEOXact_HashTables(false);
179
180 /*
181 * Now return to normal top-level context and clear ErrorContext for
182 * next time.
183 */
186
187 /* Flush any leaked data in the top-level context */
189
190 /* re-initialize to avoid repeated errors causing problems */
192
193 /* Now we can allow interrupts again */
195
196 /*
197 * Sleep at least 1 second after any error. A write error is likely
198 * to be repeated, and we don't want to be filling the error logs as
199 * fast as we can.
200 */
201 pg_usleep(1000000L);
202
203 /* Report wait end here, when there is no further possibility of wait */
205 }
206
207 /* We can now handle ereport(ERROR) */
209
210 /*
211 * Unblock signals (they were blocked when the postmaster forked us)
212 */
214
215 /*
216 * Reset hibernation state after any error.
217 */
218 prev_hibernate = false;
219
220 /*
221 * Loop forever
222 */
223 for (;;)
224 {
225 bool can_hibernate;
226 int rc;
227
228 /* Clear any already-pending wakeups */
230
232
233 /*
234 * Do one cycle of dirty-buffer writing.
235 */
237
238 /* Report pending statistics to the cumulative stats system */
240 pgstat_report_wal(true);
241
243 {
244 /*
245 * After any checkpoint, free all smgr objects. Otherwise we
246 * would never do so for dropped relations, as the bgwriter does
247 * not process shared invalidation messages or call
248 * AtEOXact_SMgr().
249 */
251 }
252
253 /*
254 * Log a new xl_running_xacts every now and then so replication can
255 * get into a consistent state faster (think of suboverflowed
256 * snapshots) and clean up resources (locks, KnownXids*) more
257 * frequently. The costs of this are relatively low, so doing it 4
258 * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
259 *
260 * We assume the interval for writing xl_running_xacts is
261 * significantly bigger than BgWriterDelay, so we don't complicate the
262 * overall timeout handling but just assume we're going to get called
263 * often enough even if hibernation mode is active. It's not that
264 * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
265 * sure we're not waking the disk up unnecessarily on an idle system
266 * we check whether there has been any WAL inserted since the last
267 * time we've logged a running xacts.
268 *
269 * We do this logging in the bgwriter as it is the only process that
270 * is run regularly and returns to its mainloop all the time. E.g.
271 * Checkpointer, when active, is barely ever in its mainloop and thus
272 * makes it hard to log regularly.
273 */
275 {
278
281
282 /*
283 * Only log if enough time has passed and interesting records have
284 * been inserted since the last snapshot. Have to compare with <=
285 * instead of < because GetLastImportantRecPtr() points at the
286 * start of a record, whereas last_snapshot_lsn points just past
287 * the end of the record.
288 */
289 if (now >= timeout &&
291 {
294 }
295 }
296
297 /*
298 * Sleep until we are signaled or BgWriterDelay has elapsed.
299 *
300 * Note: the feedback control loop in BgBufferSync() expects that we
301 * will call it every BgWriterDelay msec. While it's not critical for
302 * correctness that that be exact, the feedback loop might misbehave
303 * if we stray too far from that. Hence, avoid loading this process
304 * down with latch events that are likely to happen frequently during
305 * normal operation.
306 */
307 rc = WaitLatch(MyLatch,
310
311 /*
312 * If no latch event and BgBufferSync says nothing's happening, extend
313 * the sleep in "hibernation" mode, where we sleep for much longer
314 * than bgwriter_delay says. Fewer wakeups save electricity. When a
315 * backend starts using buffers again, it will wake us up by setting
316 * our latch. Because the extra sleep will persist only as long as no
317 * buffer allocations happen, this should not distort the behavior of
318 * BgBufferSync's control loop too badly; essentially, it will think
319 * that the system-wide idle interval didn't exist.
320 *
321 * There is a race condition here, in that a backend might allocate a
322 * buffer between the time BgBufferSync saw the alloc count as zero
323 * and the time we call StrategyNotifyBgWriter. While it's not
324 * critical that we not hibernate anyway, we try to reduce the odds of
325 * that by only hibernating when BgBufferSync says nothing's happening
326 * for two consecutive cycles. Also, we mitigate any possible
327 * consequences of a missed wakeup by not hibernating forever.
328 */
330 {
331 /* Ask for notification at next buffer allocation */
333 /* Sleep ... */
338 /* Reset the notification request in case we timed out */
340 }
341
343 }
344}
void pgaio_error_cleanup(void)
Definition aio.c:1175
void AuxiliaryProcessMainCommon(void)
Definition auxprocess.c:41
sigset_t UnBlockSig
Definition pqsignal.c:22
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1603
static XLogRecPtr last_snapshot_lsn
Definition bgwriter.c:79
static TimestampTz last_snapshot_ts
Definition bgwriter.c:78
int BgWriterDelay
Definition bgwriter.c:59
#define HIBERNATE_FACTOR
Definition bgwriter.c:65
#define LOG_SNAPSHOT_INTERVAL_MS
Definition bgwriter.c:71
void AtEOXact_Buffers(bool isCommit)
Definition bufmgr.c:4199
bool BgBufferSync(WritebackContext *wb_context)
Definition bufmgr.c:3831
void UnlockBuffers(void)
Definition bufmgr.c:5852
int bgwriter_flush_after
Definition bufmgr.c:224
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition bufmgr.c:7678
#define Assert(condition)
Definition c.h:943
bool FirstCallSinceLastCheckpoint(void)
bool ConditionVariableCancelSleep(void)
int64 TimestampTz
Definition timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition dynahash.c:1864
void EmitErrorReport(void)
Definition elog.c:1882
ErrorContextCallback * error_context_stack
Definition elog.c:99
void FlushErrorState(void)
Definition elog.c:2062
sigjmp_buf * PG_exception_stack
Definition elog.c:101
void AtEOXact_Files(bool isCommit)
Definition fd.c:3214
void StrategyNotifyBgWriter(int bgwprocno)
Definition freelist.c:368
ProcNumber MyProcNumber
Definition globals.c:92
struct Latch * MyLatch
Definition globals.c:65
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition interrupt.c:104
void ProcessMainLoopInterrupts(void)
Definition interrupt.c:34
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition interrupt.c:61
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:1866
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
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:138
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
void pgstat_report_bgwriter(void)
void pgstat_report_wal(bool force)
Definition pgstat_wal.c:46
#define pqsignal
Definition port.h:547
#define InvalidOid
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:688
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:1017
XLogRecPtr LogStandbySnapshot(Oid dbid)
Definition standby.c:1303
#define TimestampTzPlusMilliseconds(tz, ms)
Definition timestamp.h:85
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 RecoveryInProgress(void)
Definition xlog.c:6830
XLogRecPtr GetLastImportantRecPtr(void)
Definition xlog.c:7052
#define XLogStandbyInfoActive()
Definition xlog.h:126

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), AuxiliaryProcessMainCommon(), BgBufferSync(), bgwriter_flush_after, BgWriterDelay, ConditionVariableCancelSleep(), EmitErrorReport(), error_context_stack, fb(), FirstCallSinceLastCheckpoint(), FlushErrorState(), GetCurrentTimestamp(), GetLastImportantRecPtr(), HIBERNATE_FACTOR, HOLD_INTERRUPTS, InvalidOid, last_snapshot_lsn, last_snapshot_ts, LOG_SNAPSHOT_INTERVAL_MS, LogStandbySnapshot(), LWLockReleaseAll(), MemoryContextReset(), MemoryContextSwitchTo(), MyLatch, MyProcNumber, now(), PG_exception_stack, pg_usleep(), pgaio_error_cleanup(), pgstat_report_bgwriter(), pgstat_report_wait_end(), pgstat_report_wal(), pqsignal, ProcessMainLoopInterrupts(), procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrdestroyall(), StrategyNotifyBgWriter(), TimestampTzPlusMilliseconds, TopMemoryContext, UnBlockSig, UnlockBuffers(), WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, WritebackContextInit(), and XLogStandbyInfoActive.

◆ CheckpointerMain()

pg_noreturn void CheckpointerMain ( const void startup_data,
size_t  startup_data_len 
)
extern

Definition at line 205 of file checkpointer.c.

206{
209
211
213
215
216 /*
217 * Properly accept or ignore signals the postmaster might send us
218 *
219 * Note: we deliberately ignore SIGTERM, because during a standard Unix
220 * system shutdown cycle, init will SIGTERM all processes at once. We
221 * want to wait for the backends to exit, whereupon the postmaster will
222 * tell us it's okay to shut down (via SIGUSR2).
223 */
226 pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
227 /* SIGQUIT handler was already set up by InitPostmasterChild */
232
233 /*
234 * Reset some signals that are accepted by postmaster but not here
235 */
237
238 /*
239 * Initialize so that first time-driven event happens at the correct time.
240 */
242
243 /*
244 * Write out stats after shutdown. This needs to be called by exactly one
245 * process during a normal shutdown, and since checkpointer is shut down
246 * very late...
247 *
248 * While e.g. walsenders are active after the shutdown checkpoint has been
249 * written (and thus could produce more stats), checkpointer stays around
250 * after the shutdown checkpoint has been written. postmaster will only
251 * signal checkpointer to exit after all processes that could emit stats
252 * have been shut down.
253 */
255
256 /*
257 * Create a memory context that we will do all our work in. We do this so
258 * that we can reset the context during error recovery and thereby avoid
259 * possible memory leaks. Formerly this code just ran in
260 * TopMemoryContext, but resetting that would be a really bad idea.
261 */
263 "Checkpointer",
266
267 /*
268 * If an exception is encountered, processing resumes here.
269 *
270 * You might wonder why this isn't coded as an infinite loop around a
271 * PG_TRY construct. The reason is that this is the bottom of the
272 * exception stack, and so with PG_TRY there would be no exception handler
273 * in force at all during the CATCH part. By leaving the outermost setjmp
274 * always active, we have at least some chance of recovering from an error
275 * during error recovery. (If we get into an infinite loop thereby, it
276 * will soon be stopped by overflow of elog.c's internal state stack.)
277 *
278 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
279 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
280 * signals other than SIGQUIT will be blocked until we complete error
281 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
282 * call redundant, but it is not since InterruptPending might be set
283 * already.
284 */
285 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
286 {
287 /* Since not using PG_TRY, must reset error stack by hand */
289
290 /* Prevent interrupts while cleaning up */
292
293 /* Report the error to the server log */
295
296 /*
297 * These operations are really just a minimal subset of
298 * AbortTransaction(). We don't have very many resources to worry
299 * about in checkpointer, but we do have LWLocks, buffers, and temp
300 * files.
301 */
308 AtEOXact_Buffers(false);
310 AtEOXact_Files(false);
311 AtEOXact_HashTables(false);
312
313 /* Warn any waiting backends that the checkpoint failed. */
314 if (ckpt_active)
315 {
320
322
323 ckpt_active = false;
324 }
325
326 /*
327 * Now return to normal top-level context and clear ErrorContext for
328 * next time.
329 */
332
333 /* Flush any leaked data in the top-level context */
335
336 /* Now we can allow interrupts again */
338
339 /*
340 * Sleep at least 1 second after any error. A write error is likely
341 * to be repeated, and we don't want to be filling the error logs as
342 * fast as we can.
343 */
344 pg_usleep(1000000L);
345 }
346
347 /* We can now handle ereport(ERROR) */
349
350 /*
351 * Unblock signals (they were blocked when the postmaster forked us)
352 */
354
355 /*
356 * Ensure all shared memory values are set correctly for the config. Doing
357 * this here ensures no race conditions from other concurrent updaters.
358 */
360
361 /*
362 * Advertise our proc number that backends can use to wake us up while
363 * we're sleeping.
364 */
366
367 /*
368 * Loop until we've been asked to write the shutdown checkpoint or
369 * terminate.
370 */
371 for (;;)
372 {
373 bool do_checkpoint = false;
374 int flags = 0;
376 int elapsed_secs;
377 int cur_timeout;
378 bool chkpt_or_rstpt_requested = false;
379 bool chkpt_or_rstpt_timed = false;
380
381 /* Clear any already-pending wakeups */
383
384 /*
385 * Process any requests or signals received recently.
386 */
388
391 break;
392
393 /*
394 * Detect a pending checkpoint request by checking whether the flags
395 * word in shared memory is nonzero. We shouldn't need to acquire the
396 * ckpt_lck for this.
397 */
398 if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
399 {
400 do_checkpoint = true;
402 }
403
404 /*
405 * Force a checkpoint if too much time has elapsed since the last one.
406 * Note that we count a timed checkpoint in stats only when this
407 * occurs without an external request, but we set the CAUSE_TIME flag
408 * bit even if there is also an external request.
409 */
410 now = (pg_time_t) time(NULL);
413 {
414 if (!do_checkpoint)
416 do_checkpoint = true;
417 flags |= CHECKPOINT_CAUSE_TIME;
418 }
419
420 /*
421 * Do a checkpoint if requested.
422 */
423 if (do_checkpoint)
424 {
425 bool ckpt_performed = false;
426 bool do_restartpoint;
427
428 /* Check if we should perform a checkpoint or a restartpoint. */
430
431 /*
432 * Atomically fetch the request flags to figure out what kind of a
433 * checkpoint we should perform, and increase the started-counter
434 * to acknowledge that we've started a new checkpoint.
435 */
441
443
444 /*
445 * The end-of-recovery checkpoint is a real checkpoint that's
446 * performed while we're still in recovery.
447 */
448 if (flags & CHECKPOINT_END_OF_RECOVERY)
449 do_restartpoint = false;
450
452 {
453 chkpt_or_rstpt_timed = false;
454 if (do_restartpoint)
456 else
458 }
459
461 {
463 if (do_restartpoint)
465 else
467 }
468
469 /*
470 * We will warn if (a) too soon since last checkpoint (whatever
471 * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
472 * since the last checkpoint start. Note in particular that this
473 * implementation will not generate warnings caused by
474 * CheckPointTimeout < CheckPointWarning.
475 */
476 if (!do_restartpoint &&
477 (flags & CHECKPOINT_CAUSE_XLOG) &&
479 ereport(LOG,
480 (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
481 "checkpoints are occurring too frequently (%d seconds apart)",
484 errhint("Consider increasing the configuration parameter \"%s\".", "max_wal_size")));
485
486 /*
487 * Initialize checkpointer-private variables used during
488 * checkpoint.
489 */
490 ckpt_active = true;
491 if (do_restartpoint)
493 else
497
498 /*
499 * Do the checkpoint.
500 */
501 if (!do_restartpoint)
503 else
505
506 /*
507 * After any checkpoint, free all smgr objects. Otherwise we
508 * would never do so for dropped relations, as the checkpointer
509 * does not process shared invalidation messages or call
510 * AtEOXact_SMgr().
511 */
513
514 /*
515 * Indicate checkpoint completion to any waiting backends.
516 */
520
522
523 if (!do_restartpoint)
524 {
525 /*
526 * Note we record the checkpoint start time not end time as
527 * last_checkpoint_time. This is so that time-driven
528 * checkpoints happen at a predictable spacing.
529 */
531
532 if (ckpt_performed)
534 }
535 else
536 {
537 if (ckpt_performed)
538 {
539 /*
540 * The same as for checkpoint. Please see the
541 * corresponding comment.
542 */
544
546 }
547 else
548 {
549 /*
550 * We were not able to perform the restartpoint
551 * (checkpoints throw an ERROR in case of error). Most
552 * likely because we have not received any new checkpoint
553 * WAL records since the last restartpoint. Try again in
554 * 15 s.
555 */
557 }
558 }
559
560 ckpt_active = false;
561
562 /*
563 * We may have received an interrupt during the checkpoint and the
564 * latch might have been reset (e.g. in CheckpointWriteDelay).
565 */
568 break;
569 }
570
571 /*
572 * Disable logical decoding if someone requested it. See comments atop
573 * logicalctl.c.
574 */
576
577 /* Check for archive_timeout and switch xlog files if necessary. */
579
580 /* Report pending statistics to the cumulative stats system */
582 pgstat_report_wal(true);
583
584 /*
585 * If any checkpoint flags have been set, redo the loop to handle the
586 * checkpoint without sleeping.
587 */
588 if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
589 continue;
590
591 /*
592 * Sleep until we are signaled or it's time for another checkpoint or
593 * xlog file switch.
594 */
595 now = (pg_time_t) time(NULL);
598 continue; /* no sleep for us ... */
601 {
604 continue; /* no sleep for us ... */
606 }
607
610 cur_timeout * 1000L /* convert to ms */ ,
612 }
613
614 /*
615 * From here on, elog(ERROR) should end with exit(1), not send control
616 * back to the sigsetjmp block above.
617 */
618 ExitOnAnyError = true;
619
621 {
622 /*
623 * Close down the database.
624 *
625 * Since ShutdownXLOG() creates restartpoint or checkpoint, and
626 * updates the statistics, increment the checkpoint request and flush
627 * out pending statistic.
628 */
630 ShutdownXLOG(0, 0);
632 pgstat_report_wal(true);
633
634 /*
635 * Tell postmaster that we're done.
636 */
638 ShutdownXLOGPending = false;
639 }
640
641 /*
642 * Wait until we're asked to shut down. By separating the writing of the
643 * shutdown checkpoint from checkpointer exiting, checkpointer can perform
644 * some should-be-as-late-as-possible work like writing out stats.
645 */
646 for (;;)
647 {
648 /* Clear any already-pending wakeups */
650
652
654 break;
655
658 0,
660 }
661
662 /* Normal exit from the checkpointer is here */
663 proc_exit(0); /* done */
664}
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)
static pg_time_t last_xlog_switch_time
int CheckPointWarning
int CheckPointTimeout
static pg_time_t last_checkpoint_time
static pg_time_t ckpt_start_time
void ConditionVariableBroadcast(ConditionVariable *cv)
#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
int MyProcPid
Definition globals.c:49
bool ExitOnAnyError
Definition globals.c:125
volatile sig_atomic_t ShutdownRequestPending
Definition interrupt.c:28
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 DisableLogicalDecodingIfNecessary(void)
Definition logicalctl.c:458
void pgstat_before_server_shutdown(int code, Datum arg)
Definition pgstat.c:590
void pgstat_report_checkpointer(void)
PgStat_CheckpointerStats PendingCheckpointerStats
int64 pg_time_t
Definition pgtime.h:23
void SendPostmasterSignal(PMSignalReason reason)
Definition pmsignal.c:164
@ PMSIGNAL_XLOG_IS_SHUTDOWN
Definition pmsignal.h:45
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56
PROC_HDR * ProcGlobal
Definition proc.c:74
ConditionVariable done_cv
ConditionVariable start_cv
ProcNumber checkpointerProc
Definition proc.h:489
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
bool CreateRestartPoint(int flags)
Definition xlog.c:8129
XLogRecPtr GetInsertRecPtr(void)
Definition xlog.c:6978
void ShutdownXLOG(int code, Datum arg)
Definition xlog.c:7098
int XLogArchiveTimeout
Definition xlog.c:125
bool CreateCheckPoint(int flags)
Definition xlog.c:7395
#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, 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(), 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, 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.

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)
extern

Definition at line 800 of file checkpointer.c.

801{
803
804 /* Do nothing if checkpoint is being executed by non-checkpointer process */
806 return;
807
808 /*
809 * Perform the usual duties and take a nap, unless we're behind schedule,
810 * in which case we just try to catch up as quickly as possible.
811 */
812 if (!(flags & CHECKPOINT_FAST) &&
817 {
819 {
820 ConfigReloadPending = false;
822 /* update shmem copies of config variables */
824 }
825
828
830
831 /* Report interim statistics to the cumulative stats system */
833
834 /*
835 * This sleep used to be connected to bgwriter_delay, typically 200ms.
836 * That resulted in more frequent wakeups if not much work to do.
837 * Checkpointer and bgwriter are no longer related so take the Big
838 * Sleep.
839 */
841 100,
844 }
845 else if (--absorb_counter <= 0)
846 {
847 /*
848 * Absorb pending fsync requests after each WRITES_PER_ABSORB write
849 * operations even when we don't sleep, to prevent overflow of the
850 * fsync request queue.
851 */
854 }
855
856 /* Check for barrier events. */
859}
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:503
#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().

◆ ExecCheckpoint()

void ExecCheckpoint ( ParseState pstate,
CheckPointStmt stmt 
)
extern

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,
1022 errmsg("unrecognized value for %s option \"%s\": \"%s\"",
1023 "CHECKPOINT", "mode", mode),
1024 parser_errposition(pstate, opt->location)));
1025 }
1026 else if (strcmp(opt->defname, "flush_unlogged") == 0)
1027 unlogged = defGetBoolean(opt);
1028 else
1029 ereport(ERROR,
1031 errmsg("unrecognized %s option \"%s\"",
1032 "CHECKPOINT", opt->defname),
1033 parser_errposition(pstate, opt->location)));
1034 }
1035
1037 ereport(ERROR,
1039 /* translator: %s is name of an SQL command (e.g., CHECKPOINT) */
1040 errmsg("permission denied to execute %s command",
1041 "CHECKPOINT"),
1042 errdetail("Only roles with privileges of the \"%s\" role may execute this command.",
1043 "pg_checkpoint")));
1044
1046 (fast ? CHECKPOINT_FAST : 0) |
1049}
bool has_privs_of_role(Oid member, Oid role)
Definition acl.c:5314
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:874
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().

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )
extern

Definition at line 1521 of file checkpointer.c.

1522{
1523 static int ckpt_done = 0;
1524 int new_done;
1525 bool FirstCall = false;
1526
1530
1531 if (new_done != ckpt_done)
1532 FirstCall = true;
1533
1534 ckpt_done = new_done;
1535
1536 return FirstCall;
1537}

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

Referenced by BackgroundWriterMain().

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)
extern

Definition at line 1219 of file checkpointer.c.

1220{
1222 bool too_full;
1223 int insert_pos;
1224
1225 if (!IsUnderPostmaster)
1226 return false; /* probably shouldn't even get here */
1227
1229 elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1230
1232
1233 /*
1234 * If the checkpointer isn't running or the request queue is full, the
1235 * backend will have to perform its own fsync request. But before forcing
1236 * that to happen, we can try to compact the request queue.
1237 */
1241 {
1243 return false;
1244 }
1245
1246 /* OK, insert request */
1249 request->ftag = *ftag;
1250 request->type = type;
1251
1254
1255 /* If queue is more than half full, nudge the checkpointer to empty it */
1258
1260
1261 /* ... but not till after we release the lock */
1262 if (too_full)
1263 {
1264 volatile PROC_HDR *procglobal = ProcGlobal;
1265 ProcNumber checkpointerProc = procglobal->checkpointerProc;
1266
1267 if (checkpointerProc != INVALID_PROC_NUMBER)
1268 SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1269 }
1270
1271 return true;
1272}
static bool CompactCheckpointerRequestQueue(void)
#define elog(elevel,...)
Definition elog.h:228
bool IsUnderPostmaster
Definition globals.c:122
void SetLatch(Latch *latch)
Definition latch.c:290
#define GetPGProcByNumber(n)
Definition proc.h:504
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
int ProcNumber
Definition procnumber.h:24
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, ProcGlobal, CheckpointerShmemStruct::requests, SetLatch(), CheckpointerShmemStruct::tail, and type.

Referenced by RegisterSyncRequest().

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)
extern

Definition at line 1069 of file checkpointer.c.

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

Variable Documentation

◆ BgWriterDelay

PGDLLIMPORT int BgWriterDelay
extern

Definition at line 59 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

◆ CheckPointCompletionTarget

PGDLLIMPORT double CheckPointCompletionTarget
extern

◆ CheckPointTimeout

PGDLLIMPORT int CheckPointTimeout
extern

Definition at line 167 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

PGDLLIMPORT int CheckPointWarning
extern

Definition at line 168 of file checkpointer.c.

Referenced by CheckpointerMain().