1 /*-------------------------------------------------------------------------
5 * The background writer (bgwriter) is new in 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-2005, PostgreSQL Global Development Group
40 * $PostgreSQL: pgsql/src/backend/postmaster/bgwriter.c,v 1.20 2005/09/12 22:20:16 tgl Exp $
42 *-------------------------------------------------------------------------
49 #include "access/xlog.h"
50 #include "libpq/pqsignal.h"
51 #include "miscadmin.h"
52 #include "postmaster/bgwriter.h"
53 #include "storage/bufmgr.h"
54 #include "storage/freespace.h"
55 #include "storage/ipc.h"
56 #include "storage/pmsignal.h"
57 #include "storage/smgr.h"
58 #include "tcop/tcopprot.h"
59 #include "utils/guc.h"
60 #include "utils/memutils.h"
64 * Shared memory area for communication between bgwriter and backends
66 * The ckpt counters allow backends to watch for completion of a checkpoint
67 * request they send. Here's how it works:
68 * * At start of a checkpoint, bgwriter increments ckpt_started.
69 * * On completion of a checkpoint, bgwriter sets ckpt_done to
71 * * On failure of a checkpoint, bgwrite first increments ckpt_failed,
72 * then sets ckpt_done to equal ckpt_started.
73 * All three fields are declared sig_atomic_t to ensure they can be read
74 * and written without explicit locking. The algorithm for backends is:
75 * 1. Record current values of ckpt_failed and ckpt_started (in that
77 * 2. Send signal to request checkpoint.
78 * 3. Sleep until ckpt_started changes. Now you know a checkpoint has
79 * begun since you started this algorithm (although *not* that it was
80 * specifically initiated by your signal).
81 * 4. Record new value of ckpt_started.
82 * 5. Sleep until ckpt_done >= saved value of ckpt_started. (Use modulo
83 * arithmetic here in case counters wrap around.) Now you know a
84 * checkpoint has started and completed, but not whether it was
86 * 6. If ckpt_failed is different from the originally saved value,
87 * assume request failed; otherwise it was definitely successful.
89 * An additional field is ckpt_time_warn; this is also sig_atomic_t for
90 * simplicity, but is only used as a boolean. If a backend is requesting
91 * a checkpoint for which a checkpoints-too-close-together warning is
92 * reasonable, it should set this field TRUE just before sending the signal.
94 * The requests array holds fsync requests sent by backends and not yet
95 * absorbed by the bgwriter. Unlike the checkpoint fields, the requests
96 * fields are protected by BgWriterCommLock.
103 /* might add a request-type field later */
108 pid_t bgwriter_pid; /* PID of bgwriter (0 if not started) */
110 sig_atomic_t ckpt_started; /* advances when checkpoint starts */
111 sig_atomic_t ckpt_done; /* advances when checkpoint done */
112 sig_atomic_t ckpt_failed; /* advances when checkpoint fails */
114 sig_atomic_t ckpt_time_warn; /* warn if too soon since last ckpt? */
116 int num_requests; /* current # of requests */
117 int max_requests; /* allocated array size */
118 BgWriterRequest requests[1]; /* VARIABLE LENGTH ARRAY */
119 } BgWriterShmemStruct;
121 static BgWriterShmemStruct *BgWriterShmem;
126 int BgWriterDelay = 200;
127 int CheckPointTimeout = 300;
128 int CheckPointWarning = 30;
131 * Flags set by interrupt handlers for later service in the main loop.
133 static volatile sig_atomic_t got_SIGHUP = false;
134 static volatile sig_atomic_t checkpoint_requested = false;
135 static volatile sig_atomic_t shutdown_requested = false;
140 static bool am_bg_writer = false;
142 static bool ckpt_active = false;
144 static time_t last_checkpoint_time;
147 static void bg_quickdie(SIGNAL_ARGS);
148 static void BgSigHupHandler(SIGNAL_ARGS);
149 static void ReqCheckpointHandler(SIGNAL_ARGS);
150 static void ReqShutdownHandler(SIGNAL_ARGS);
154 * Main entry point for bgwriter process
156 * This is invoked from BootstrapMain, which has already created the basic
157 * execution environment, but not enabled signals yet.
160 BackgroundWriterMain(void)
162 sigjmp_buf local_sigjmp_buf;
163 MemoryContext bgwriter_context;
165 Assert(BgWriterShmem != NULL);
166 BgWriterShmem->bgwriter_pid = MyProcPid;
170 * Properly accept or ignore signals the postmaster might send us
172 * Note: we deliberately ignore SIGTERM, because during a standard Unix
173 * system shutdown cycle, init will SIGTERM all processes at once. We
174 * want to wait for the backends to exit, whereupon the postmaster
175 * will tell us it's okay to shut down (via SIGUSR2).
177 * SIGUSR1 is presently unused; keep it spare in case someday we want
178 * this process to participate in sinval messaging.
180 pqsignal(SIGHUP, BgSigHupHandler); /* set flag to read config file */
181 pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
182 pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
183 pqsignal(SIGQUIT, bg_quickdie); /* hard crash time */
184 pqsignal(SIGALRM, SIG_IGN);
185 pqsignal(SIGPIPE, SIG_IGN);
186 pqsignal(SIGUSR1, SIG_IGN); /* reserve for sinval */
187 pqsignal(SIGUSR2, ReqShutdownHandler); /* request shutdown */
190 * Reset some signals that are accepted by postmaster but not here
192 pqsignal(SIGCHLD, SIG_DFL);
193 pqsignal(SIGTTIN, SIG_DFL);
194 pqsignal(SIGTTOU, SIG_DFL);
195 pqsignal(SIGCONT, SIG_DFL);
196 pqsignal(SIGWINCH, SIG_DFL);
198 /* We allow SIGQUIT (quickdie) at all times */
199 #ifdef HAVE_SIGPROCMASK
200 sigdelset(&BlockSig, SIGQUIT);
202 BlockSig &= ~(sigmask(SIGQUIT));
206 * Initialize so that first time-driven checkpoint happens at the
209 last_checkpoint_time = time(NULL);
212 * Create a memory context that we will do all our work in. We do this
213 * so that we can reset the context during error recovery and thereby
214 * avoid possible memory leaks. Formerly this code just ran in
215 * TopMemoryContext, but resetting that would be a really bad idea.
217 bgwriter_context = AllocSetContextCreate(TopMemoryContext,
219 ALLOCSET_DEFAULT_MINSIZE,
220 ALLOCSET_DEFAULT_INITSIZE,
221 ALLOCSET_DEFAULT_MAXSIZE);
222 MemoryContextSwitchTo(bgwriter_context);
225 * If an exception is encountered, processing resumes here.
227 * See notes in postgres.c about the design of this coding.
229 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
231 /* Since not using PG_TRY, must reset error stack by hand */
232 error_context_stack = NULL;
234 /* Prevent interrupts while cleaning up */
237 /* Report the error to the server log */
241 * These operations are really just a minimal subset of
242 * AbortTransaction(). We don't have very many resources to worry
243 * about in bgwriter, but we do have LWLocks and buffers.
249 /* Warn any waiting backends that the checkpoint failed. */
252 /* use volatile pointer to prevent code rearrangement */
253 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
256 bgs->ckpt_done = bgs->ckpt_started;
261 * Now return to normal top-level context and clear ErrorContext
264 MemoryContextSwitchTo(bgwriter_context);
267 /* Flush any leaked data in the top-level context */
268 MemoryContextResetAndDeleteChildren(bgwriter_context);
270 /* Now we can allow interrupts again */
274 * Sleep at least 1 second after any error. A write error is
275 * likely to be repeated, and we don't want to be filling the
276 * error logs as fast as we can.
281 /* We can now handle ereport(ERROR) */
282 PG_exception_stack = &local_sigjmp_buf;
285 * Unblock signals (they were blocked when the postmaster forked us)
287 PG_SETMASK(&UnBlockSig);
294 bool do_checkpoint = false;
295 bool force_checkpoint = false;
301 * Emergency bailout if postmaster has died. This is to avoid the
302 * necessity for manual cleanup of all postmaster children.
304 if (!PostmasterIsAlive(true))
308 * Process any requests or signals received recently.
310 AbsorbFsyncRequests();
315 ProcessConfigFile(PGC_SIGHUP);
317 if (checkpoint_requested)
319 checkpoint_requested = false;
320 do_checkpoint = true;
321 force_checkpoint = true;
323 if (shutdown_requested)
326 DumpFreeSpaceMap(0, 0);
327 /* Normal exit from the bgwriter is here */
328 proc_exit(0); /* done */
332 * Do an unforced checkpoint if too much time has elapsed since
336 elapsed_secs = now - last_checkpoint_time;
337 if (elapsed_secs >= CheckPointTimeout)
338 do_checkpoint = true;
341 * Do a checkpoint if requested, otherwise do one cycle of
342 * dirty-buffer writing.
347 * We will warn if (a) too soon since last checkpoint (whatever
348 * caused it) and (b) somebody has set the ckpt_time_warn flag
349 * since the last checkpoint start. Note in particular that
350 * this implementation will not generate warnings caused by
351 * CheckPointTimeout < CheckPointWarning.
353 if (BgWriterShmem->ckpt_time_warn &&
354 elapsed_secs < CheckPointWarning)
356 (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
358 errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
359 BgWriterShmem->ckpt_time_warn = false;
362 * Indicate checkpoint start to any waiting backends.
365 BgWriterShmem->ckpt_started++;
367 CreateCheckPoint(false, force_checkpoint);
370 * After any checkpoint, close all smgr files. This is so we
371 * won't hang onto smgr references to deleted files
377 * Indicate checkpoint completion to any waiting backends.
379 BgWriterShmem->ckpt_done = BgWriterShmem->ckpt_started;
383 * Note we record the checkpoint start time not end time as
384 * last_checkpoint_time. This is so that time-driven
385 * checkpoints happen at a predictable spacing.
387 last_checkpoint_time = now;
393 * Nap for the configured time, or sleep for 10 seconds if there
394 * is no bgwriter activity configured.
396 * On some platforms, signals won't interrupt the sleep. To ensure
397 * we respond reasonably promptly when someone signals us, break
398 * down the sleep into 1-second increments, and check for
399 * interrupts after each nap.
401 * We absorb pending requests after each short sleep.
403 if ((bgwriter_all_percent > 0.0 && bgwriter_all_maxpages > 0) ||
404 (bgwriter_lru_percent > 0.0 && bgwriter_lru_maxpages > 0))
405 udelay = BgWriterDelay * 1000L;
408 while (udelay > 1000000L)
410 if (got_SIGHUP || checkpoint_requested || shutdown_requested)
413 AbsorbFsyncRequests();
416 if (!(got_SIGHUP || checkpoint_requested || shutdown_requested))
422 /* --------------------------------
423 * signal handler routines
424 * --------------------------------
428 * bg_quickdie() occurs when signalled SIGQUIT by the postmaster.
430 * Some backend has bought the farm,
431 * so we need to stop what we're doing and exit.
434 bg_quickdie(SIGNAL_ARGS)
436 PG_SETMASK(&BlockSig);
439 * DO NOT proc_exit() -- we're here because shared memory may be
440 * corrupted, so we don't want to try to clean up our transaction.
441 * Just nail the windows shut and get out of town.
443 * Note we do exit(1) not exit(0). This is to force the postmaster into
444 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
445 * random backend. This is necessary precisely because we don't clean
446 * up our shared memory state.
451 /* SIGHUP: set flag to re-read config file at next convenient time */
453 BgSigHupHandler(SIGNAL_ARGS)
458 /* SIGINT: set flag to run a normal checkpoint right away */
460 ReqCheckpointHandler(SIGNAL_ARGS)
462 checkpoint_requested = true;
465 /* SIGUSR2: set flag to run a shutdown checkpoint and exit */
467 ReqShutdownHandler(SIGNAL_ARGS)
469 shutdown_requested = true;
473 /* --------------------------------
474 * communication with backends
475 * --------------------------------
480 * Compute space needed for bgwriter-related shared memory
483 BgWriterShmemSize(void)
488 * Currently, the size of the requests[] array is arbitrarily set
489 * equal to NBuffers. This may prove too large or small ...
491 size = offsetof(BgWriterShmemStruct, requests);
492 size = add_size(size, mul_size(NBuffers, sizeof(BgWriterRequest)));
499 * Allocate and initialize bgwriter-related shared memory
502 BgWriterShmemInit(void)
506 BgWriterShmem = (BgWriterShmemStruct *)
507 ShmemInitStruct("Background Writer Data",
510 if (BgWriterShmem == NULL)
512 (errcode(ERRCODE_OUT_OF_MEMORY),
513 errmsg("not enough shared memory for background writer")));
515 return; /* already initialized */
517 MemSet(BgWriterShmem, 0, sizeof(BgWriterShmemStruct));
518 BgWriterShmem->max_requests = NBuffers;
523 * Called in backend processes to request an immediate checkpoint
525 * If waitforit is true, wait until the checkpoint is completed
526 * before returning; otherwise, just signal the request and return
529 * If warnontime is true, and it's "too soon" since the last checkpoint,
530 * the bgwriter will log a warning. This should be true only for checkpoints
531 * caused due to xlog filling, else the warning will be misleading.
534 RequestCheckpoint(bool waitforit, bool warnontime)
536 /* use volatile pointer to prevent code rearrangement */
537 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
538 sig_atomic_t old_failed = bgs->ckpt_failed;
539 sig_atomic_t old_started = bgs->ckpt_started;
542 * If in a standalone backend, just do it ourselves.
544 if (!IsPostmasterEnvironment)
546 CreateCheckPoint(false, true);
549 * After any checkpoint, close all smgr files. This is so we
550 * won't hang onto smgr references to deleted files
558 /* Set warning request flag if appropriate */
560 bgs->ckpt_time_warn = true;
563 * Send signal to request checkpoint. When waitforit is false, we
564 * consider failure to send the signal to be nonfatal.
566 if (BgWriterShmem->bgwriter_pid == 0)
567 elog(waitforit ? ERROR : LOG,
568 "could not request checkpoint because bgwriter not running");
569 if (kill(BgWriterShmem->bgwriter_pid, SIGINT) != 0)
570 elog(waitforit ? ERROR : LOG,
571 "could not signal for checkpoint: %m");
574 * If requested, wait for completion. We detect completion according
575 * to the algorithm given above.
579 while (bgs->ckpt_started == old_started)
581 CHECK_FOR_INTERRUPTS();
584 old_started = bgs->ckpt_started;
587 * We are waiting for ckpt_done >= old_started, in a modulo sense.
588 * This is a little tricky since we don't know the width or
589 * signedness of sig_atomic_t. We make the lowest common
590 * denominator assumption that it is only as wide as "char". This
591 * means that this algorithm will cope correctly as long as we
592 * don't sleep for more than 127 completed checkpoints. (If we
593 * do, we will get another chance to exit after 128 more
596 while (((signed char) (bgs->ckpt_done - old_started)) < 0)
598 CHECK_FOR_INTERRUPTS();
601 if (bgs->ckpt_failed != old_failed)
603 (errmsg("checkpoint request failed"),
604 errhint("Consult the server log for details.")));
609 * ForwardFsyncRequest
610 * Forward a file-fsync request from a backend to the bgwriter
612 * Whenever a backend is compelled to write directly to a relation
613 * (which should be seldom, if the bgwriter is getting its job done),
614 * the backend calls this routine to pass over knowledge that the relation
615 * is dirty and must be fsync'd before next checkpoint.
617 * If we are unable to pass over the request (at present, this can happen
618 * if the shared memory queue is full), we return false. That forces
619 * the backend to do its own fsync. We hope that will be even more seldom.
621 * Note: we presently make no attempt to eliminate duplicate requests
622 * in the requests[] queue. The bgwriter will have to eliminate dups
623 * internally anyway, so we may as well avoid holding the lock longer
624 * than we have to here.
627 ForwardFsyncRequest(RelFileNode rnode, BlockNumber segno)
629 BgWriterRequest *request;
631 if (!IsUnderPostmaster)
632 return false; /* probably shouldn't even get here */
633 Assert(BgWriterShmem != NULL);
635 LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
636 if (BgWriterShmem->bgwriter_pid == 0 ||
637 BgWriterShmem->num_requests >= BgWriterShmem->max_requests)
639 LWLockRelease(BgWriterCommLock);
642 request = &BgWriterShmem->requests[BgWriterShmem->num_requests++];
643 request->rnode = rnode;
644 request->segno = segno;
645 LWLockRelease(BgWriterCommLock);
650 * AbsorbFsyncRequests
651 * Retrieve queued fsync requests and pass them to local smgr.
653 * This is exported because it must be called during CreateCheckPoint;
654 * we have to be sure we have accepted all pending requests *after* we
655 * establish the checkpoint REDO pointer. Since CreateCheckPoint
656 * sometimes runs in non-bgwriter processes, do nothing if not bgwriter.
659 AbsorbFsyncRequests(void)
661 BgWriterRequest *requests = NULL;
662 BgWriterRequest *request;
669 * We have to PANIC if we fail to absorb all the pending requests
670 * (eg, because our hashtable runs out of memory). This is because
671 * the system cannot run safely if we are unable to fsync what we
672 * have been told to fsync. Fortunately, the hashtable is so small
673 * that the problem is quite unlikely to arise in practice.
675 START_CRIT_SECTION();
678 * We try to avoid holding the lock for a long time by copying the
681 LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
683 n = BgWriterShmem->num_requests;
686 requests = (BgWriterRequest *) palloc(n * sizeof(BgWriterRequest));
687 memcpy(requests, BgWriterShmem->requests, n * sizeof(BgWriterRequest));
689 BgWriterShmem->num_requests = 0;
691 LWLockRelease(BgWriterCommLock);
693 for (request = requests; n > 0; request++, n--)
694 RememberFsyncRequest(request->rnode, request->segno);