PostgreSQL Source Code git master
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)
 
Size CheckpointerShmemSize (void)
 
void CheckpointerShmemInit (void)
 
bool FirstCallSinceLastCheckpoint (void)
 

Variables

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

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1437 of file checkpointer.c.

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

◆ BackgroundWriterMain()

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

Definition at line 88 of file bgwriter.c.

89{
90 sigjmp_buf local_sigjmp_buf;
91 MemoryContext bgwriter_context;
92 bool prev_hibernate;
93 WritebackContext wb_context;
94
95 Assert(startup_data_len == 0);
96
99
100 /*
101 * Properly accept or ignore signals that might be sent to us.
102 */
104 pqsignal(SIGINT, SIG_IGN);
106 /* SIGQUIT handler was already set up by InitPostmasterChild */
107 pqsignal(SIGALRM, SIG_IGN);
108 pqsignal(SIGPIPE, SIG_IGN);
110 pqsignal(SIGUSR2, SIG_IGN);
111
112 /*
113 * Reset some signals that are accepted by postmaster but not here
114 */
115 pqsignal(SIGCHLD, SIG_DFL);
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 */
129 bgwriter_context = AllocSetContextCreate(TopMemoryContext,
130 "Background Writer",
132 MemoryContextSwitchTo(bgwriter_context);
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 */
157 error_context_stack = NULL;
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 */
184 MemoryContextSwitchTo(bgwriter_context);
186
187 /* Flush any leaked data in the top-level context */
188 MemoryContextReset(bgwriter_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) */
208 PG_exception_stack = &local_sigjmp_buf;
209
210 /*
211 * Unblock signals (they were blocked when the postmaster forked us)
212 */
213 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
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 */
236 can_hibernate = BgBufferSync(&wb_context);
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 {
276 TimestampTz timeout = 0;
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,
309 BgWriterDelay /* ms */ , WAIT_EVENT_BGWRITER_MAIN);
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 */
329 if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
330 {
331 /* Ask for notification at next buffer allocation */
333 /* Sleep ... */
334 (void) WaitLatch(MyLatch,
337 WAIT_EVENT_BGWRITER_HIBERNATE);
338 /* Reset the notification request in case we timed out */
340 }
341
342 prev_hibernate = can_hibernate;
343 }
344}
void pgaio_error_cleanup(void)
Definition: aio.c:1165
void AuxiliaryProcessMainCommon(void)
Definition: auxprocess.c:39
sigset_t UnBlockSig
Definition: pqsignal.c:22
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
static XLogRecPtr last_snapshot_lsn
Definition: bgwriter.c:78
static TimestampTz last_snapshot_ts
Definition: bgwriter.c:77
int BgWriterDelay
Definition: bgwriter.c:58
#define HIBERNATE_FACTOR
Definition: bgwriter.c:64
#define LOG_SNAPSHOT_INTERVAL_MS
Definition: bgwriter.c:70
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:4084
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:3716
void UnlockBuffers(void)
Definition: bufmgr.c:5668
int bgwriter_flush_after
Definition: bufmgr.c:201
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:6519
bool FirstCallSinceLastCheckpoint(void)
bool ConditionVariableCancelSleep(void)
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1931
void EmitErrorReport(void)
Definition: elog.c:1704
ErrorContextCallback * error_context_stack
Definition: elog.c:95
void FlushErrorState(void)
Definition: elog.c:1884
sigjmp_buf * PG_exception_stack
Definition: elog.c:97
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3210
void StrategyNotifyBgWriter(int bgwprocno)
Definition: freelist.c:358
ProcNumber MyProcNumber
Definition: globals.c:90
struct Latch * MyLatch
Definition: globals.c:63
Assert(PointerIsAligned(start, uint64))
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:1949
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:136
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:134
@ B_BG_WRITER
Definition: miscadmin.h:362
BackendType MyBackendType
Definition: miscinit.c:64
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:551
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:677
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
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1282
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
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 RecoveryInProgress(void)
Definition: xlog.c:6461
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:6683
#define XLogStandbyInfoActive()
Definition: xlog.h:125

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), AuxiliaryProcessMainCommon(), B_BG_WRITER, BgBufferSync(), bgwriter_flush_after, BgWriterDelay, ConditionVariableCancelSleep(), EmitErrorReport(), error_context_stack, FirstCallSinceLastCheckpoint(), FlushErrorState(), GetCurrentTimestamp(), GetLastImportantRecPtr(), HIBERNATE_FACTOR, HOLD_INTERRUPTS, last_snapshot_lsn, last_snapshot_ts, LOG_SNAPSHOT_INTERVAL_MS, LogStandbySnapshot(), LWLockReleaseAll(), MemoryContextReset(), MemoryContextSwitchTo(), MyBackendType, 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 
)

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 /*
563 * Disable logical decoding if someone requested it. See comments atop
564 * logicalctl.c.
565 */
567
568 /* Check for archive_timeout and switch xlog files if necessary. */
570
571 /* Report pending statistics to the cumulative stats system */
573 pgstat_report_wal(true);
574
575 /*
576 * If any checkpoint flags have been set, redo the loop to handle the
577 * checkpoint without sleeping.
578 */
579 if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
580 continue;
581
582 /*
583 * Sleep until we are signaled or it's time for another checkpoint or
584 * xlog file switch.
585 */
586 now = (pg_time_t) time(NULL);
587 elapsed_secs = now - last_checkpoint_time;
588 if (elapsed_secs >= CheckPointTimeout)
589 continue; /* no sleep for us ... */
590 cur_timeout = CheckPointTimeout - elapsed_secs;
592 {
593 elapsed_secs = now - last_xlog_switch_time;
594 if (elapsed_secs >= XLogArchiveTimeout)
595 continue; /* no sleep for us ... */
596 cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
597 }
598
599 (void) WaitLatch(MyLatch,
601 cur_timeout * 1000L /* convert to ms */ ,
602 WAIT_EVENT_CHECKPOINTER_MAIN);
603 }
604
605 /*
606 * From here on, elog(ERROR) should end with exit(1), not send control
607 * back to the sigsetjmp block above.
608 */
609 ExitOnAnyError = true;
610
612 {
613 /*
614 * Close down the database.
615 *
616 * Since ShutdownXLOG() creates restartpoint or checkpoint, and
617 * updates the statistics, increment the checkpoint request and flush
618 * out pending statistic.
619 */
621 ShutdownXLOG(0, 0);
623 pgstat_report_wal(true);
624
625 /*
626 * Tell postmaster that we're done.
627 */
629 ShutdownXLOGPending = false;
630 }
631
632 /*
633 * Wait until we're asked to shut down. By separating the writing of the
634 * shutdown checkpoint from checkpointer exiting, checkpointer can perform
635 * some should-be-as-late-as-possible work like writing out stats.
636 */
637 for (;;)
638 {
639 /* Clear any already-pending wakeups */
641
643
645 break;
646
647 (void) WaitLatch(MyLatch,
649 0,
650 WAIT_EVENT_CHECKPOINTER_SHUTDOWN);
651 }
652
653 /* Normal exit from the checkpointer is here */
654 proc_exit(0); /* done */
655}
static void UpdateSharedMemoryConfig(void)
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:169
static void ReqShutdownXLOG(SIGNAL_ARGS)
Definition: checkpointer.c:940
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:703
static double ckpt_cached_elapsed
Definition: checkpointer.c:170
static bool ckpt_active
Definition: checkpointer.c:164
static void ProcessCheckpointerInterrupts(void)
Definition: checkpointer.c:661
static volatile sig_atomic_t ShutdownXLOGPending
Definition: checkpointer.c:165
void AbsorbSyncRequests(void)
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:173
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
void ConditionVariableBroadcast(ConditionVariable *cv)
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1193
int errhint(const char *fmt,...)
Definition: elog.c:1330
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:150
int MyProcPid
Definition: globals.c:47
bool ExitOnAnyError
Definition: globals.c:123
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
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 DisableLogicalDecodingIfNecessary(void)
Definition: logicalctl.c:460
@ B_CHECKPOINTER
Definition: miscadmin.h:363
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:572
void pgstat_report_checkpointer(void)
PgStat_CheckpointerStats PendingCheckpointerStats
int64 pg_time_t
Definition: pgtime.h:23
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:165
@ PMSIGNAL_XLOG_IS_SHUTDOWN
Definition: pmsignal.h:44
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
PROC_HDR * ProcGlobal
Definition: proc.c:79
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:262
PgStat_Counter num_requested
Definition: pgstat.h:259
PgStat_Counter num_performed
Definition: pgstat.h:260
PgStat_Counter restartpoints_timed
Definition: pgstat.h:261
PgStat_Counter num_timed
Definition: pgstat.h:258
PgStat_Counter restartpoints_performed
Definition: pgstat.h:263
bool CreateRestartPoint(int flags)
Definition: xlog.c:7722
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:6609
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6729
int XLogArchiveTimeout
Definition: xlog.c:121
bool CreateCheckPoint(int flags)
Definition: xlog.c:7016
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:159
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:151
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:160
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)

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(), DisableLogicalDecodingIfNecessary(), 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 979 of file checkpointer.c.

