1 /*-------------------------------------------------------------------------
5 * The background writer (bgwriter) is new as of Postgres 8.0. It attempts
6 * to keep regular backends from having to write out dirty shared buffers
7 * (which they would only do when needing to free a shared buffer to read in
8 * another page). In the best scenario all writes from shared buffers will
9 * be issued by the background writer process. However, regular backends are
10 * still empowered to issue writes if the bgwriter fails to maintain enough
11 * clean shared buffers.
13 * The bgwriter is also charged with handling all checkpoints. It will
14 * automatically dispatch a checkpoint after a certain amount of time has
15 * elapsed since the last one, and it can be signaled to perform requested
16 * checkpoints as well. (The GUC parameter that mandates a checkpoint every
17 * so many WAL segments is implemented by having backends signal the bgwriter
18 * when they fill WAL segments; the bgwriter itself doesn't watch for the
21 * The bgwriter is started by the postmaster as soon as the startup subprocess
22 * finishes. It remains alive until the postmaster commands it to terminate.
23 * Normal termination is by SIGUSR2, which instructs the bgwriter to execute
24 * a shutdown checkpoint and then exit(0). (All backends must be stopped
25 * before SIGUSR2 is issued!) Emergency termination is by SIGQUIT; like any
26 * backend, the bgwriter will simply abort and exit on SIGQUIT.
28 * If the bgwriter exits unexpectedly, the postmaster treats that the same
29 * as a backend crash: shared memory may be corrupted, so remaining backends
30 * should be killed by SIGQUIT and then a recovery cycle started. (Even if
31 * shared memory isn't corrupted, we have lost information about which
32 * files need to be fsync'd for the next checkpoint, and so a system
33 * restart needs to be forced.)
36 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
40 * $PostgreSQL: pgsql/src/backend/postmaster/bgwriter.c,v 1.58 2009/05/15 15:56:39 tgl Exp $
42 *-------------------------------------------------------------------------
51 #include "access/xlog_internal.h"
52 #include "catalog/pg_control.h"
53 #include "libpq/pqsignal.h"
54 #include "miscadmin.h"
56 #include "postmaster/bgwriter.h"
57 #include "storage/bufmgr.h"
58 #include "storage/fd.h"
59 #include "storage/ipc.h"
60 #include "storage/lwlock.h"
61 #include "storage/pmsignal.h"
62 #include "storage/shmem.h"
63 #include "storage/smgr.h"
64 #include "storage/spin.h"
65 #include "tcop/tcopprot.h"
66 #include "utils/guc.h"
67 #include "utils/memutils.h"
68 #include "utils/resowner.h"
72 * Shared memory area for communication between bgwriter and backends
74 * The ckpt counters allow backends to watch for completion of a checkpoint
75 * request they send. Here's how it works:
76 * * At start of a checkpoint, bgwriter reads (and clears) the request flags
77 * and increments ckpt_started, while holding ckpt_lck.
78 * * On completion of a checkpoint, bgwriter sets ckpt_done to
80 * * On failure of a checkpoint, bgwriter increments ckpt_failed
81 * and sets ckpt_done to equal ckpt_started.
83 * The algorithm for backends is:
84 * 1. Record current values of ckpt_failed and ckpt_started, and
85 * set request flags, while holding ckpt_lck.
86 * 2. Send signal to request checkpoint.
87 * 3. Sleep until ckpt_started changes. Now you know a checkpoint has
88 * begun since you started this algorithm (although *not* that it was
89 * specifically initiated by your signal), and that it is using your flags.
90 * 4. Record new value of ckpt_started.
91 * 5. Sleep until ckpt_done >= saved value of ckpt_started. (Use modulo
92 * arithmetic here in case counters wrap around.) Now you know a
93 * checkpoint has started and completed, but not whether it was
95 * 6. If ckpt_failed is different from the originally saved value,
96 * assume request failed; otherwise it was definitely successful.
98 * ckpt_flags holds the OR of the checkpoint request flags sent by all
99 * requesting backends since the last checkpoint start. The flags are
100 * chosen so that OR'ing is the correct way to combine multiple requests.
102 * num_backend_writes is used to count the number of buffer writes performed
103 * by non-bgwriter processes. This counter should be wide enough that it
104 * can't overflow during a single bgwriter cycle.
106 * The requests array holds fsync requests sent by backends and not yet
107 * absorbed by the bgwriter.
109 * Unlike the checkpoint fields, num_backend_writes and the requests
110 * fields are protected by BgWriterCommLock.
117 BlockNumber segno; /* see md.c for special values */
118 /* might add a real request-type field later; not needed yet */
123 pid_t bgwriter_pid; /* PID of bgwriter (0 if not started) */
125 slock_t ckpt_lck; /* protects all the ckpt_* fields */
127 int ckpt_started; /* advances when checkpoint starts */
128 int ckpt_done; /* advances when checkpoint done */
129 int ckpt_failed; /* advances when checkpoint fails */
131 int ckpt_flags; /* checkpoint flags, as defined in xlog.h */
133 uint32 num_backend_writes; /* counts non-bgwriter buffer writes */
135 int num_requests; /* current # of requests */
136 int max_requests; /* allocated array size */
137 BgWriterRequest requests[1]; /* VARIABLE LENGTH ARRAY */
138 } BgWriterShmemStruct;
140 static BgWriterShmemStruct *BgWriterShmem;
142 /* interval for calling AbsorbFsyncRequests in CheckpointWriteDelay */
143 #define WRITES_PER_ABSORB 1000
148 int BgWriterDelay = 200;
149 int CheckPointTimeout = 300;
150 int CheckPointWarning = 30;
151 double CheckPointCompletionTarget = 0.5;
154 * Flags set by interrupt handlers for later service in the main loop.
156 static volatile sig_atomic_t got_SIGHUP = false;
157 static volatile sig_atomic_t checkpoint_requested = false;
158 static volatile sig_atomic_t shutdown_requested = false;
163 static bool am_bg_writer = false;
165 static bool ckpt_active = false;
167 /* these values are valid when ckpt_active is true: */
168 static pg_time_t ckpt_start_time;
169 static XLogRecPtr ckpt_start_recptr;
170 static double ckpt_cached_elapsed;
172 static pg_time_t last_checkpoint_time;
173 static pg_time_t last_xlog_switch_time;
175 /* Prototypes for private functions */
177 static void CheckArchiveTimeout(void);
178 static void BgWriterNap(void);
179 static bool IsCheckpointOnSchedule(double progress);
180 static bool ImmediateCheckpointRequested(void);
182 /* Signal handlers */
184 static void bg_quickdie(SIGNAL_ARGS);
185 static void BgSigHupHandler(SIGNAL_ARGS);
186 static void ReqCheckpointHandler(SIGNAL_ARGS);
187 static void ReqShutdownHandler(SIGNAL_ARGS);
191 * Main entry point for bgwriter process
193 * This is invoked from BootstrapMain, which has already created the basic
194 * execution environment, but not enabled signals yet.
197 BackgroundWriterMain(void)
199 sigjmp_buf local_sigjmp_buf;
200 MemoryContext bgwriter_context;
202 BgWriterShmem->bgwriter_pid = MyProcPid;
206 * If possible, make this process a group leader, so that the postmaster
207 * can signal any child processes too. (bgwriter probably never has any
208 * child processes, but for consistency we make all postmaster child
209 * processes do this.)
213 elog(FATAL, "setsid() failed: %m");
217 * Properly accept or ignore signals the postmaster might send us
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).
224 * SIGUSR1 is presently unused; keep it spare in case someday we want this
225 * process to participate in sinval messaging.
227 pqsignal(SIGHUP, BgSigHupHandler); /* set flag to read config file */
228 pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
229 pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
230 pqsignal(SIGQUIT, bg_quickdie); /* hard crash time */
231 pqsignal(SIGALRM, SIG_IGN);
232 pqsignal(SIGPIPE, SIG_IGN);
233 pqsignal(SIGUSR1, SIG_IGN); /* reserve for sinval */
234 pqsignal(SIGUSR2, ReqShutdownHandler); /* request shutdown */
237 * Reset some signals that are accepted by postmaster but not here
239 pqsignal(SIGCHLD, SIG_DFL);
240 pqsignal(SIGTTIN, SIG_DFL);
241 pqsignal(SIGTTOU, SIG_DFL);
242 pqsignal(SIGCONT, SIG_DFL);
243 pqsignal(SIGWINCH, SIG_DFL);
245 /* We allow SIGQUIT (quickdie) at all times */
246 #ifdef HAVE_SIGPROCMASK
247 sigdelset(&BlockSig, SIGQUIT);
249 BlockSig &= ~(sigmask(SIGQUIT));
253 * Initialize so that first time-driven event happens at the correct time.
255 last_checkpoint_time = last_xlog_switch_time = (pg_time_t) time(NULL);
258 * Create a resource owner to keep track of our resources (currently only
261 CurrentResourceOwner = ResourceOwnerCreate(NULL, "Background Writer");
264 * Create a memory context that we will do all our work in. We do this so
265 * that we can reset the context during error recovery and thereby avoid
266 * possible memory leaks. Formerly this code just ran in
267 * TopMemoryContext, but resetting that would be a really bad idea.
269 bgwriter_context = AllocSetContextCreate(TopMemoryContext,
271 ALLOCSET_DEFAULT_MINSIZE,
272 ALLOCSET_DEFAULT_INITSIZE,
273 ALLOCSET_DEFAULT_MAXSIZE);
274 MemoryContextSwitchTo(bgwriter_context);
277 * If an exception is encountered, processing resumes here.
279 * See notes in postgres.c about the design of this coding.
281 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
283 /* Since not using PG_TRY, must reset error stack by hand */
284 error_context_stack = NULL;
286 /* Prevent interrupts while cleaning up */
289 /* Report the error to the server log */
293 * These operations are really just a minimal subset of
294 * AbortTransaction(). We don't have very many resources to worry
295 * about in bgwriter, but we do have LWLocks, buffers, and temp files.
300 /* buffer pins are released here: */
301 ResourceOwnerRelease(CurrentResourceOwner,
302 RESOURCE_RELEASE_BEFORE_LOCKS,
304 /* we needn't bother with the other ResourceOwnerRelease phases */
305 AtEOXact_Buffers(false);
307 AtEOXact_HashTables(false);
309 /* Warn any waiting backends that the checkpoint failed. */
312 /* use volatile pointer to prevent code rearrangement */
313 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
315 SpinLockAcquire(&bgs->ckpt_lck);
317 bgs->ckpt_done = bgs->ckpt_started;
318 SpinLockRelease(&bgs->ckpt_lck);
324 * Now return to normal top-level context and clear ErrorContext for
327 MemoryContextSwitchTo(bgwriter_context);
330 /* Flush any leaked data in the top-level context */
331 MemoryContextResetAndDeleteChildren(bgwriter_context);
333 /* Now we can allow interrupts again */
337 * Sleep at least 1 second after any error. A write error is likely
338 * to be repeated, and we don't want to be filling the error logs as
344 * Close all open files after any error. This is helpful on Windows,
345 * where holding deleted files open causes various strange errors.
346 * It's not clear we need it elsewhere, but shouldn't hurt.
351 /* We can now handle ereport(ERROR) */
352 PG_exception_stack = &local_sigjmp_buf;
355 * Unblock signals (they were blocked when the postmaster forked us)
357 PG_SETMASK(&UnBlockSig);
364 bool do_checkpoint = false;
370 * Emergency bailout if postmaster has died. This is to avoid the
371 * necessity for manual cleanup of all postmaster children.
373 if (!PostmasterIsAlive(true))
377 * Process any requests or signals received recently.
379 AbsorbFsyncRequests();
384 ProcessConfigFile(PGC_SIGHUP);
386 if (checkpoint_requested)
388 checkpoint_requested = false;
389 do_checkpoint = true;
390 BgWriterStats.m_requested_checkpoints++;
392 if (shutdown_requested)
395 * From here on, elog(ERROR) should end with exit(1), not send
396 * control back to the sigsetjmp block above
398 ExitOnAnyError = true;
399 /* Close down the database */
401 /* Normal exit from the bgwriter is here */
402 proc_exit(0); /* done */
406 * Force a checkpoint if too much time has elapsed since the last one.
407 * Note that we count a timed checkpoint in stats only when this
408 * occurs without an external request, but we set the CAUSE_TIME flag
409 * bit even if there is also an external request.
411 now = (pg_time_t) time(NULL);
412 elapsed_secs = now - last_checkpoint_time;
413 if (elapsed_secs >= CheckPointTimeout)
416 BgWriterStats.m_timed_checkpoints++;
417 do_checkpoint = true;
418 flags |= CHECKPOINT_CAUSE_TIME;
422 * Do a checkpoint if requested, otherwise do one cycle of
423 * dirty-buffer writing.
427 bool ckpt_performed = false;
428 bool do_restartpoint;
430 /* use volatile pointer to prevent code rearrangement */
431 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
434 * Check if we should perform a checkpoint or a restartpoint.
435 * As a side-effect, RecoveryInProgress() initializes
436 * TimeLineID if it's not set yet.
438 do_restartpoint = RecoveryInProgress();
441 * Atomically fetch the request flags to figure out what kind of a
442 * checkpoint we should perform, and increase the started-counter
443 * to acknowledge that we've started a new checkpoint.
445 SpinLockAcquire(&bgs->ckpt_lck);
446 flags |= bgs->ckpt_flags;
449 SpinLockRelease(&bgs->ckpt_lck);
452 * We will warn if (a) too soon since last checkpoint (whatever
453 * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
454 * since the last checkpoint start. Note in particular that this
455 * implementation will not generate warnings caused by
456 * CheckPointTimeout < CheckPointWarning.
458 if (!do_restartpoint &&
459 (flags & CHECKPOINT_CAUSE_XLOG) &&
460 elapsed_secs < CheckPointWarning)
462 (errmsg(ngettext("checkpoints are occurring too frequently (%d second apart)",
463 "checkpoints are occurring too frequently (%d seconds apart)",
466 errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
469 * Initialize bgwriter-private variables used during checkpoint.
472 if (!do_restartpoint)
473 ckpt_start_recptr = GetInsertRecPtr();
474 ckpt_start_time = now;
475 ckpt_cached_elapsed = 0;
480 if (!do_restartpoint)
482 CreateCheckPoint(flags);
483 ckpt_performed = true;
486 ckpt_performed = CreateRestartPoint(flags);
489 * After any checkpoint, close all smgr files. This is so we
490 * won't hang onto smgr references to deleted files indefinitely.
495 * Indicate checkpoint completion to any waiting backends.
497 SpinLockAcquire(&bgs->ckpt_lck);
498 bgs->ckpt_done = bgs->ckpt_started;
499 SpinLockRelease(&bgs->ckpt_lck);
504 * Note we record the checkpoint start time not end time as
505 * last_checkpoint_time. This is so that time-driven
506 * checkpoints happen at a predictable spacing.
508 last_checkpoint_time = now;
513 * We were not able to perform the restartpoint (checkpoints
514 * throw an ERROR in case of error). Most likely because we
515 * have not received any new checkpoint WAL records since the
516 * last restartpoint. Try again in 15 s.
518 last_checkpoint_time = now - CheckPointTimeout + 15;
526 /* Check for archive_timeout and switch xlog files if necessary. */
527 CheckArchiveTimeout();
529 /* Nap for the configured time. */
535 * CheckArchiveTimeout -- check for archive_timeout and switch xlog files
539 CheckArchiveTimeout(void)
544 if (XLogArchiveTimeout <= 0 || RecoveryInProgress())
547 now = (pg_time_t) time(NULL);
549 /* First we do a quick check using possibly-stale local state. */
550 if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
554 * Update local state ... note that last_xlog_switch_time is the last time
555 * a switch was performed *or requested*.
557 last_time = GetLastSegSwitchTime();
559 last_xlog_switch_time = Max(last_xlog_switch_time, last_time);
561 /* Now we can do the real check */
562 if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
564 XLogRecPtr switchpoint;
566 /* OK, it's time to switch */
567 switchpoint = RequestXLogSwitch();
570 * If the returned pointer points exactly to a segment boundary,
571 * assume nothing happened.
573 if ((switchpoint.xrecoff % XLogSegSize) != 0)
575 (errmsg("transaction log switch forced (archive_timeout=%d)",
576 XLogArchiveTimeout)));
579 * Update state in any case, so we don't retry constantly when the
582 last_xlog_switch_time = now;
587 * BgWriterNap -- Nap for the configured time or until a signal is received.
595 * Send off activity statistics to the stats collector
597 pgstat_send_bgwriter();
600 * Nap for the configured time, or sleep for 10 seconds if there is no
601 * bgwriter activity configured.
603 * On some platforms, signals won't interrupt the sleep. To ensure we
604 * respond reasonably promptly when someone signals us, break down the
605 * sleep into 1-second increments, and check for interrupts after each
608 * We absorb pending requests after each short sleep.
610 if (bgwriter_lru_maxpages > 0 || ckpt_active)
611 udelay = BgWriterDelay * 1000L;
612 else if (XLogArchiveTimeout > 0)
613 udelay = 1000000L; /* One second */
615 udelay = 10000000L; /* Ten seconds */
617 while (udelay > 999999L)
619 if (got_SIGHUP || shutdown_requested ||
620 (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested))
623 AbsorbFsyncRequests();
627 if (!(got_SIGHUP || shutdown_requested ||
628 (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested)))
633 * Returns true if an immediate checkpoint request is pending. (Note that
634 * this does not check the *current* checkpoint's IMMEDIATE flag, but whether
635 * there is one pending behind it.)
638 ImmediateCheckpointRequested(void)
640 if (checkpoint_requested)
642 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
645 * We don't need to acquire the ckpt_lck in this case because we're
646 * only looking at a single flag bit.
648 if (bgs->ckpt_flags & CHECKPOINT_IMMEDIATE)
655 * CheckpointWriteDelay -- yield control to bgwriter during a checkpoint
657 * This function is called after each page write performed by BufferSync().
658 * It is responsible for keeping the bgwriter's normal activities in
659 * progress during a long checkpoint, and for throttling BufferSync()'s
660 * write rate to hit checkpoint_completion_target.
662 * The checkpoint request flags should be passed in; currently the only one
663 * examined is CHECKPOINT_IMMEDIATE, which disables delays between writes.
665 * 'progress' is an estimate of how much of the work has been done, as a
666 * fraction between 0.0 meaning none, and 1.0 meaning all done.
669 CheckpointWriteDelay(int flags, double progress)
671 static int absorb_counter = WRITES_PER_ABSORB;
673 /* Do nothing if checkpoint is being executed by non-bgwriter process */
678 * Perform the usual bgwriter duties and take a nap, unless we're behind
679 * schedule, in which case we just try to catch up as quickly as possible.
681 if (!(flags & CHECKPOINT_IMMEDIATE) &&
682 !shutdown_requested &&
683 !ImmediateCheckpointRequested() &&
684 IsCheckpointOnSchedule(progress))
689 ProcessConfigFile(PGC_SIGHUP);
692 AbsorbFsyncRequests();
693 absorb_counter = WRITES_PER_ABSORB;
696 CheckArchiveTimeout();
699 else if (--absorb_counter <= 0)
702 * Absorb pending fsync requests after each WRITES_PER_ABSORB write
703 * operations even when we don't sleep, to prevent overflow of the
704 * fsync request queue.
706 AbsorbFsyncRequests();
707 absorb_counter = WRITES_PER_ABSORB;
712 * IsCheckpointOnSchedule -- are we on schedule to finish this checkpoint
715 * Compares the current progress against the time/segments elapsed since last
716 * checkpoint, and returns true if the progress we've made this far is greater
717 * than the elapsed time/segments.
720 IsCheckpointOnSchedule(double progress)
724 double elapsed_xlogs,
729 /* Scale progress according to checkpoint_completion_target. */
730 progress *= CheckPointCompletionTarget;
733 * Check against the cached value first. Only do the more expensive
734 * calculations once we reach the target previously calculated. Since
735 * neither time or WAL insert pointer moves backwards, a freshly
736 * calculated value can only be greater than or equal to the cached value.
738 if (progress < ckpt_cached_elapsed)
742 * Check progress against WAL segments written and checkpoint_segments.
744 * We compare the current WAL insert location against the location
745 * computed before calling CreateCheckPoint. The code in XLogInsert that
746 * actually triggers a checkpoint when checkpoint_segments is exceeded
747 * compares against RedoRecptr, so this is not completely accurate.
748 * However, it's good enough for our purposes, we're only calculating an
751 if (!RecoveryInProgress())
753 recptr = GetInsertRecPtr();
755 (((double) (int32) (recptr.xlogid - ckpt_start_recptr.xlogid)) * XLogSegsPerFile +
756 ((double) recptr.xrecoff - (double) ckpt_start_recptr.xrecoff) / XLogSegSize) /
759 if (progress < elapsed_xlogs)
761 ckpt_cached_elapsed = elapsed_xlogs;
767 * Check progress against time elapsed and checkpoint_timeout.
769 gettimeofday(&now, NULL);
770 elapsed_time = ((double) ((pg_time_t) now.tv_sec - ckpt_start_time) +
771 now.tv_usec / 1000000.0) / CheckPointTimeout;
773 if (progress < elapsed_time)
775 ckpt_cached_elapsed = elapsed_time;
779 /* It looks like we're on schedule. */
784 /* --------------------------------
785 * signal handler routines
786 * --------------------------------
790 * bg_quickdie() occurs when signalled SIGQUIT by the postmaster.
792 * Some backend has bought the farm,
793 * so we need to stop what we're doing and exit.
796 bg_quickdie(SIGNAL_ARGS)
798 PG_SETMASK(&BlockSig);
801 * We DO NOT want to run proc_exit() callbacks -- we're here because
802 * shared memory may be corrupted, so we don't want to try to clean up our
803 * transaction. Just nail the windows shut and get out of town. Now that
804 * there's an atexit callback to prevent third-party code from breaking
805 * things by calling exit() directly, we have to reset the callbacks
806 * explicitly to make this work as intended.
811 * Note we do exit(2) not exit(0). This is to force the postmaster into a
812 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
813 * backend. This is necessary precisely because we don't clean up our
814 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
815 * should ensure the postmaster sees this as a crash, too, but no harm
816 * in being doubly sure.)
821 /* SIGHUP: set flag to re-read config file at next convenient time */
823 BgSigHupHandler(SIGNAL_ARGS)
828 /* SIGINT: set flag to run a normal checkpoint right away */
830 ReqCheckpointHandler(SIGNAL_ARGS)
832 checkpoint_requested = true;
835 /* SIGUSR2: set flag to run a shutdown checkpoint and exit */
837 ReqShutdownHandler(SIGNAL_ARGS)
839 shutdown_requested = true;
843 /* --------------------------------
844 * communication with backends
845 * --------------------------------
850 * Compute space needed for bgwriter-related shared memory
853 BgWriterShmemSize(void)
858 * Currently, the size of the requests[] array is arbitrarily set equal to
859 * NBuffers. This may prove too large or small ...
861 size = offsetof(BgWriterShmemStruct, requests);
862 size = add_size(size, mul_size(NBuffers, sizeof(BgWriterRequest)));
869 * Allocate and initialize bgwriter-related shared memory
872 BgWriterShmemInit(void)
876 BgWriterShmem = (BgWriterShmemStruct *)
877 ShmemInitStruct("Background Writer Data",
880 if (BgWriterShmem == NULL)
882 (errcode(ERRCODE_OUT_OF_MEMORY),
883 errmsg("not enough shared memory for background writer")));
885 return; /* already initialized */
887 MemSet(BgWriterShmem, 0, sizeof(BgWriterShmemStruct));
888 SpinLockInit(&BgWriterShmem->ckpt_lck);
889 BgWriterShmem->max_requests = NBuffers;
894 * Called in backend processes to request a checkpoint
896 * flags is a bitwise OR of the following:
897 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
898 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
899 * ignoring checkpoint_completion_target parameter.
900 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
901 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
902 * CHECKPOINT_WAIT: wait for completion before returning (otherwise,
903 * just signal bgwriter to do it, and return).
904 * CHECKPOINT_CAUSE_XLOG: checkpoint is requested due to xlog filling.
905 * (This affects logging, and in particular enables CheckPointWarning.)
908 RequestCheckpoint(int flags)
910 /* use volatile pointer to prevent code rearrangement */
911 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
917 * If in a standalone backend, just do it ourselves.
919 if (!IsPostmasterEnvironment)
922 * There's no point in doing slow checkpoints in a standalone backend,
923 * because there's no other backends the checkpoint could disrupt.
925 CreateCheckPoint(flags | CHECKPOINT_IMMEDIATE);
928 * After any checkpoint, close all smgr files. This is so we won't
929 * hang onto smgr references to deleted files indefinitely.
937 * Atomically set the request flags, and take a snapshot of the counters.
938 * When we see ckpt_started > old_started, we know the flags we set here
939 * have been seen by bgwriter.
941 * Note that we OR the flags with any existing flags, to avoid overriding
942 * a "stronger" request by another backend. The flag senses must be
943 * chosen to make this work!
945 SpinLockAcquire(&bgs->ckpt_lck);
947 old_failed = bgs->ckpt_failed;
948 old_started = bgs->ckpt_started;
949 bgs->ckpt_flags |= flags;
951 SpinLockRelease(&bgs->ckpt_lck);
954 * Send signal to request checkpoint. It's possible that the bgwriter
955 * hasn't started yet, or is in process of restarting, so we will retry
956 * a few times if needed. Also, if not told to wait for the checkpoint
957 * to occur, we consider failure to send the signal to be nonfatal and
960 for (ntries = 0; ; ntries++)
962 if (BgWriterShmem->bgwriter_pid == 0)
964 if (ntries >= 20) /* max wait 2.0 sec */
966 elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
967 "could not request checkpoint because bgwriter not running");
971 else if (kill(BgWriterShmem->bgwriter_pid, SIGINT) != 0)
973 if (ntries >= 20) /* max wait 2.0 sec */
975 elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
976 "could not signal for checkpoint: %m");
981 break; /* signal sent successfully */
983 CHECK_FOR_INTERRUPTS();
984 pg_usleep(100000L); /* wait 0.1 sec, then retry */
988 * If requested, wait for completion. We detect completion according to
989 * the algorithm given above.
991 if (flags & CHECKPOINT_WAIT)
996 /* Wait for a new checkpoint to start. */
999 SpinLockAcquire(&bgs->ckpt_lck);
1000 new_started = bgs->ckpt_started;
1001 SpinLockRelease(&bgs->ckpt_lck);
1003 if (new_started != old_started)
1006 CHECK_FOR_INTERRUPTS();
1011 * We are waiting for ckpt_done >= new_started, in a modulo sense.
1017 SpinLockAcquire(&bgs->ckpt_lck);
1018 new_done = bgs->ckpt_done;
1019 new_failed = bgs->ckpt_failed;
1020 SpinLockRelease(&bgs->ckpt_lck);
1022 if (new_done - new_started >= 0)
1025 CHECK_FOR_INTERRUPTS();
1029 if (new_failed != old_failed)
1031 (errmsg("checkpoint request failed"),
1032 errhint("Consult recent messages in the server log for details.")));
1037 * ForwardFsyncRequest
1038 * Forward a file-fsync request from a backend to the bgwriter
1040 * Whenever a backend is compelled to write directly to a relation
1041 * (which should be seldom, if the bgwriter is getting its job done),
1042 * the backend calls this routine to pass over knowledge that the relation
1043 * is dirty and must be fsync'd before next checkpoint. We also use this
1044 * opportunity to count such writes for statistical purposes.
1046 * segno specifies which segment (not block!) of the relation needs to be
1047 * fsync'd. (Since the valid range is much less than BlockNumber, we can
1048 * use high values for special flags; that's all internal to md.c, which
1051 * If we are unable to pass over the request (at present, this can happen
1052 * if the shared memory queue is full), we return false. That forces
1053 * the backend to do its own fsync. We hope that will be even more seldom.
1055 * Note: we presently make no attempt to eliminate duplicate requests
1056 * in the requests[] queue. The bgwriter will have to eliminate dups
1057 * internally anyway, so we may as well avoid holding the lock longer
1058 * than we have to here.
1061 ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
1063 BgWriterRequest *request;
1065 if (!IsUnderPostmaster)
1066 return false; /* probably shouldn't even get here */
1069 elog(ERROR, "ForwardFsyncRequest must not be called in bgwriter");
1071 LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
1073 /* we count non-bgwriter writes even when the request queue overflows */
1074 BgWriterShmem->num_backend_writes++;
1076 if (BgWriterShmem->bgwriter_pid == 0 ||
1077 BgWriterShmem->num_requests >= BgWriterShmem->max_requests)
1079 LWLockRelease(BgWriterCommLock);
1082 request = &BgWriterShmem->requests[BgWriterShmem->num_requests++];
1083 request->rnode = rnode;
1084 request->forknum = forknum;
1085 request->segno = segno;
1086 LWLockRelease(BgWriterCommLock);
1091 * AbsorbFsyncRequests
1092 * Retrieve queued fsync requests and pass them to local smgr.
1094 * This is exported because it must be called during CreateCheckPoint;
1095 * we have to be sure we have accepted all pending requests just before
1096 * we start fsync'ing. Since CreateCheckPoint sometimes runs in
1097 * non-bgwriter processes, do nothing if not bgwriter.
1100 AbsorbFsyncRequests(void)
1102 BgWriterRequest *requests = NULL;
1103 BgWriterRequest *request;
1110 * We have to PANIC if we fail to absorb all the pending requests (eg,
1111 * because our hashtable runs out of memory). This is because the system
1112 * cannot run safely if we are unable to fsync what we have been told to
1113 * fsync. Fortunately, the hashtable is so small that the problem is
1114 * quite unlikely to arise in practice.
1116 START_CRIT_SECTION();
1119 * We try to avoid holding the lock for a long time by copying the request
1122 LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
1124 /* Transfer write count into pending pgstats message */
1125 BgWriterStats.m_buf_written_backend += BgWriterShmem->num_backend_writes;
1126 BgWriterShmem->num_backend_writes = 0;
1128 n = BgWriterShmem->num_requests;
1131 requests = (BgWriterRequest *) palloc(n * sizeof(BgWriterRequest));
1132 memcpy(requests, BgWriterShmem->requests, n * sizeof(BgWriterRequest));
1134 BgWriterShmem->num_requests = 0;
1136 LWLockRelease(BgWriterCommLock);
1138 for (request = requests; n > 0; request++, n--)
1139 RememberFsyncRequest(request->rnode, request->forknum, request->segno);