Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * checkpointer.c
4 : : *
5 : : * The checkpointer is new as of Postgres 9.2. It handles all checkpoints.
6 : : * Checkpoints are automatically dispatched after a certain amount of time has
7 : : * elapsed since the last one, and it can be signaled to perform requested
8 : : * checkpoints as well. (The GUC parameter that mandates a checkpoint every
9 : : * so many WAL segments is implemented by having backends signal when they
10 : : * fill WAL segments; the checkpointer itself doesn't watch for the
11 : : * condition.)
12 : : *
13 : : * The normal termination sequence is that checkpointer is instructed to
14 : : * execute the shutdown checkpoint by SIGINT. After that checkpointer waits
15 : : * to be terminated via SIGUSR2, which instructs the checkpointer to exit(0).
16 : : * All backends must be stopped before SIGINT or SIGUSR2 is issued!
17 : : *
18 : : * Emergency termination is by SIGQUIT; like any backend, the checkpointer
19 : : * will simply abort and exit on SIGQUIT.
20 : : *
21 : : * If the checkpointer exits unexpectedly, the postmaster treats that the same
22 : : * as a backend crash: shared memory may be corrupted, so remaining backends
23 : : * should be killed by SIGQUIT and then a recovery cycle started. (Even if
24 : : * shared memory isn't corrupted, we have lost information about which
25 : : * files need to be fsync'd for the next checkpoint, and so a system
26 : : * restart needs to be forced.)
27 : : *
28 : : *
29 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
30 : : *
31 : : *
32 : : * IDENTIFICATION
33 : : * src/backend/postmaster/checkpointer.c
34 : : *
35 : : *-------------------------------------------------------------------------
36 : : */
37 : : #include "postgres.h"
38 : :
39 : : #include <sys/time.h>
40 : : #include <time.h>
41 : :
42 : : #include "access/xlog.h"
43 : : #include "access/xlog_internal.h"
44 : : #include "access/xlogrecovery.h"
45 : : #include "catalog/pg_authid.h"
46 : : #include "commands/defrem.h"
47 : : #include "libpq/pqsignal.h"
48 : : #include "miscadmin.h"
49 : : #include "pgstat.h"
50 : : #include "postmaster/auxprocess.h"
51 : : #include "postmaster/bgwriter.h"
52 : : #include "postmaster/interrupt.h"
53 : : #include "replication/syncrep.h"
54 : : #include "storage/aio_subsys.h"
55 : : #include "storage/bufmgr.h"
56 : : #include "storage/condition_variable.h"
57 : : #include "storage/fd.h"
58 : : #include "storage/ipc.h"
59 : : #include "storage/lwlock.h"
60 : : #include "storage/pmsignal.h"
61 : : #include "storage/proc.h"
62 : : #include "storage/procsignal.h"
63 : : #include "storage/shmem.h"
64 : : #include "storage/smgr.h"
65 : : #include "storage/spin.h"
66 : : #include "storage/subsystems.h"
67 : : #include "utils/acl.h"
68 : : #include "utils/guc.h"
69 : : #include "utils/memutils.h"
70 : : #include "utils/resowner.h"
71 : : #include "utils/wait_event.h"
72 : :
73 : :
74 : : /*----------
75 : : * Shared memory area for communication between checkpointer and backends
76 : : *
77 : : * The ckpt counters allow backends to watch for completion of a checkpoint
78 : : * request they send. Here's how it works:
79 : : * * At start of a checkpoint, checkpointer reads (and clears) the request
80 : : * flags and increments ckpt_started, while holding ckpt_lck.
81 : : * * On completion of a checkpoint, checkpointer sets ckpt_done to
82 : : * equal ckpt_started.
83 : : * * On failure of a checkpoint, checkpointer increments ckpt_failed
84 : : * and sets ckpt_done to equal ckpt_started.
85 : : *
86 : : * The algorithm for backends is:
87 : : * 1. Record current values of ckpt_failed and ckpt_started, and
88 : : * set request flags, while holding ckpt_lck.
89 : : * 2. Send signal to request checkpoint.
90 : : * 3. Sleep until ckpt_started changes. Now you know a checkpoint has
91 : : * begun since you started this algorithm (although *not* that it was
92 : : * specifically initiated by your signal), and that it is using your flags.
93 : : * 4. Record new value of ckpt_started.
94 : : * 5. Sleep until ckpt_done >= saved value of ckpt_started. (Use modulo
95 : : * arithmetic here in case counters wrap around.) Now you know a
96 : : * checkpoint has started and completed, but not whether it was
97 : : * successful.
98 : : * 6. If ckpt_failed is different from the originally saved value,
99 : : * assume request failed; otherwise it was definitely successful.
100 : : *
101 : : * ckpt_flags holds the OR of the checkpoint request flags sent by all
102 : : * requesting backends since the last checkpoint start. The flags are
103 : : * chosen so that OR'ing is the correct way to combine multiple requests.
104 : : *
105 : : * The requests array holds fsync requests sent by backends and not yet
106 : : * absorbed by the checkpointer.
107 : : *
108 : : * Unlike the checkpoint fields, requests related fields are protected by
109 : : * CheckpointerCommLock.
110 : : *----------
111 : : */
112 : : typedef struct
113 : : {
114 : : SyncRequestType type; /* request type */
115 : : FileTag ftag; /* file identifier */
116 : : } CheckpointerRequest;
117 : :
118 : : typedef struct
119 : : {
120 : : pid_t checkpointer_pid; /* PID (0 if not started) */
121 : :
122 : : slock_t ckpt_lck; /* protects all the ckpt_* fields */
123 : :
124 : : int ckpt_started; /* advances when checkpoint starts */
125 : : int ckpt_done; /* advances when checkpoint done */
126 : : int ckpt_failed; /* advances when checkpoint fails */
127 : :
128 : : int ckpt_flags; /* checkpoint flags, as defined in xlog.h */
129 : :
130 : : ConditionVariable start_cv; /* signaled when ckpt_started advances */
131 : : ConditionVariable done_cv; /* signaled when ckpt_done advances */
132 : :
133 : : int num_requests; /* current # of requests */
134 : : int max_requests; /* allocated array size */
135 : :
136 : : int head; /* Index of the first request in the ring
137 : : * buffer */
138 : : int tail; /* Index of the last request in the ring
139 : : * buffer */
140 : :
141 : : /* The ring buffer of pending checkpointer requests */
142 : : CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER];
143 : : } CheckpointerShmemStruct;
144 : :
145 : : static CheckpointerShmemStruct *CheckpointerShmem;
146 : :
147 : : static void CheckpointerShmemRequest(void *arg);
148 : : static void CheckpointerShmemInit(void *arg);
149 : :
150 : : const ShmemCallbacks CheckpointerShmemCallbacks = {
151 : : .request_fn = CheckpointerShmemRequest,
152 : : .init_fn = CheckpointerShmemInit,
153 : : };
154 : :
155 : : /* interval for calling AbsorbSyncRequests in CheckpointWriteDelay */
156 : : #define WRITES_PER_ABSORB 1000
157 : :
158 : : /* Maximum number of checkpointer requests to process in one batch */
159 : : #define CKPT_REQ_BATCH_SIZE 10000
160 : :
161 : : /* Max number of requests the checkpointer request queue can hold */
162 : : #define MAX_CHECKPOINT_REQUESTS 10000000
163 : :
164 : : /*
165 : : * GUC parameters
166 : : */
167 : : int CheckPointTimeout = 300;
168 : : int CheckPointWarning = 30;
169 : : double CheckPointCompletionTarget = 0.9;
170 : :
171 : : /*
172 : : * Private state
173 : : */
174 : : static bool ckpt_active = false;
175 : : static volatile sig_atomic_t ShutdownXLOGPending = false;
176 : :
177 : : /* these values are valid when ckpt_active is true: */
178 : : static pg_time_t ckpt_start_time;
179 : : static XLogRecPtr ckpt_start_recptr;
180 : : static double ckpt_cached_elapsed;
181 : :
182 : : static pg_time_t last_checkpoint_time;
183 : : static pg_time_t last_xlog_switch_time;
184 : :
185 : : /* Prototypes for private functions */
186 : :
187 : : static void ProcessCheckpointerInterrupts(void);
188 : : static void CheckArchiveTimeout(void);
189 : : static bool IsCheckpointOnSchedule(double progress);
190 : : static bool FastCheckpointRequested(void);
191 : : static bool CompactCheckpointerRequestQueue(void);
192 : : static void UpdateSharedMemoryConfig(void);
193 : :
194 : : /* Signal handlers */
195 : : static void ReqShutdownXLOG(SIGNAL_ARGS);
196 : :
197 : :
198 : : /*
199 : : * Main entry point for checkpointer process
200 : : *
201 : : * This is invoked from AuxiliaryProcessMain, which has already created the
202 : : * basic execution environment, but not enabled signals yet.
203 : : */
204 : : void
438 peter@eisentraut.org 205 :CBC 638 : CheckpointerMain(const void *startup_data, size_t startup_data_len)
206 : : {
207 : : sigjmp_buf local_sigjmp_buf;
208 : : MemoryContext checkpointer_context;
209 : :
778 heikki.linnakangas@i 210 [ - + ]: 638 : Assert(startup_data_len == 0);
211 : :
212 : 638 : AuxiliaryProcessMainCommon();
213 : :
5109 simon@2ndQuadrant.co 214 : 638 : CheckpointerShmem->checkpointer_pid = MyProcPid;
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 : : */
2331 rhaas@postgresql.org 224 : 638 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
465 andres@anarazel.de 225 : 638 : pqsignal(SIGINT, ReqShutdownXLOG);
21 andrew@dunslane.net 226 :GNC 638 : pqsignal(SIGTERM, PG_SIG_IGN); /* ignore SIGTERM */
227 : : /* SIGQUIT handler was already set up by InitPostmasterChild */
228 : 638 : pqsignal(SIGALRM, PG_SIG_IGN);
229 : 638 : pqsignal(SIGPIPE, PG_SIG_IGN);
2353 rhaas@postgresql.org 230 :CBC 638 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
2331 231 : 638 : pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
232 : :
233 : : /*
234 : : * Reset some signals that are accepted by postmaster but not here
235 : : */
21 andrew@dunslane.net 236 :GNC 638 : pqsignal(SIGCHLD, PG_SIG_DFL);
237 : :
238 : : /*
239 : : * Initialize so that first time-driven event happens at the correct time.
240 : : */
5299 simon@2ndQuadrant.co 241 :CBC 638 : last_checkpoint_time = last_xlog_switch_time = (pg_time_t) time(NULL);
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 : : */
1490 andres@anarazel.de 254 : 638 : before_shmem_exit(pgstat_before_server_shutdown, 0);
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 : : */
5299 simon@2ndQuadrant.co 262 : 638 : checkpointer_context = AllocSetContextCreate(TopMemoryContext,
263 : : "Checkpointer",
264 : : ALLOCSET_DEFAULT_SIZES);
265 : 638 : MemoryContextSwitchTo(checkpointer_context);
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 [ - + ]: 638 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
286 : : {
287 : : /* Since not using PG_TRY, must reset error stack by hand */
5299 simon@2ndQuadrant.co 288 :UBC 0 : error_context_stack = NULL;
289 : :
290 : : /* Prevent interrupts while cleaning up */
291 : 0 : HOLD_INTERRUPTS();
292 : :
293 : : /* Report the error to the server log */
294 : 0 : EmitErrorReport();
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 : : */
302 : 0 : LWLockReleaseAll();
3451 rhaas@postgresql.org 303 : 0 : ConditionVariableCancelSleep();
3708 304 : 0 : pgstat_report_wait_end();
414 andres@anarazel.de 305 : 0 : pgaio_error_cleanup();
5299 simon@2ndQuadrant.co 306 : 0 : UnlockBuffers();
2848 tgl@sss.pgh.pa.us 307 : 0 : ReleaseAuxProcessResources(false);
5299 simon@2ndQuadrant.co 308 : 0 : AtEOXact_Buffers(false);
4948 tgl@sss.pgh.pa.us 309 : 0 : AtEOXact_SMgr();
2929 310 : 0 : AtEOXact_Files(false);
5299 simon@2ndQuadrant.co 311 : 0 : AtEOXact_HashTables(false);
312 : :
313 : : /* Warn any waiting backends that the checkpoint failed. */
314 [ # # ]: 0 : if (ckpt_active)
315 : : {
3864 rhaas@postgresql.org 316 [ # # ]: 0 : SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
317 : 0 : CheckpointerShmem->ckpt_failed++;
318 : 0 : CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
319 : 0 : SpinLockRelease(&CheckpointerShmem->ckpt_lck);
320 : :
2586 tmunro@postgresql.or 321 : 0 : ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
322 : :
5299 simon@2ndQuadrant.co 323 : 0 : ckpt_active = false;
324 : : }
325 : :
326 : : /*
327 : : * Now return to normal top-level context and clear ErrorContext for
328 : : * next time.
329 : : */
330 : 0 : MemoryContextSwitchTo(checkpointer_context);
331 : 0 : FlushErrorState();
332 : :
333 : : /* Flush any leaked data in the top-level context */
902 nathan@postgresql.or 334 : 0 : MemoryContextReset(checkpointer_context);
335 : :
336 : : /* Now we can allow interrupts again */
5299 simon@2ndQuadrant.co 337 [ # # ]: 0 : RESUME_INTERRUPTS();
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 : 0 : pg_usleep(1000000L);
345 : : }
346 : :
347 : : /* We can now handle ereport(ERROR) */
5299 simon@2ndQuadrant.co 348 :CBC 638 : PG_exception_stack = &local_sigjmp_buf;
349 : :
350 : : /*
351 : : * Unblock signals (they were blocked when the postmaster forked us)
352 : : */
1187 tmunro@postgresql.or 353 : 638 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
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 : : */
5214 simon@2ndQuadrant.co 359 : 638 : UpdateSharedMemoryConfig();
360 : :
361 : : /*
362 : : * Advertise our proc number that backends can use to wake us up while
363 : : * we're sleeping.
364 : : */
550 heikki.linnakangas@i 365 : 638 : ProcGlobal->checkpointerProc = MyProcNumber;
366 : :
367 : : /*
368 : : * Loop until we've been asked to write the shutdown checkpoint or
369 : : * terminate.
370 : : */
371 : : for (;;)
5299 simon@2ndQuadrant.co 372 : 5767 : {
373 : 6405 : bool do_checkpoint = false;
374 : 6405 : int flags = 0;
375 : : pg_time_t now;
376 : : int elapsed_secs;
377 : : int cur_timeout;
862 akorotkov@postgresql 378 : 6405 : bool chkpt_or_rstpt_requested = false;
379 : 6405 : bool chkpt_or_rstpt_timed = false;
380 : :
381 : : /* Clear any already-pending wakeups */
4129 andres@anarazel.de 382 : 6405 : ResetLatch(MyLatch);
383 : :
384 : : /*
385 : : * Process any requests or signals received recently.
386 : : */
2588 tmunro@postgresql.or 387 : 6405 : AbsorbSyncRequests();
388 : :
426 heikki.linnakangas@i 389 : 6405 : ProcessCheckpointerInterrupts();
465 andres@anarazel.de 390 [ + + + - ]: 6405 : if (ShutdownXLOGPending || ShutdownRequestPending)
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 : : */
2604 tgl@sss.pgh.pa.us 398 [ + + ]: 5775 : if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
399 : : {
400 : 1393 : do_checkpoint = true;
862 akorotkov@postgresql 401 : 1393 : chkpt_or_rstpt_requested = 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 : : */
5299 simon@2ndQuadrant.co 410 : 5775 : now = (pg_time_t) time(NULL);
411 : 5775 : elapsed_secs = now - last_checkpoint_time;
412 [ - + ]: 5775 : if (elapsed_secs >= CheckPointTimeout)
413 : : {
5299 simon@2ndQuadrant.co 414 [ # # ]:LBC (1) : if (!do_checkpoint)
862 akorotkov@postgresql 415 : (1) : chkpt_or_rstpt_timed = true;
5299 simon@2ndQuadrant.co 416 : (1) : do_checkpoint = true;
417 : (1) : flags |= CHECKPOINT_CAUSE_TIME;
418 : : }
419 : :
420 : : /*
421 : : * Do a checkpoint if requested.
422 : : */
5299 simon@2ndQuadrant.co 423 [ + + ]:CBC 5775 : if (do_checkpoint)
424 : : {
425 : 1393 : bool ckpt_performed = false;
426 : : bool do_restartpoint;
427 : :
428 : : /* Check if we should perform a checkpoint or a restartpoint. */
429 : 1393 : do_restartpoint = RecoveryInProgress();
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 : : */
3864 rhaas@postgresql.org 436 [ - + ]: 1393 : SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
437 : 1393 : flags |= CheckpointerShmem->ckpt_flags;
438 : 1393 : CheckpointerShmem->ckpt_flags = 0;
439 : 1393 : CheckpointerShmem->ckpt_started++;
440 : 1393 : SpinLockRelease(&CheckpointerShmem->ckpt_lck);
441 : :
2609 tmunro@postgresql.or 442 : 1393 : ConditionVariableBroadcast(&CheckpointerShmem->start_cv);
443 : :
444 : : /*
445 : : * The end-of-recovery checkpoint is a real checkpoint that's
446 : : * performed while we're still in recovery.
447 : : */
5299 simon@2ndQuadrant.co 448 [ + + ]: 1393 : if (flags & CHECKPOINT_END_OF_RECOVERY)
449 : 21 : do_restartpoint = false;
450 : :
862 akorotkov@postgresql 451 [ - + ]: 1393 : if (chkpt_or_rstpt_timed)
452 : : {
862 akorotkov@postgresql 453 :LBC (1) : chkpt_or_rstpt_timed = false;
454 [ # # ]: (1) : if (do_restartpoint)
455 : (1) : PendingCheckpointerStats.restartpoints_timed++;
456 : : else
862 akorotkov@postgresql 457 :UBC 0 : PendingCheckpointerStats.num_timed++;
458 : : }
459 : :
862 akorotkov@postgresql 460 [ + - ]:CBC 1393 : if (chkpt_or_rstpt_requested)
461 : : {
462 : 1393 : chkpt_or_rstpt_requested = false;
463 [ + + ]: 1393 : if (do_restartpoint)
464 : 593 : PendingCheckpointerStats.restartpoints_requested++;
465 : : else
466 : 800 : PendingCheckpointerStats.num_requested++;
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 : : */
5299 simon@2ndQuadrant.co 476 [ + + ]: 1393 : if (!do_restartpoint &&
477 [ + + ]: 800 : (flags & CHECKPOINT_CAUSE_XLOG) &&
478 [ + + ]: 209 : elapsed_secs < CheckPointWarning)
479 [ + - ]: 207 : ereport(LOG,
480 : : (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
481 : : "checkpoints are occurring too frequently (%d seconds apart)",
482 : : elapsed_secs,
483 : : elapsed_secs),
484 : : errhint("Consider increasing the configuration parameter \"%s\".", "max_wal_size")));
485 : :
486 : : /*
487 : : * Initialize checkpointer-private variables used during
488 : : * checkpoint.
489 : : */
490 : 1393 : ckpt_active = true;
3963 heikki.linnakangas@i 491 [ + + ]: 1393 : if (do_restartpoint)
492 : 593 : ckpt_start_recptr = GetXLogReplayRecPtr(NULL);
493 : : else
5299 simon@2ndQuadrant.co 494 : 800 : ckpt_start_recptr = GetInsertRecPtr();
495 : 1393 : ckpt_start_time = now;
496 : 1393 : ckpt_cached_elapsed = 0;
497 : :
498 : : /*
499 : : * Do the checkpoint.
500 : : */
501 [ + + ]: 1393 : if (!do_restartpoint)
582 fujii@postgresql.org 502 : 800 : ckpt_performed = CreateCheckPoint(flags);
503 : : else
5299 simon@2ndQuadrant.co 504 : 593 : ckpt_performed = CreateRestartPoint(flags);
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 : : */
825 heikki.linnakangas@i 512 : 1393 : smgrdestroyall();
513 : :
514 : : /*
515 : : * Indicate checkpoint completion to any waiting backends.
516 : : */
3864 rhaas@postgresql.org 517 [ - + ]: 1393 : SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
518 : 1393 : CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
519 : 1393 : SpinLockRelease(&CheckpointerShmem->ckpt_lck);
520 : :
2609 tmunro@postgresql.or 521 : 1393 : ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
522 : :
582 fujii@postgresql.org 523 [ + + ]: 1393 : 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 : : */
5299 simon@2ndQuadrant.co 530 : 800 : last_checkpoint_time = now;
531 : :
582 fujii@postgresql.org 532 [ + + ]: 800 : if (ckpt_performed)
533 : 798 : PendingCheckpointerStats.num_performed++;
534 : : }
535 : : else
536 : : {
537 [ + + ]: 593 : if (ckpt_performed)
538 : : {
539 : : /*
540 : : * The same as for checkpoint. Please see the
541 : : * corresponding comment.
542 : : */
543 : 188 : last_checkpoint_time = now;
544 : :
545 : 188 : PendingCheckpointerStats.restartpoints_performed++;
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 : : */
556 : 405 : last_checkpoint_time = now - CheckPointTimeout + 15;
557 : : }
558 : : }
559 : :
5299 simon@2ndQuadrant.co 560 : 1393 : 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 : : */
426 heikki.linnakangas@i 566 : 1393 : ProcessCheckpointerInterrupts();
465 andres@anarazel.de 567 [ + + + - ]: 1393 : if (ShutdownXLOGPending || ShutdownRequestPending)
568 : : break;
569 : : }
570 : :
571 : : /*
572 : : * Disable logical decoding if someone requested it. See comments atop
573 : : * logicalctl.c.
574 : : */
133 msawada@postgresql.o 575 :GNC 5770 : DisableLogicalDecodingIfNecessary();
576 : :
577 : : /* Check for archive_timeout and switch xlog files if necessary. */
5110 tgl@sss.pgh.pa.us 578 :CBC 5770 : CheckArchiveTimeout();
579 : :
580 : : /* Report pending statistics to the cumulative stats system */
1490 andres@anarazel.de 581 : 5770 : pgstat_report_checkpointer();
582 : 5770 : 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 : : */
2197 alvherre@alvh.no-ip. 588 [ + + ]: 5770 : if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
589 : 286 : continue;
590 : :
591 : : /*
592 : : * Sleep until we are signaled or it's time for another checkpoint or
593 : : * xlog file switch.
594 : : */
5110 tgl@sss.pgh.pa.us 595 : 5484 : now = (pg_time_t) time(NULL);
596 : 5484 : elapsed_secs = now - last_checkpoint_time;
597 [ - + ]: 5484 : if (elapsed_secs >= CheckPointTimeout)
5110 tgl@sss.pgh.pa.us 598 :UBC 0 : continue; /* no sleep for us ... */
5110 tgl@sss.pgh.pa.us 599 :CBC 5484 : cur_timeout = CheckPointTimeout - elapsed_secs;
600 [ - + - - ]: 5484 : if (XLogArchiveTimeout > 0 && !RecoveryInProgress())
601 : : {
5110 tgl@sss.pgh.pa.us 602 :UBC 0 : elapsed_secs = now - last_xlog_switch_time;
603 [ # # ]: 0 : if (elapsed_secs >= XLogArchiveTimeout)
604 : 0 : continue; /* no sleep for us ... */
605 : 0 : cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
606 : : }
607 : :
2720 tmunro@postgresql.or 608 :CBC 5484 : (void) WaitLatch(MyLatch,
609 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
610 : : cur_timeout * 1000L /* convert to ms */ ,
611 : : WAIT_EVENT_CHECKPOINTER_MAIN);
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 : : */
465 andres@anarazel.de 618 : 635 : ExitOnAnyError = true;
619 : :
620 [ + - ]: 635 : if (ShutdownXLOGPending)
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 : : */
629 : 635 : PendingCheckpointerStats.num_requested++;
630 : 635 : ShutdownXLOG(0, 0);
631 : 635 : pgstat_report_checkpointer();
632 : 635 : pgstat_report_wal(true);
633 : :
634 : : /*
635 : : * Tell postmaster that we're done.
636 : : */
637 : 635 : SendPostmasterSignal(PMSIGNAL_XLOG_IS_SHUTDOWN);
638 : 635 : 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 */
649 : 1320 : ResetLatch(MyLatch);
650 : :
426 heikki.linnakangas@i 651 : 1320 : ProcessCheckpointerInterrupts();
652 : :
465 andres@anarazel.de 653 [ + + ]: 1320 : if (ShutdownRequestPending)
654 : 635 : break;
655 : :
656 : 685 : (void) WaitLatch(MyLatch,
657 : : WL_LATCH_SET | WL_EXIT_ON_PM_DEATH,
658 : : 0,
659 : : WAIT_EVENT_CHECKPOINTER_SHUTDOWN);
660 : : }
661 : :
662 : : /* Normal exit from the checkpointer is here */
663 : 635 : proc_exit(0); /* done */
664 : : }
665 : :
666 : : /*
667 : : * Process any new interrupts.
668 : : */
669 : : static void
426 heikki.linnakangas@i 670 : 9118 : ProcessCheckpointerInterrupts(void)
671 : : {
2329 rhaas@postgresql.org 672 [ + + ]: 9118 : if (ProcSignalBarrierPending)
673 : 402 : ProcessProcSignalBarrier();
674 : :
2331 675 [ + + ]: 9118 : if (ConfigReloadPending)
676 : : {
677 : 94 : ConfigReloadPending = false;
678 : 94 : ProcessConfigFile(PGC_SIGHUP);
679 : :
680 : : /*
681 : : * Checkpointer is the last process to shut down, so we ask it to hold
682 : : * the keys for a range of other tasks required most of which have
683 : : * nothing to do with checkpointing at all.
684 : : *
685 : : * For various reasons, some config values can change dynamically so
686 : : * the primary copy of them is held in shared memory to make sure all
687 : : * backends see the same value. We make Checkpointer responsible for
688 : : * updating the shared memory copy if the parameter setting changes
689 : : * because of SIGHUP.
690 : : */
691 : 94 : UpdateSharedMemoryConfig();
692 : : }
693 : :
694 : : /* Perform logging of memory contexts of this process */
1575 fujii@postgresql.org 695 [ + + ]: 9118 : if (LogMemoryContextPending)
696 : 1 : ProcessLogMemoryContextInterrupt();
2331 rhaas@postgresql.org 697 : 9118 : }
698 : :
699 : : /*
700 : : * CheckArchiveTimeout -- check for archive_timeout and switch xlog files
701 : : *
702 : : * This will switch to a new WAL file and force an archive file write if
703 : : * meaningful activity is recorded in the current WAL file. This includes most
704 : : * writes, including just a single checkpoint record, but excludes WAL records
705 : : * that were inserted with the XLOG_MARK_UNIMPORTANT flag being set (like
706 : : * snapshots of running transactions). Such records, depending on
707 : : * configuration, occur on regular intervals and don't contain important
708 : : * information. This avoids generating archives with a few unimportant
709 : : * records.
710 : : */
711 : : static void
5299 simon@2ndQuadrant.co 712 : 14338 : CheckArchiveTimeout(void)
713 : : {
714 : : pg_time_t now;
715 : : pg_time_t last_time;
716 : : XLogRecPtr last_switch_lsn;
717 : :
718 [ - + - - ]: 14338 : if (XLogArchiveTimeout <= 0 || RecoveryInProgress())
719 : 14338 : return;
720 : :
5299 simon@2ndQuadrant.co 721 :UBC 0 : now = (pg_time_t) time(NULL);
722 : :
723 : : /* First we do a quick check using possibly-stale local state. */
724 [ # # ]: 0 : if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
725 : 0 : return;
726 : :
727 : : /*
728 : : * Update local state ... note that last_xlog_switch_time is the last time
729 : : * a switch was performed *or requested*.
730 : : */
3421 andres@anarazel.de 731 : 0 : last_time = GetLastSegSwitchData(&last_switch_lsn);
732 : :
5299 simon@2ndQuadrant.co 733 : 0 : last_xlog_switch_time = Max(last_xlog_switch_time, last_time);
734 : :
735 : : /* Now we can do the real checks */
736 [ # # ]: 0 : if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
737 : : {
738 : : /*
739 : : * Switch segment only when "important" WAL has been logged since the
740 : : * last segment switch (last_switch_lsn points to end of segment
741 : : * switch occurred in).
742 : : */
3421 andres@anarazel.de 743 [ # # ]: 0 : if (GetLastImportantRecPtr() > last_switch_lsn)
744 : : {
745 : : XLogRecPtr switchpoint;
746 : :
747 : : /* mark switch as unimportant, avoids triggering checkpoints */
748 : 0 : switchpoint = RequestXLogSwitch(true);
749 : :
750 : : /*
751 : : * If the returned pointer points exactly to a segment boundary,
752 : : * assume nothing happened.
753 : : */
3150 754 [ # # ]: 0 : if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
608 michael@paquier.xyz 755 [ # # ]: 0 : elog(DEBUG1, "write-ahead log switch forced (\"archive_timeout\"=%d)",
756 : : XLogArchiveTimeout);
757 : : }
758 : :
759 : : /*
760 : : * Update state in any case, so we don't retry constantly when the
761 : : * system is idle.
762 : : */
5299 simon@2ndQuadrant.co 763 : 0 : last_xlog_switch_time = now;
764 : : }
765 : : }
766 : :
767 : : /*
768 : : * Returns true if a fast checkpoint request is pending. (Note that this does
769 : : * not check the *current* checkpoint's FAST flag, but whether there is one
770 : : * pending behind it.)
771 : : */
772 : : static bool
298 nathan@postgresql.or 773 :GNC 51776 : FastCheckpointRequested(void)
774 : : {
2604 tgl@sss.pgh.pa.us 775 :CBC 51776 : volatile CheckpointerShmemStruct *cps = CheckpointerShmem;
776 : :
777 : : /*
778 : : * We don't need to acquire the ckpt_lck in this case because we're only
779 : : * looking at a single flag bit.
780 : : */
298 nathan@postgresql.or 781 [ + + ]:GNC 51776 : if (cps->ckpt_flags & CHECKPOINT_FAST)
2604 tgl@sss.pgh.pa.us 782 :CBC 6425 : return true;
5299 simon@2ndQuadrant.co 783 : 45351 : return false;
784 : : }
785 : :
786 : : /*
787 : : * CheckpointWriteDelay -- control rate of checkpoint
788 : : *
789 : : * This function is called after each page write performed by BufferSync().
790 : : * It is responsible for throttling BufferSync()'s write rate to hit
791 : : * checkpoint_completion_target.
792 : : *
793 : : * The checkpoint request flags should be passed in; currently the only one
794 : : * examined is CHECKPOINT_FAST, which disables delays between writes.
795 : : *
796 : : * 'progress' is an estimate of how much of the work has been done, as a
797 : : * fraction between 0.0 meaning none, and 1.0 meaning all done.
798 : : */
799 : : void
800 : 344186 : CheckpointWriteDelay(int flags, double progress)
801 : : {
802 : : static int absorb_counter = WRITES_PER_ABSORB;
803 : :
804 : : /* Do nothing if checkpoint is being executed by non-checkpointer process */
5039 tgl@sss.pgh.pa.us 805 [ + + ]: 344186 : if (!AmCheckpointerProcess())
5299 simon@2ndQuadrant.co 806 : 59236 : 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 : : */
298 nathan@postgresql.or 812 [ + + ]:GNC 284950 : if (!(flags & CHECKPOINT_FAST) &&
465 andres@anarazel.de 813 [ + + ]:CBC 51821 : !ShutdownXLOGPending &&
2331 rhaas@postgresql.org 814 [ + - ]: 51776 : !ShutdownRequestPending &&
298 nathan@postgresql.or 815 [ + + + + ]:GNC 97127 : !FastCheckpointRequested() &&
5299 simon@2ndQuadrant.co 816 :CBC 45351 : IsCheckpointOnSchedule(progress))
817 : : {
2331 rhaas@postgresql.org 818 [ - + ]: 8568 : if (ConfigReloadPending)
819 : : {
2331 rhaas@postgresql.org 820 :UBC 0 : ConfigReloadPending = false;
5299 simon@2ndQuadrant.co 821 : 0 : ProcessConfigFile(PGC_SIGHUP);
822 : : /* update shmem copies of config variables */
5209 823 : 0 : UpdateSharedMemoryConfig();
824 : : }
825 : :
2588 tmunro@postgresql.or 826 :CBC 8568 : AbsorbSyncRequests();
5299 simon@2ndQuadrant.co 827 : 8568 : absorb_counter = WRITES_PER_ABSORB;
828 : :
829 : 8568 : CheckArchiveTimeout();
830 : :
831 : : /* Report interim statistics to the cumulative stats system */
1490 andres@anarazel.de 832 : 8568 : pgstat_report_checkpointer();
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 : : */
1511 tmunro@postgresql.or 840 : 8568 : WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH | WL_TIMEOUT,
841 : : 100,
842 : : WAIT_EVENT_CHECKPOINT_WRITE_DELAY);
843 : 8568 : ResetLatch(MyLatch);
844 : : }
5299 simon@2ndQuadrant.co 845 [ + + ]: 276382 : 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 : : */
2588 tmunro@postgresql.or 852 : 161 : AbsorbSyncRequests();
5299 simon@2ndQuadrant.co 853 : 161 : absorb_counter = WRITES_PER_ABSORB;
854 : : }
855 : :
856 : : /* Check for barrier events. */
2329 rhaas@postgresql.org 857 [ + + ]: 284950 : if (ProcSignalBarrierPending)
858 : 10 : ProcessProcSignalBarrier();
859 : : }
860 : :
861 : : /*
862 : : * IsCheckpointOnSchedule -- are we on schedule to finish this checkpoint
863 : : * (or restartpoint) in time?
864 : : *
865 : : * Compares the current progress against the time/segments elapsed since last
866 : : * checkpoint, and returns true if the progress we've made this far is greater
867 : : * than the elapsed time/segments.
868 : : */
869 : : static bool
5299 simon@2ndQuadrant.co 870 : 45351 : IsCheckpointOnSchedule(double progress)
871 : : {
872 : : XLogRecPtr recptr;
873 : : struct timeval now;
874 : : double elapsed_xlogs,
875 : : elapsed_time;
876 : :
877 [ - + ]: 45351 : Assert(ckpt_active);
878 : :
879 : : /* Scale progress according to checkpoint_completion_target. */
880 : 45351 : progress *= CheckPointCompletionTarget;
881 : :
882 : : /*
883 : : * Check against the cached value first. Only do the more expensive
884 : : * calculations once we reach the target previously calculated. Since
885 : : * neither time or WAL insert pointer moves backwards, a freshly
886 : : * calculated value can only be greater than or equal to the cached value.
887 : : */
888 [ + + ]: 45351 : if (progress < ckpt_cached_elapsed)
889 : 32245 : return false;
890 : :
891 : : /*
892 : : * Check progress against WAL segments written and CheckPointSegments.
893 : : *
894 : : * We compare the current WAL insert location against the location
895 : : * computed before calling CreateCheckPoint. The code in XLogInsert that
896 : : * actually triggers a checkpoint when CheckPointSegments is exceeded
897 : : * compares against RedoRecPtr, so this is not completely accurate.
898 : : * However, it's good enough for our purposes, we're only calculating an
899 : : * estimate anyway.
900 : : *
901 : : * During recovery, we compare last replayed WAL record's location with
902 : : * the location computed before calling CreateRestartPoint. That maintains
903 : : * the same pacing as we have during checkpoints in normal operation, but
904 : : * we might exceed max_wal_size by a fair amount. That's because there can
905 : : * be a large gap between a checkpoint's redo-pointer and the checkpoint
906 : : * record itself, and we only start the restartpoint after we've seen the
907 : : * checkpoint record. (The gap is typically up to CheckPointSegments *
908 : : * checkpoint_completion_target where checkpoint_completion_target is the
909 : : * value that was in effect when the WAL was generated).
910 : : */
3963 heikki.linnakangas@i 911 [ + + ]: 13106 : if (RecoveryInProgress())
912 : 5599 : recptr = GetXLogReplayRecPtr(NULL);
913 : : else
5299 simon@2ndQuadrant.co 914 : 7507 : recptr = GetInsertRecPtr();
3150 andres@anarazel.de 915 : 13106 : elapsed_xlogs = (((double) (recptr - ckpt_start_recptr)) /
916 : 13106 : wal_segment_size) / CheckPointSegments;
917 : :
3963 heikki.linnakangas@i 918 [ + + ]: 13106 : if (progress < elapsed_xlogs)
919 : : {
920 : 4534 : ckpt_cached_elapsed = elapsed_xlogs;
921 : 4534 : return false;
922 : : }
923 : :
924 : : /*
925 : : * Check progress against time elapsed and checkpoint_timeout.
926 : : */
5299 simon@2ndQuadrant.co 927 : 8572 : gettimeofday(&now, NULL);
928 : 8572 : elapsed_time = ((double) ((pg_time_t) now.tv_sec - ckpt_start_time) +
929 : 8572 : now.tv_usec / 1000000.0) / CheckPointTimeout;
930 : :
931 [ + + ]: 8572 : if (progress < elapsed_time)
932 : : {
933 : 4 : ckpt_cached_elapsed = elapsed_time;
934 : 4 : return false;
935 : : }
936 : :
937 : : /* It looks like we're on schedule. */
938 : 8568 : return true;
939 : : }
940 : :
941 : :
942 : : /* --------------------------------
943 : : * signal handler routines
944 : : * --------------------------------
945 : : */
946 : :
947 : : /* SIGINT: set flag to trigger writing of shutdown checkpoint */
948 : : static void
465 andres@anarazel.de 949 : 771 : ReqShutdownXLOG(SIGNAL_ARGS)
950 : : {
951 : 771 : ShutdownXLOGPending = true;
952 : 771 : SetLatch(MyLatch);
953 : 771 : }
954 : :
955 : :
956 : : /* --------------------------------
957 : : * communication with backends
958 : : * --------------------------------
959 : : */
960 : :
961 : : /*
962 : : * CheckpointerShmemRequest
963 : : * Register shared memory space needed for checkpointer
964 : : */
965 : : static void
29 heikki.linnakangas@i 966 :GNC 1244 : CheckpointerShmemRequest(void *arg)
967 : : {
968 : : Size size;
969 : :
970 : : /*
971 : : * The size of the requests[] array is arbitrarily set equal to NBuffers.
972 : : * But there is a cap of MAX_CHECKPOINT_REQUESTS to prevent accumulating
973 : : * too many checkpoint requests in the ring buffer.
974 : : */
5109 simon@2ndQuadrant.co 975 :CBC 1244 : size = offsetof(CheckpointerShmemStruct, requests);
271 akorotkov@postgresql 976 : 1244 : size = add_size(size, mul_size(Min(NBuffers,
977 : : MAX_CHECKPOINT_REQUESTS),
978 : : sizeof(CheckpointerRequest)));
29 heikki.linnakangas@i 979 :GNC 1244 : ShmemRequestStruct(.name = "Checkpointer Data",
980 : : .size = size,
981 : : .ptr = (void **) &CheckpointerShmem,
982 : : );
5299 simon@2ndQuadrant.co 983 :GIC 1244 : }
984 : :
985 : : /*
986 : : * CheckpointerShmemInit
987 : : * Initialize checkpointer-related shared memory
988 : : */
989 : : static void
29 heikki.linnakangas@i 990 :GNC 1241 : CheckpointerShmemInit(void *arg)
991 : : {
992 : 1241 : SpinLockInit(&CheckpointerShmem->ckpt_lck);
993 : 1241 : CheckpointerShmem->max_requests = Min(NBuffers, MAX_CHECKPOINT_REQUESTS);
994 : 1241 : CheckpointerShmem->head = CheckpointerShmem->tail = 0;
995 : 1241 : ConditionVariableInit(&CheckpointerShmem->start_cv);
996 : 1241 : ConditionVariableInit(&CheckpointerShmem->done_cv);
5299 simon@2ndQuadrant.co 997 : 1241 : }
998 : :
999 : : /*
1000 : : * ExecCheckpoint
1001 : : * Primary entry point for manual CHECKPOINT commands
1002 : : *
1003 : : * This is mainly a wrapper for RequestCheckpoint().
1004 : : */
1005 : : void
298 nathan@postgresql.or 1006 : 460 : ExecCheckpoint(ParseState *pstate, CheckPointStmt *stmt)
1007 : : {
1008 : 460 : bool fast = true;
1009 : 460 : bool unlogged = false;
1010 : :
1011 [ + + + + : 924 : foreach_ptr(DefElem, opt, stmt->options)
+ + ]
1012 : : {
1013 [ + + ]: 20 : if (strcmp(opt->defname, "mode") == 0)
1014 : : {
1015 : 8 : char *mode = defGetString(opt);
1016 : :
1017 [ - + ]: 8 : if (strcmp(mode, "spread") == 0)
298 nathan@postgresql.or 1018 :UNC 0 : fast = false;
298 nathan@postgresql.or 1019 [ + + ]:GNC 8 : else if (strcmp(mode, "fast") != 0)
1020 [ + - ]: 4 : ereport(ERROR,
1021 : : (errcode(ERRCODE_SYNTAX_ERROR),
1022 : : errmsg("unrecognized value for %s option \"%s\": \"%s\"",
1023 : : "CHECKPOINT", "mode", mode),
1024 : : parser_errposition(pstate, opt->location)));
1025 : : }
1026 [ + + ]: 12 : else if (strcmp(opt->defname, "flush_unlogged") == 0)
1027 : 8 : unlogged = defGetBoolean(opt);
1028 : : else
1029 [ + - ]: 4 : ereport(ERROR,
1030 : : (errcode(ERRCODE_SYNTAX_ERROR),
1031 : : errmsg("unrecognized %s option \"%s\"",
1032 : : "CHECKPOINT", opt->defname),
1033 : : parser_errposition(pstate, opt->location)));
1034 : : }
1035 : :
1036 [ - + ]: 452 : if (!has_privs_of_role(GetUserId(), ROLE_PG_CHECKPOINT))
298 nathan@postgresql.or 1037 [ # # ]:UNC 0 : ereport(ERROR,
1038 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
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 : :
298 nathan@postgresql.or 1045 [ + - ]:GNC 904 : RequestCheckpoint(CHECKPOINT_WAIT |
1046 : 452 : (fast ? CHECKPOINT_FAST : 0) |
1047 [ + + ]: 452 : (unlogged ? CHECKPOINT_FLUSH_UNLOGGED : 0) |
1048 [ + + ]: 452 : (RecoveryInProgress() ? 0 : CHECKPOINT_FORCE));
298 nathan@postgresql.or 1049 :CBC 452 : }
1050 : :
1051 : : /*
1052 : : * RequestCheckpoint
1053 : : * Called in backend processes to request a checkpoint
1054 : : *
1055 : : * flags is a bitwise OR of the following:
1056 : : * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
1057 : : * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
1058 : : * CHECKPOINT_FAST: finish the checkpoint ASAP,
1059 : : * ignoring checkpoint_completion_target parameter.
1060 : : * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
1061 : : * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
1062 : : * CHECKPOINT_END_OF_RECOVERY, and the CHECKPOINT command).
1063 : : * CHECKPOINT_WAIT: wait for completion before returning (otherwise,
1064 : : * just signal checkpointer to do it, and return).
1065 : : * CHECKPOINT_CAUSE_XLOG: checkpoint is requested due to xlog filling.
1066 : : * (This affects logging, and in particular enables CheckPointWarning.)
1067 : : */
1068 : : void
5299 simon@2ndQuadrant.co 1069 : 2619 : RequestCheckpoint(int flags)
1070 : : {
1071 : : int ntries;
1072 : : int old_failed,
1073 : : old_started;
1074 : :
1075 : : /*
1076 : : * If in a standalone backend, just do it ourselves.
1077 : : */
1078 [ + + ]: 2619 : if (!IsPostmasterEnvironment)
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 : : */
298 nathan@postgresql.or 1084 :GNC 229 : CreateCheckPoint(flags | CHECKPOINT_FAST);
1085 : :
1086 : : /* Free all smgr objects, as CheckpointerMain() normally would. */
825 heikki.linnakangas@i 1087 :CBC 229 : smgrdestroyall();
1088 : :
5299 simon@2ndQuadrant.co 1089 : 229 : 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 : : */
3864 rhaas@postgresql.org 1101 [ - + ]: 2390 : SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1102 : :
1103 : 2390 : old_failed = CheckpointerShmem->ckpt_failed;
1104 : 2390 : old_started = CheckpointerShmem->ckpt_started;
2604 tgl@sss.pgh.pa.us 1105 : 2390 : CheckpointerShmem->ckpt_flags |= (flags | CHECKPOINT_REQUESTED);
1106 : :
3864 rhaas@postgresql.org 1107 : 2390 : SpinLockRelease(&CheckpointerShmem->ckpt_lck);
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 */
5299 simon@2ndQuadrant.co 1120 : 2390 : for (ntries = 0;; ntries++)
1121 : 1 : {
466 andres@anarazel.de 1122 : 2391 : volatile PROC_HDR *procglobal = ProcGlobal;
1123 : 2391 : ProcNumber checkpointerProc = procglobal->checkpointerProc;
1124 : :
1125 [ + + ]: 2391 : if (checkpointerProc == INVALID_PROC_NUMBER)
1126 : : {
2604 tgl@sss.pgh.pa.us 1127 [ + - + + ]: 3 : if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
1128 : : {
5299 simon@2ndQuadrant.co 1129 [ - + + - ]:GBC 2 : elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
1130 : : "could not notify checkpoint: checkpointer is not running");
1131 : 2 : break;
1132 : : }
1133 : : }
1134 : : else
1135 : : {
466 andres@anarazel.de 1136 :CBC 2388 : SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1137 : : /* notified successfully */
1138 : 2388 : break;
1139 : : }
1140 : :
5299 simon@2ndQuadrant.co 1141 [ - + ]: 1 : CHECK_FOR_INTERRUPTS();
1142 : 1 : 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 [ + + ]: 2390 : if (flags & CHECKPOINT_WAIT)
1150 : : {
1151 : : int new_started,
1152 : : new_failed;
1153 : :
1154 : : /* Wait for a new checkpoint to start. */
2609 tmunro@postgresql.or 1155 : 876 : ConditionVariablePrepareToSleep(&CheckpointerShmem->start_cv);
1156 : : for (;;)
1157 : : {
3864 rhaas@postgresql.org 1158 [ - + ]: 1620 : SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1159 : 1620 : new_started = CheckpointerShmem->ckpt_started;
1160 : 1620 : SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1161 : :
5299 simon@2ndQuadrant.co 1162 [ + + ]: 1620 : if (new_started != old_started)
1163 : 876 : break;
1164 : :
2609 tmunro@postgresql.or 1165 : 744 : ConditionVariableSleep(&CheckpointerShmem->start_cv,
1166 : : WAIT_EVENT_CHECKPOINT_START);
1167 : : }
1168 : 876 : ConditionVariableCancelSleep();
1169 : :
1170 : : /*
1171 : : * We are waiting for ckpt_done >= new_started, in a modulo sense.
1172 : : */
1173 : 876 : ConditionVariablePrepareToSleep(&CheckpointerShmem->done_cv);
1174 : : for (;;)
5299 simon@2ndQuadrant.co 1175 : 545 : {
1176 : : int new_done;
1177 : :
3864 rhaas@postgresql.org 1178 [ - + ]: 1421 : SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1179 : 1421 : new_done = CheckpointerShmem->ckpt_done;
1180 : 1421 : new_failed = CheckpointerShmem->ckpt_failed;
1181 : 1421 : SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1182 : :
5299 simon@2ndQuadrant.co 1183 [ + + ]: 1421 : if (new_done - new_started >= 0)
1184 : 876 : break;
1185 : :
2609 tmunro@postgresql.or 1186 : 545 : ConditionVariableSleep(&CheckpointerShmem->done_cv,
1187 : : WAIT_EVENT_CHECKPOINT_DONE);
1188 : : }
1189 : 876 : ConditionVariableCancelSleep();
1190 : :
5299 simon@2ndQuadrant.co 1191 [ - + ]: 876 : if (new_failed != old_failed)
5299 simon@2ndQuadrant.co 1192 [ # # ]:UBC 0 : ereport(ERROR,
1193 : : (errmsg("checkpoint request failed"),
1194 : : errhint("Consult recent messages in the server log for details.")));
1195 : : }
1196 : : }
1197 : :
1198 : : /*
1199 : : * ForwardSyncRequest
1200 : : * Forward a file-fsync request from a backend to the checkpointer
1201 : : *
1202 : : * Whenever a backend is compelled to write directly to a relation
1203 : : * (which should be seldom, if the background writer is getting its job done),
1204 : : * the backend calls this routine to pass over knowledge that the relation
1205 : : * is dirty and must be fsync'd before next checkpoint. We also use this
1206 : : * opportunity to count such writes for statistical purposes.
1207 : : *
1208 : : * To avoid holding the lock for longer than necessary, we normally write
1209 : : * to the requests[] queue without checking for duplicates. The checkpointer
1210 : : * will have to eliminate dups internally anyway. However, if we discover
1211 : : * that the queue is full, we make a pass over the entire queue to compact
1212 : : * it. This is somewhat expensive, but the alternative is for the backend
1213 : : * to perform its own fsync, which is far more expensive in practice. It
1214 : : * is theoretically possible a backend fsync might still be necessary, if
1215 : : * the queue is full and contains no duplicate entries. In that case, we
1216 : : * let the backend know by returning false.
1217 : : */
1218 : : bool
2588 tmunro@postgresql.or 1219 :CBC 1029012 : ForwardSyncRequest(const FileTag *ftag, SyncRequestType type)
1220 : : {
1221 : : CheckpointerRequest *request;
1222 : : bool too_full;
1223 : : int insert_pos;
1224 : :
5299 simon@2ndQuadrant.co 1225 [ - + ]: 1029012 : if (!IsUnderPostmaster)
5299 simon@2ndQuadrant.co 1226 :UBC 0 : return false; /* probably shouldn't even get here */
1227 : :
5039 tgl@sss.pgh.pa.us 1228 [ - + ]:CBC 1029012 : if (AmCheckpointerProcess())
2588 tmunro@postgresql.or 1229 [ # # ]:UBC 0 : elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1230 : :
5109 simon@2ndQuadrant.co 1231 :CBC 1029012 : LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
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 : : */
1238 [ + + ]: 1029012 : if (CheckpointerShmem->checkpointer_pid == 0 ||
1239 [ + + ]: 1028979 : (CheckpointerShmem->num_requests >= CheckpointerShmem->max_requests &&
5110 tgl@sss.pgh.pa.us 1240 [ + + ]: 93 : !CompactCheckpointerRequestQueue()))
1241 : : {
5109 simon@2ndQuadrant.co 1242 : 45 : LWLockRelease(CheckpointerCommLock);
5299 1243 : 45 : return false;
1244 : : }
1245 : :
1246 : : /* OK, insert request */
282 akorotkov@postgresql 1247 :GNC 1028967 : insert_pos = CheckpointerShmem->tail;
1248 : 1028967 : request = &CheckpointerShmem->requests[insert_pos];
2588 tmunro@postgresql.or 1249 :CBC 1028967 : request->ftag = *ftag;
1250 : 1028967 : request->type = type;
1251 : :
282 akorotkov@postgresql 1252 :GNC 1028967 : CheckpointerShmem->tail = (CheckpointerShmem->tail + 1) % CheckpointerShmem->max_requests;
1253 : 1028967 : CheckpointerShmem->num_requests++;
1254 : :
1255 : : /* If queue is more than half full, nudge the checkpointer to empty it */
5109 simon@2ndQuadrant.co 1256 :CBC 1028967 : too_full = (CheckpointerShmem->num_requests >=
1257 : 1028967 : CheckpointerShmem->max_requests / 2);
1258 : :
1259 : 1028967 : LWLockRelease(CheckpointerCommLock);
1260 : :
1261 : : /* ... but not till after we release the lock */
550 heikki.linnakangas@i 1262 [ + + ]: 1028967 : if (too_full)
1263 : : {
1264 : 30382 : volatile PROC_HDR *procglobal = ProcGlobal;
1265 : 30382 : ProcNumber checkpointerProc = procglobal->checkpointerProc;
1266 : :
1267 [ + - ]: 30382 : if (checkpointerProc != INVALID_PROC_NUMBER)
1268 : 30382 : SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1269 : : }
1270 : :
5299 simon@2ndQuadrant.co 1271 : 1028967 : return true;
1272 : : }
1273 : :
1274 : : /*
1275 : : * CompactCheckpointerRequestQueue
1276 : : * Remove duplicates from the request queue to avoid backend fsyncs.
1277 : : * Returns "true" if any entries were removed.
1278 : : *
1279 : : * Although a full fsync request queue is not common, it can lead to severe
1280 : : * performance problems when it does happen. So far, this situation has
1281 : : * only been observed to occur when the system is under heavy write load,
1282 : : * and especially during the "sync" phase of a checkpoint. Without this
1283 : : * logic, each backend begins doing an fsync for every block written, which
1284 : : * gets very expensive and can slow down the whole system.
1285 : : *
1286 : : * Trying to do this every time the queue is full could lose if there
1287 : : * aren't any removable entries. But that should be vanishingly rare in
1288 : : * practice: there's one queue entry per shared buffer.
1289 : : */
1290 : : static bool
5110 tgl@sss.pgh.pa.us 1291 : 93 : CompactCheckpointerRequestQueue(void)
1292 : : {
1293 : : struct CheckpointerSlotMapping
1294 : : {
1295 : : CheckpointerRequest request;
1296 : : int ring_idx;
1297 : : };
1298 : :
1299 : : int n;
5299 simon@2ndQuadrant.co 1300 : 93 : int num_skipped = 0;
1301 : : int head;
1302 : : int max_requests;
1303 : : int num_requests;
1304 : : int read_idx,
1305 : : write_idx;
1306 : : HASHCTL ctl;
1307 : : HTAB *htab;
1308 : : bool *skip_slot;
1309 : :
1310 : : /* must hold CheckpointerCommLock in exclusive mode */
5109 1311 [ - + ]: 93 : Assert(LWLockHeldByMe(CheckpointerCommLock));
1312 : :
1313 : : /* Avoid memory allocations in a critical section. */
683 heikki.linnakangas@i 1314 [ - + ]: 93 : if (CritSectionCount > 0)
683 heikki.linnakangas@i 1315 :UBC 0 : return false;
1316 : :
282 akorotkov@postgresql 1317 :GNC 93 : max_requests = CheckpointerShmem->max_requests;
1318 : 93 : num_requests = CheckpointerShmem->num_requests;
1319 : :
1320 : : /* Initialize skip_slot array */
146 michael@paquier.xyz 1321 : 93 : skip_slot = palloc0_array(bool, max_requests);
1322 : :
282 akorotkov@postgresql 1323 : 93 : head = CheckpointerShmem->head;
1324 : :
1325 : : /* Initialize temporary hash table */
5109 simon@2ndQuadrant.co 1326 :CBC 93 : ctl.keysize = sizeof(CheckpointerRequest);
5108 tgl@sss.pgh.pa.us 1327 : 93 : ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
5040 1328 : 93 : ctl.hcxt = CurrentMemoryContext;
1329 : :
5209 simon@2ndQuadrant.co 1330 : 93 : htab = hash_create("CompactCheckpointerRequestQueue",
5109 1331 : 93 : CheckpointerShmem->num_requests,
1332 : : &ctl,
1333 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1334 : :
1335 : : /*
1336 : : * The basic idea here is that a request can be skipped if it's followed
1337 : : * by a later, identical request. It might seem more sensible to work
1338 : : * backwards from the end of the queue and check whether a request is
1339 : : * *preceded* by an earlier, identical request, in the hopes of doing less
1340 : : * copying. But that might change the semantics, if there's an
1341 : : * intervening SYNC_FORGET_REQUEST or SYNC_FILTER_REQUEST, so we do it
1342 : : * this way. It would be possible to be even smarter if we made the code
1343 : : * below understand the specific semantics of such requests (it could blow
1344 : : * away preceding entries that would end up being canceled anyhow), but
1345 : : * it's not clear that the extra complexity would buy us anything.
1346 : : */
282 akorotkov@postgresql 1347 :GNC 93 : read_idx = head;
1348 [ + + ]: 9421 : for (n = 0; n < num_requests; n++)
1349 : : {
1350 : : CheckpointerRequest *request;
1351 : : struct CheckpointerSlotMapping *slotmap;
1352 : : bool found;
1353 : :
1354 : : /*
1355 : : * We use the request struct directly as a hashtable key. This
1356 : : * assumes that any padding bytes in the structs are consistently the
1357 : : * same, which should be okay because we zeroed them in
1358 : : * CheckpointerShmemInit. Note also that RelFileLocator had better
1359 : : * contain no pad bytes.
1360 : : */
1361 : 9328 : request = &CheckpointerShmem->requests[read_idx];
5299 simon@2ndQuadrant.co 1362 :CBC 9328 : slotmap = hash_search(htab, request, HASH_ENTER, &found);
1363 [ + + ]: 9328 : if (found)
1364 : : {
1365 : : /* Duplicate, so mark the previous occurrence as skippable */
282 akorotkov@postgresql 1366 :GNC 5197 : skip_slot[slotmap->ring_idx] = true;
5040 tgl@sss.pgh.pa.us 1367 :CBC 5197 : num_skipped++;
1368 : : }
1369 : : /* Remember slot containing latest occurrence of this request value */
282 akorotkov@postgresql 1370 :GNC 9328 : slotmap->ring_idx = read_idx;
1371 : :
1372 : : /* Move to the next request in the ring buffer */
1373 : 9328 : read_idx = (read_idx + 1) % max_requests;
1374 : : }
1375 : :
1376 : : /* Done with the hash table. */
5299 simon@2ndQuadrant.co 1377 :CBC 93 : hash_destroy(htab);
1378 : :
1379 : : /* If no duplicates, we're out of luck. */
1380 [ + + ]: 93 : if (!num_skipped)
1381 : : {
1382 : 12 : pfree(skip_slot);
1383 : 12 : return false;
1384 : : }
1385 : :
1386 : : /* We found some duplicates; remove them. */
282 akorotkov@postgresql 1387 :GNC 81 : read_idx = write_idx = head;
1388 [ + + ]: 7873 : for (n = 0; n < num_requests; n++)
1389 : : {
1390 : : /* If this slot is NOT skipped, keep it */
1391 [ + + ]: 7792 : if (!skip_slot[read_idx])
1392 : : {
1393 : : /* If the read and write positions are different, copy the request */
1394 [ + + ]: 2595 : if (write_idx != read_idx)
1395 : 2321 : CheckpointerShmem->requests[write_idx] =
1396 : 2321 : CheckpointerShmem->requests[read_idx];
1397 : :
1398 : : /* Advance the write position */
1399 : 2595 : write_idx = (write_idx + 1) % max_requests;
1400 : : }
1401 : :
1402 : 7792 : read_idx = (read_idx + 1) % max_requests;
1403 : : }
1404 : :
1405 : : /*
1406 : : * Update ring buffer state: head remains the same, tail moves, count
1407 : : * decreases
1408 : : */
1409 : 81 : CheckpointerShmem->tail = write_idx;
1410 : 81 : CheckpointerShmem->num_requests -= num_skipped;
1411 : :
5299 simon@2ndQuadrant.co 1412 [ + + ]:CBC 81 : ereport(DEBUG1,
1413 : : (errmsg_internal("compacted fsync request queue from %d entries to %d entries",
1414 : : num_requests, CheckpointerShmem->num_requests)));
1415 : :
1416 : : /* Cleanup. */
1417 : 81 : pfree(skip_slot);
1418 : 81 : return true;
1419 : : }
1420 : :
1421 : : /*
1422 : : * AbsorbSyncRequests
1423 : : * Retrieve queued sync requests and pass them to sync mechanism.
1424 : : *
1425 : : * This is exported because it must be called during CreateCheckPoint;
1426 : : * we have to be sure we have accepted all pending requests just before
1427 : : * we start fsync'ing. Since CreateCheckPoint sometimes runs in
1428 : : * non-checkpointer processes, do nothing if not checkpointer.
1429 : : */
1430 : : void
2588 tmunro@postgresql.or 1431 : 22409 : AbsorbSyncRequests(void)
1432 : : {
5109 simon@2ndQuadrant.co 1433 : 22409 : CheckpointerRequest *requests = NULL;
1434 : : CheckpointerRequest *request;
1435 : : int n,
1436 : : i;
1437 : : bool loop;
1438 : :
5039 tgl@sss.pgh.pa.us 1439 [ + + ]: 22409 : if (!AmCheckpointerProcess())
5299 simon@2ndQuadrant.co 1440 : 724 : return;
1441 : :
1442 : : do
1443 : : {
282 akorotkov@postgresql 1444 :GNC 21685 : LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
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 : : */
1465 : 21685 : n = Min(CheckpointerShmem->num_requests, CKPT_REQ_BATCH_SIZE);
1466 [ + + ]: 21685 : if (n > 0)
1467 : : {
1468 [ + - ]: 11783 : if (!requests)
1469 : 11783 : requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1470 : :
1471 [ + + ]: 880913 : for (i = 0; i < n; i++)
1472 : : {
1473 : 869130 : requests[i] = CheckpointerShmem->requests[CheckpointerShmem->head];
1474 : 869130 : CheckpointerShmem->head = (CheckpointerShmem->head + 1) % CheckpointerShmem->max_requests;
1475 : : }
1476 : :
1477 : 11783 : CheckpointerShmem->num_requests -= n;
1478 : :
1479 : : }
1480 : :
1481 : 21685 : START_CRIT_SECTION();
1482 : :
1483 : : /* Are there any requests in the queue? If so, keep going. */
1484 : 21685 : loop = CheckpointerShmem->num_requests != 0;
1485 : :
1486 : 21685 : LWLockRelease(CheckpointerCommLock);
1487 : :
1488 [ + + ]: 890815 : for (request = requests; n > 0; request++, n--)
1489 : 869130 : RememberSyncRequest(&request->ftag, request->type);
1490 : :
1491 [ - + ]: 21685 : END_CRIT_SECTION();
1492 [ - + ]: 21685 : } while (loop);
1493 : :
5299 simon@2ndQuadrant.co 1494 [ + + ]:CBC 21685 : if (requests)
1495 : 11783 : pfree(requests);
1496 : : }
1497 : :
1498 : : /*
1499 : : * Update any shared memory configurations based on config parameters
1500 : : */
1501 : : static void
5214 1502 : 732 : UpdateSharedMemoryConfig(void)
1503 : : {
1504 : : /* update global shmem state for sync rep */
1505 : 732 : SyncRepUpdateSyncStandbysDefined();
1506 : :
1507 : : /*
1508 : : * If full_page_writes has been changed by SIGHUP, we update it in shared
1509 : : * memory and write an XLOG_FPW_CHANGE record.
1510 : : */
1511 : 732 : UpdateFullPageWrites();
1512 : :
1513 [ + + ]: 732 : elog(DEBUG2, "checkpointer updated shared memory configuration values");
1514 : 732 : }
1515 : :
1516 : : /*
1517 : : * FirstCallSinceLastCheckpoint allows a process to take an action once
1518 : : * per checkpoint cycle by asynchronously checking for checkpoint completion.
1519 : : */
1520 : : bool
5086 1521 : 13948 : FirstCallSinceLastCheckpoint(void)
1522 : : {
1523 : : static int ckpt_done = 0;
1524 : : int new_done;
5077 bruce@momjian.us 1525 : 13948 : bool FirstCall = false;
1526 : :
3864 rhaas@postgresql.org 1527 [ - + ]: 13948 : SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1528 : 13948 : new_done = CheckpointerShmem->ckpt_done;
1529 : 13948 : SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1530 : :
5086 simon@2ndQuadrant.co 1531 [ + + ]: 13948 : if (new_done != ckpt_done)
1532 : 617 : FirstCall = true;
1533 : :
1534 : 13948 : ckpt_done = new_done;
1535 : :
1536 : 13948 : return FirstCall;
1537 : : }
1538 : :
1539 : : /*
1540 : : * Wake up the checkpointer process.
1541 : : */
1542 : : void
133 msawada@postgresql.o 1543 :GNC 1021 : WakeupCheckpointer(void)
1544 : : {
1545 : 1021 : volatile PROC_HDR *procglobal = ProcGlobal;
1546 : 1021 : ProcNumber checkpointerProc = procglobal->checkpointerProc;
1547 : :
1548 [ + + ]: 1021 : if (checkpointerProc != INVALID_PROC_NUMBER)
1549 : 817 : SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
1550 : 1021 : }
|