980{
982 bool found;
983
985 ShmemInitStruct("Checkpointer Data",
986 size,
987 &found);
988
989 if (!found)
990 {
991 /*
992 * First time through, so initialize. Note that we zero the whole
993 * requests array; this is so that CompactCheckpointerRequestQueue can
994 * assume that any pad bytes in the request structs are zeroes.
995 */
996 MemSet(CheckpointerShmem, 0, size);
1002 }
1003}
#define MemSet(start, val, len)
Definition: c.h:1019
size_t Size
Definition: c.h:625
#define MAX_CHECKPOINT_REQUESTS
Definition: checkpointer.c:152
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:957
void ConditionVariableInit(ConditionVariable *cv)
int NBuffers
Definition: globals.c:142
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:389
#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 957 of file checkpointer.c.

958{
959 Size size;
960
961 /*
962 * The size of the requests[] array is arbitrarily set equal to NBuffers.
963 * But there is a cap of MAX_CHECKPOINT_REQUESTS to prevent accumulating
964 * too many checkpoint requests in the ring buffer.
965 */
966 size = offsetof(CheckpointerShmemStruct, requests);
967 size = add_size(size, mul_size(Min(NBuffers,
969 sizeof(CheckpointerRequest)));
970
971 return size;
972}
Size add_size(Size s1, Size s2)
Definition: shmem.c:495
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 791 of file checkpointer.c.

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

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().

◆ ExecCheckpoint()

void ExecCheckpoint ( ParseState pstate,
CheckPointStmt stmt 
)

Definition at line 1012 of file checkpointer.c.

1013{
1014 bool fast = true;
1015 bool unlogged = false;
1016
1017 foreach_ptr(DefElem, opt, stmt->options)
1018 {
1019 if (strcmp(opt->defname, "mode") == 0)
1020 {
1021 char *mode = defGetString(opt);
1022
1023 if (strcmp(mode, "spread") == 0)
1024 fast = false;
1025 else if (strcmp(mode, "fast") != 0)
1026 ereport(ERROR,
1027 (errcode(ERRCODE_SYNTAX_ERROR),
1028 errmsg("unrecognized value for %s option \"%s\": \"%s\"",
1029 "CHECKPOINT", "mode", mode),
1030 parser_errposition(pstate, opt->location)));
1031 }
1032 else if (strcmp(opt->defname, "flush_unlogged") == 0)
1033 unlogged = defGetBoolean(opt);
1034 else
1035 ereport(ERROR,
1036 (errcode(ERRCODE_SYNTAX_ERROR),
1037 errmsg("unrecognized %s option \"%s\"",
1038 "CHECKPOINT", opt->defname),
1039 parser_errposition(pstate, opt->location)));
1040 }
1041
1042 if (!has_privs_of_role(GetUserId(), ROLE_PG_CHECKPOINT))
1043 ereport(ERROR,
1044 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1045 /* translator: %s is name of an SQL command (e.g., CHECKPOINT) */
1046 errmsg("permission denied to execute %s command",
1047 "CHECKPOINT"),
1048 errdetail("Only roles with privileges of the \"%s\" role may execute this command.",
1049 "pg_checkpoint")));
1050
1052 (fast ? CHECKPOINT_FAST : 0) |
1053 (unlogged ? CHECKPOINT_FLUSH_UNLOGGED : 0) |
1055}
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5284
void RequestCheckpoint(int flags)
char * defGetString(DefElem *def)
Definition: define.c:35
bool defGetBoolean(DefElem *def)
Definition: define.c:94
int errdetail(const char *fmt,...)
Definition: elog.c:1216
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#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:56
#define foreach_ptr(type, var, lst)
Definition: pg_list.h:469
#define CHECKPOINT_FLUSH_UNLOGGED
Definition: xlog.h:154
#define CHECKPOINT_FORCE
Definition: xlog.h:153
#define CHECKPOINT_WAIT
Definition: xlog.h:156

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().

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1527 of file checkpointer.c.

1528{
1529 static int ckpt_done = 0;
1530 int new_done;
1531 bool FirstCall = false;
1532
1534 new_done = CheckpointerShmem->ckpt_done;
1536
1537 if (new_done != ckpt_done)
1538 FirstCall = true;
1539
1540 ckpt_done = new_done;
1541
1542 return FirstCall;
1543}

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

Referenced by BackgroundWriterMain().

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)

Definition at line 1225 of file checkpointer.c.

1226{
1227 CheckpointerRequest *request;
1228 bool too_full;
1229 int insert_pos;
1230
1231 if (!IsUnderPostmaster)
1232 return false; /* probably shouldn't even get here */
1233
1235 elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1236
1237 LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1238
1239 /*
1240 * If the checkpointer isn't running or the request queue is full, the
1241 * backend will have to perform its own fsync request. But before forcing
1242 * that to happen, we can try to compact the request queue.
1243 */
1247 {
1248 LWLockRelease(CheckpointerCommLock);
1249 return false;
1250 }
1251
1252 /* OK, insert request */
1253 insert_pos = CheckpointerShmem->tail;
1254 request = &CheckpointerShmem->requests[insert_pos];
1255 request->ftag = *ftag;
1256 request->type = type;
1257
1260
1261 /* If queue is more than half full, nudge the checkpointer to empty it */
1262 too_full = (CheckpointerShmem->num_requests >=
1264
1265 LWLockRelease(CheckpointerCommLock);
1266
1267 /* ... but not till after we release the lock */
1268 if (too_full)
1269 {
1270 volatile PROC_HDR *procglobal = ProcGlobal;
1271 ProcNumber checkpointerProc = procglobal->checkpointerProc;
1272
1273 if (checkpointerProc != INVALID_PROC_NUMBER)
1274 SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1275 }
1276
1277 return true;
1278}
static bool CompactCheckpointerRequestQueue(void)
#define elog(elevel,...)
Definition: elog.h:226
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().

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 1075 of file checkpointer.c.

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

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().

Variable Documentation

◆ BgWriterDelay

PGDLLIMPORT int BgWriterDelay
extern

Definition at line 58 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

◆ CheckPointCompletionTarget

PGDLLIMPORT double CheckPointCompletionTarget
extern

◆ CheckPointTimeout

PGDLLIMPORT int CheckPointTimeout
extern

Definition at line 157 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

PGDLLIMPORT int CheckPointWarning
extern

Definition at line 158 of file checkpointer.c.

Referenced by CheckpointerMain().