Minor improvements in backup and recovery:
[PostgreSQL.git] / src / backend / postmaster / bgwriter.c
blob500f2f85e925a34522dc3e3ed635b4e2dd652aa6
1 /*-------------------------------------------------------------------------
3 * bgwriter.c
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
19 * condition.)
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-2007, PostgreSQL Global Development Group
39 * IDENTIFICATION
40 * $PostgreSQL$
42 *-------------------------------------------------------------------------
44 #include "postgres.h"
46 #include <signal.h>
47 #include <sys/time.h>
48 #include <time.h>
49 #include <unistd.h>
51 #include "access/xlog_internal.h"
52 #include "libpq/pqsignal.h"
53 #include "miscadmin.h"
54 #include "pgstat.h"
55 #include "postmaster/bgwriter.h"
56 #include "storage/fd.h"
57 #include "storage/freespace.h"
58 #include "storage/ipc.h"
59 #include "storage/lwlock.h"
60 #include "storage/pmsignal.h"
61 #include "storage/shmem.h"
62 #include "storage/smgr.h"
63 #include "storage/spin.h"
64 #include "tcop/tcopprot.h"
65 #include "utils/guc.h"
66 #include "utils/memutils.h"
67 #include "utils/resowner.h"
70 /*----------
71 * Shared memory area for communication between bgwriter and backends
73 * The ckpt counters allow backends to watch for completion of a checkpoint
74 * request they send. Here's how it works:
75 * * At start of a checkpoint, bgwriter reads (and clears) the request flags
76 * and increments ckpt_started, while holding ckpt_lck.
77 * * On completion of a checkpoint, bgwriter sets ckpt_done to
78 * equal ckpt_started.
79 * * On failure of a checkpoint, bgwriter increments ckpt_failed
80 * and sets ckpt_done to equal ckpt_started.
82 * The algorithm for backends is:
83 * 1. Record current values of ckpt_failed and ckpt_started, and
84 * set request flags, while holding ckpt_lck.
85 * 2. Send signal to request checkpoint.
86 * 3. Sleep until ckpt_started changes. Now you know a checkpoint has
87 * begun since you started this algorithm (although *not* that it was
88 * specifically initiated by your signal), and that it is using your flags.
89 * 4. Record new value of ckpt_started.
90 * 5. Sleep until ckpt_done >= saved value of ckpt_started. (Use modulo
91 * arithmetic here in case counters wrap around.) Now you know a
92 * checkpoint has started and completed, but not whether it was
93 * successful.
94 * 6. If ckpt_failed is different from the originally saved value,
95 * assume request failed; otherwise it was definitely successful.
97 * ckpt_flags holds the OR of the checkpoint request flags sent by all
98 * requesting backends since the last checkpoint start. The flags are
99 * chosen so that OR'ing is the correct way to combine multiple requests.
101 * num_backend_writes is used to count the number of buffer writes performed
102 * by non-bgwriter processes. This counter should be wide enough that it
103 * can't overflow during a single bgwriter cycle.
105 * The requests array holds fsync requests sent by backends and not yet
106 * absorbed by the bgwriter.
108 * Unlike the checkpoint fields, num_backend_writes and the requests
109 * fields are protected by BgWriterCommLock.
110 *----------
112 typedef struct
114 RelFileNode rnode;
115 BlockNumber segno; /* see md.c for special values */
116 /* might add a real request-type field later; not needed yet */
117 } BgWriterRequest;
119 typedef struct
121 pid_t bgwriter_pid; /* PID of bgwriter (0 if not started) */
123 slock_t ckpt_lck; /* protects all the ckpt_* fields */
125 int ckpt_started; /* advances when checkpoint starts */
126 int ckpt_done; /* advances when checkpoint done */
127 int ckpt_failed; /* advances when checkpoint fails */
129 int ckpt_flags; /* checkpoint flags, as defined in xlog.h */
131 uint32 num_backend_writes; /* counts non-bgwriter buffer writes */
133 int num_requests; /* current # of requests */
134 int max_requests; /* allocated array size */
135 BgWriterRequest requests[1]; /* VARIABLE LENGTH ARRAY */
136 } BgWriterShmemStruct;
138 static BgWriterShmemStruct *BgWriterShmem;
140 /* interval for calling AbsorbFsyncRequests in CheckpointWriteDelay */
141 #define WRITES_PER_ABSORB 1000
144 * GUC parameters
146 int BgWriterDelay = 200;
147 int CheckPointTimeout = 300;
148 int CheckPointWarning = 30;
149 double CheckPointCompletionTarget = 0.5;
152 * Flags set by interrupt handlers for later service in the main loop.
154 static volatile sig_atomic_t got_SIGHUP = false;
155 static volatile sig_atomic_t checkpoint_requested = false;
156 static volatile sig_atomic_t shutdown_requested = false;
159 * Private state
161 static bool am_bg_writer = false;
163 static bool ckpt_active = false;
165 /* these values are valid when ckpt_active is true: */
166 static time_t ckpt_start_time;
167 static XLogRecPtr ckpt_start_recptr;
168 static double ckpt_cached_elapsed;
170 static time_t last_checkpoint_time;
171 static time_t last_xlog_switch_time;
173 /* Prototypes for private functions */
175 static void CheckArchiveTimeout(void);
176 static void BgWriterNap(void);
177 static bool IsCheckpointOnSchedule(double progress);
178 static bool ImmediateCheckpointRequested(void);
180 /* Signal handlers */
182 static void bg_quickdie(SIGNAL_ARGS);
183 static void BgSigHupHandler(SIGNAL_ARGS);
184 static void ReqCheckpointHandler(SIGNAL_ARGS);
185 static void ReqShutdownHandler(SIGNAL_ARGS);
189 * Main entry point for bgwriter process
191 * This is invoked from BootstrapMain, which has already created the basic
192 * execution environment, but not enabled signals yet.
194 void
195 BackgroundWriterMain(void)
197 sigjmp_buf local_sigjmp_buf;
198 MemoryContext bgwriter_context;
200 BgWriterShmem->bgwriter_pid = MyProcPid;
201 am_bg_writer = true;
204 * If possible, make this process a group leader, so that the postmaster
205 * can signal any child processes too. (bgwriter probably never has
206 * any child processes, but for consistency we make all postmaster
207 * child processes do this.)
209 #ifdef HAVE_SETSID
210 if (setsid() < 0)
211 elog(FATAL, "setsid() failed: %m");
212 #endif
215 * Properly accept or ignore signals the postmaster might send us
217 * Note: we deliberately ignore SIGTERM, because during a standard Unix
218 * system shutdown cycle, init will SIGTERM all processes at once. We
219 * want to wait for the backends to exit, whereupon the postmaster will
220 * tell us it's okay to shut down (via SIGUSR2).
222 * SIGUSR1 is presently unused; keep it spare in case someday we want this
223 * process to participate in sinval messaging.
225 pqsignal(SIGHUP, BgSigHupHandler); /* set flag to read config file */
226 pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
227 pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
228 pqsignal(SIGQUIT, bg_quickdie); /* hard crash time */
229 pqsignal(SIGALRM, SIG_IGN);
230 pqsignal(SIGPIPE, SIG_IGN);
231 pqsignal(SIGUSR1, SIG_IGN); /* reserve for sinval */
232 pqsignal(SIGUSR2, ReqShutdownHandler); /* request shutdown */
235 * Reset some signals that are accepted by postmaster but not here
237 pqsignal(SIGCHLD, SIG_DFL);
238 pqsignal(SIGTTIN, SIG_DFL);
239 pqsignal(SIGTTOU, SIG_DFL);
240 pqsignal(SIGCONT, SIG_DFL);
241 pqsignal(SIGWINCH, SIG_DFL);
243 /* We allow SIGQUIT (quickdie) at all times */
244 #ifdef HAVE_SIGPROCMASK
245 sigdelset(&BlockSig, SIGQUIT);
246 #else
247 BlockSig &= ~(sigmask(SIGQUIT));
248 #endif
251 * Initialize so that first time-driven event happens at the correct time.
253 last_checkpoint_time = last_xlog_switch_time = time(NULL);
256 * Create a resource owner to keep track of our resources (currently only
257 * buffer pins).
259 CurrentResourceOwner = ResourceOwnerCreate(NULL, "Background Writer");
262 * Create a memory context that we will do all our work in. We do this so
263 * that we can reset the context during error recovery and thereby avoid
264 * possible memory leaks. Formerly this code just ran in
265 * TopMemoryContext, but resetting that would be a really bad idea.
267 bgwriter_context = AllocSetContextCreate(TopMemoryContext,
268 "Background Writer",
269 ALLOCSET_DEFAULT_MINSIZE,
270 ALLOCSET_DEFAULT_INITSIZE,
271 ALLOCSET_DEFAULT_MAXSIZE);
272 MemoryContextSwitchTo(bgwriter_context);
275 * If an exception is encountered, processing resumes here.
277 * See notes in postgres.c about the design of this coding.
279 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
281 /* Since not using PG_TRY, must reset error stack by hand */
282 error_context_stack = NULL;
284 /* Prevent interrupts while cleaning up */
285 HOLD_INTERRUPTS();
287 /* Report the error to the server log */
288 EmitErrorReport();
291 * These operations are really just a minimal subset of
292 * AbortTransaction(). We don't have very many resources to worry
293 * about in bgwriter, but we do have LWLocks, buffers, and temp files.
295 LWLockReleaseAll();
296 AbortBufferIO();
297 UnlockBuffers();
298 /* buffer pins are released here: */
299 ResourceOwnerRelease(CurrentResourceOwner,
300 RESOURCE_RELEASE_BEFORE_LOCKS,
301 false, true);
302 /* we needn't bother with the other ResourceOwnerRelease phases */
303 AtEOXact_Buffers(false);
304 AtEOXact_Files();
305 AtEOXact_HashTables(false);
307 /* Warn any waiting backends that the checkpoint failed. */
308 if (ckpt_active)
310 /* use volatile pointer to prevent code rearrangement */
311 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
313 SpinLockAcquire(&bgs->ckpt_lck);
314 bgs->ckpt_failed++;
315 bgs->ckpt_done = bgs->ckpt_started;
316 SpinLockRelease(&bgs->ckpt_lck);
318 ckpt_active = false;
322 * Now return to normal top-level context and clear ErrorContext for
323 * next time.
325 MemoryContextSwitchTo(bgwriter_context);
326 FlushErrorState();
328 /* Flush any leaked data in the top-level context */
329 MemoryContextResetAndDeleteChildren(bgwriter_context);
331 /* Now we can allow interrupts again */
332 RESUME_INTERRUPTS();
335 * Sleep at least 1 second after any error. A write error is likely
336 * to be repeated, and we don't want to be filling the error logs as
337 * fast as we can.
339 pg_usleep(1000000L);
342 * Close all open files after any error. This is helpful on Windows,
343 * where holding deleted files open causes various strange errors.
344 * It's not clear we need it elsewhere, but shouldn't hurt.
346 smgrcloseall();
349 /* We can now handle ereport(ERROR) */
350 PG_exception_stack = &local_sigjmp_buf;
353 * Unblock signals (they were blocked when the postmaster forked us)
355 PG_SETMASK(&UnBlockSig);
358 * Loop forever
360 for (;;)
362 bool do_checkpoint = false;
363 int flags = 0;
364 time_t now;
365 int elapsed_secs;
368 * Emergency bailout if postmaster has died. This is to avoid the
369 * necessity for manual cleanup of all postmaster children.
371 if (!PostmasterIsAlive(true))
372 exit(1);
375 * Process any requests or signals received recently.
377 AbsorbFsyncRequests();
379 if (got_SIGHUP)
381 got_SIGHUP = false;
382 ProcessConfigFile(PGC_SIGHUP);
384 if (checkpoint_requested)
386 checkpoint_requested = false;
387 do_checkpoint = true;
388 BgWriterStats.m_requested_checkpoints++;
390 if (shutdown_requested)
393 * From here on, elog(ERROR) should end with exit(1), not send
394 * control back to the sigsetjmp block above
396 ExitOnAnyError = true;
397 /* Close down the database */
398 ShutdownXLOG(0, 0);
399 DumpFreeSpaceMap(0, 0);
400 /* Normal exit from the bgwriter is here */
401 proc_exit(0); /* done */
405 * Force a checkpoint if too much time has elapsed since the
406 * last one. Note that we count a timed checkpoint in stats only
407 * when this occurs without an external request, but we set the
408 * CAUSE_TIME flag bit even if there is also an external request.
410 now = time(NULL);
411 elapsed_secs = now - last_checkpoint_time;
412 if (elapsed_secs >= CheckPointTimeout)
414 if (!do_checkpoint)
415 BgWriterStats.m_timed_checkpoints++;
416 do_checkpoint = true;
417 flags |= CHECKPOINT_CAUSE_TIME;
421 * Do a checkpoint if requested, otherwise do one cycle of
422 * dirty-buffer writing.
424 if (do_checkpoint)
426 /* use volatile pointer to prevent code rearrangement */
427 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
430 * Atomically fetch the request flags to figure out what
431 * kind of a checkpoint we should perform, and increase the
432 * started-counter to acknowledge that we've started
433 * a new checkpoint.
435 SpinLockAcquire(&bgs->ckpt_lck);
436 flags |= bgs->ckpt_flags;
437 bgs->ckpt_flags = 0;
438 bgs->ckpt_started++;
439 SpinLockRelease(&bgs->ckpt_lck);
442 * We will warn if (a) too soon since last checkpoint (whatever
443 * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
444 * since the last checkpoint start. Note in particular that this
445 * implementation will not generate warnings caused by
446 * CheckPointTimeout < CheckPointWarning.
448 if ((flags & CHECKPOINT_CAUSE_XLOG) &&
449 elapsed_secs < CheckPointWarning)
450 ereport(LOG,
451 (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
452 elapsed_secs),
453 errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
456 * Initialize bgwriter-private variables used during checkpoint.
458 ckpt_active = true;
459 ckpt_start_recptr = GetInsertRecPtr();
460 ckpt_start_time = now;
461 ckpt_cached_elapsed = 0;
464 * Do the checkpoint.
466 CreateCheckPoint(flags);
469 * After any checkpoint, close all smgr files. This is so we
470 * won't hang onto smgr references to deleted files indefinitely.
472 smgrcloseall();
475 * Indicate checkpoint completion to any waiting backends.
477 SpinLockAcquire(&bgs->ckpt_lck);
478 bgs->ckpt_done = bgs->ckpt_started;
479 SpinLockRelease(&bgs->ckpt_lck);
481 ckpt_active = false;
484 * Note we record the checkpoint start time not end time as
485 * last_checkpoint_time. This is so that time-driven checkpoints
486 * happen at a predictable spacing.
488 last_checkpoint_time = now;
490 else
491 BgBufferSync();
493 /* Check for archive_timeout and switch xlog files if necessary. */
494 CheckArchiveTimeout();
496 /* Nap for the configured time. */
497 BgWriterNap();
502 * CheckArchiveTimeout -- check for archive_timeout and switch xlog files
503 * if needed
505 static void
506 CheckArchiveTimeout(void)
508 time_t now;
509 time_t last_time;
511 if (XLogArchiveTimeout <= 0)
512 return;
514 now = time(NULL);
516 /* First we do a quick check using possibly-stale local state. */
517 if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
518 return;
521 * Update local state ... note that last_xlog_switch_time is the
522 * last time a switch was performed *or requested*.
524 last_time = GetLastSegSwitchTime();
526 last_xlog_switch_time = Max(last_xlog_switch_time, last_time);
528 /* Now we can do the real check */
529 if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
531 XLogRecPtr switchpoint;
533 /* OK, it's time to switch */
534 switchpoint = RequestXLogSwitch();
537 * If the returned pointer points exactly to a segment
538 * boundary, assume nothing happened.
540 if ((switchpoint.xrecoff % XLogSegSize) != 0)
541 ereport(DEBUG1,
542 (errmsg("transaction log switch forced (archive_timeout=%d)",
543 XLogArchiveTimeout)));
546 * Update state in any case, so we don't retry constantly when
547 * the system is idle.
549 last_xlog_switch_time = now;
554 * BgWriterNap -- Nap for the configured time or until a signal is received.
556 static void
557 BgWriterNap(void)
559 long udelay;
562 * Send off activity statistics to the stats collector
564 pgstat_send_bgwriter();
567 * Nap for the configured time, or sleep for 10 seconds if there is no
568 * bgwriter activity configured.
570 * On some platforms, signals won't interrupt the sleep. To ensure we
571 * respond reasonably promptly when someone signals us, break down the
572 * sleep into 1-second increments, and check for interrupts after each
573 * nap.
575 * We absorb pending requests after each short sleep.
577 if (bgwriter_lru_maxpages > 0 || ckpt_active)
578 udelay = BgWriterDelay * 1000L;
579 else if (XLogArchiveTimeout > 0)
580 udelay = 1000000L; /* One second */
581 else
582 udelay = 10000000L; /* Ten seconds */
584 while (udelay > 999999L)
586 if (got_SIGHUP || shutdown_requested ||
587 (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested))
588 break;
589 pg_usleep(1000000L);
590 AbsorbFsyncRequests();
591 udelay -= 1000000L;
594 if (!(got_SIGHUP || shutdown_requested ||
595 (ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested)))
596 pg_usleep(udelay);
600 * Returns true if an immediate checkpoint request is pending. (Note that
601 * this does not check the *current* checkpoint's IMMEDIATE flag, but whether
602 * there is one pending behind it.)
604 static bool
605 ImmediateCheckpointRequested(void)
607 if (checkpoint_requested)
609 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
612 * We don't need to acquire the ckpt_lck in this case because we're
613 * only looking at a single flag bit.
615 if (bgs->ckpt_flags & CHECKPOINT_IMMEDIATE)
616 return true;
618 return false;
622 * CheckpointWriteDelay -- yield control to bgwriter during a checkpoint
624 * This function is called after each page write performed by BufferSync().
625 * It is responsible for keeping the bgwriter's normal activities in
626 * progress during a long checkpoint, and for throttling BufferSync()'s
627 * write rate to hit checkpoint_completion_target.
629 * The checkpoint request flags should be passed in; currently the only one
630 * examined is CHECKPOINT_IMMEDIATE, which disables delays between writes.
632 * 'progress' is an estimate of how much of the work has been done, as a
633 * fraction between 0.0 meaning none, and 1.0 meaning all done.
635 void
636 CheckpointWriteDelay(int flags, double progress)
638 static int absorb_counter = WRITES_PER_ABSORB;
640 /* Do nothing if checkpoint is being executed by non-bgwriter process */
641 if (!am_bg_writer)
642 return;
645 * Perform the usual bgwriter duties and take a nap, unless we're behind
646 * schedule, in which case we just try to catch up as quickly as possible.
648 if (!(flags & CHECKPOINT_IMMEDIATE) &&
649 !shutdown_requested &&
650 !ImmediateCheckpointRequested() &&
651 IsCheckpointOnSchedule(progress))
653 if (got_SIGHUP)
655 got_SIGHUP = false;
656 ProcessConfigFile(PGC_SIGHUP);
659 AbsorbFsyncRequests();
660 absorb_counter = WRITES_PER_ABSORB;
662 BgBufferSync();
663 CheckArchiveTimeout();
664 BgWriterNap();
666 else if (--absorb_counter <= 0)
669 * Absorb pending fsync requests after each WRITES_PER_ABSORB write
670 * operations even when we don't sleep, to prevent overflow of the
671 * fsync request queue.
673 AbsorbFsyncRequests();
674 absorb_counter = WRITES_PER_ABSORB;
679 * IsCheckpointOnSchedule -- are we on schedule to finish this checkpoint
680 * in time?
682 * Compares the current progress against the time/segments elapsed since last
683 * checkpoint, and returns true if the progress we've made this far is greater
684 * than the elapsed time/segments.
686 static bool
687 IsCheckpointOnSchedule(double progress)
689 XLogRecPtr recptr;
690 struct timeval now;
691 double elapsed_xlogs,
692 elapsed_time;
694 Assert(ckpt_active);
696 /* Scale progress according to checkpoint_completion_target. */
697 progress *= CheckPointCompletionTarget;
700 * Check against the cached value first. Only do the more expensive
701 * calculations once we reach the target previously calculated. Since
702 * neither time or WAL insert pointer moves backwards, a freshly
703 * calculated value can only be greater than or equal to the cached value.
705 if (progress < ckpt_cached_elapsed)
706 return false;
709 * Check progress against WAL segments written and checkpoint_segments.
711 * We compare the current WAL insert location against the location
712 * computed before calling CreateCheckPoint. The code in XLogInsert that
713 * actually triggers a checkpoint when checkpoint_segments is exceeded
714 * compares against RedoRecptr, so this is not completely accurate.
715 * However, it's good enough for our purposes, we're only calculating
716 * an estimate anyway.
718 recptr = GetInsertRecPtr();
719 elapsed_xlogs =
720 (((double) (int32) (recptr.xlogid - ckpt_start_recptr.xlogid)) * XLogSegsPerFile +
721 ((double) (int32) (recptr.xrecoff - ckpt_start_recptr.xrecoff)) / XLogSegSize) /
722 CheckPointSegments;
724 if (progress < elapsed_xlogs)
726 ckpt_cached_elapsed = elapsed_xlogs;
727 return false;
731 * Check progress against time elapsed and checkpoint_timeout.
733 gettimeofday(&now, NULL);
734 elapsed_time = ((double) (now.tv_sec - ckpt_start_time) +
735 now.tv_usec / 1000000.0) / CheckPointTimeout;
737 if (progress < elapsed_time)
739 ckpt_cached_elapsed = elapsed_time;
740 return false;
743 /* It looks like we're on schedule. */
744 return true;
748 /* --------------------------------
749 * signal handler routines
750 * --------------------------------
754 * bg_quickdie() occurs when signalled SIGQUIT by the postmaster.
756 * Some backend has bought the farm,
757 * so we need to stop what we're doing and exit.
759 static void
760 bg_quickdie(SIGNAL_ARGS)
762 PG_SETMASK(&BlockSig);
765 * DO NOT proc_exit() -- we're here because shared memory may be
766 * corrupted, so we don't want to try to clean up our transaction. Just
767 * nail the windows shut and get out of town.
769 * Note we do exit(2) not exit(0). This is to force the postmaster into a
770 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
771 * backend. This is necessary precisely because we don't clean up our
772 * shared memory state.
774 exit(2);
777 /* SIGHUP: set flag to re-read config file at next convenient time */
778 static void
779 BgSigHupHandler(SIGNAL_ARGS)
781 got_SIGHUP = true;
784 /* SIGINT: set flag to run a normal checkpoint right away */
785 static void
786 ReqCheckpointHandler(SIGNAL_ARGS)
788 checkpoint_requested = true;
791 /* SIGUSR2: set flag to run a shutdown checkpoint and exit */
792 static void
793 ReqShutdownHandler(SIGNAL_ARGS)
795 shutdown_requested = true;
799 /* --------------------------------
800 * communication with backends
801 * --------------------------------
805 * BgWriterShmemSize
806 * Compute space needed for bgwriter-related shared memory
808 Size
809 BgWriterShmemSize(void)
811 Size size;
814 * Currently, the size of the requests[] array is arbitrarily set equal to
815 * NBuffers. This may prove too large or small ...
817 size = offsetof(BgWriterShmemStruct, requests);
818 size = add_size(size, mul_size(NBuffers, sizeof(BgWriterRequest)));
820 return size;
824 * BgWriterShmemInit
825 * Allocate and initialize bgwriter-related shared memory
827 void
828 BgWriterShmemInit(void)
830 bool found;
832 BgWriterShmem = (BgWriterShmemStruct *)
833 ShmemInitStruct("Background Writer Data",
834 BgWriterShmemSize(),
835 &found);
836 if (BgWriterShmem == NULL)
837 ereport(FATAL,
838 (errcode(ERRCODE_OUT_OF_MEMORY),
839 errmsg("not enough shared memory for background writer")));
840 if (found)
841 return; /* already initialized */
843 MemSet(BgWriterShmem, 0, sizeof(BgWriterShmemStruct));
844 SpinLockInit(&BgWriterShmem->ckpt_lck);
845 BgWriterShmem->max_requests = NBuffers;
849 * RequestCheckpoint
850 * Called in backend processes to request a checkpoint
852 * flags is a bitwise OR of the following:
853 * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
854 * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
855 * ignoring checkpoint_completion_target parameter.
856 * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occured
857 * since the last one (implied by CHECKPOINT_IS_SHUTDOWN).
858 * CHECKPOINT_WAIT: wait for completion before returning (otherwise,
859 * just signal bgwriter to do it, and return).
860 * CHECKPOINT_CAUSE_XLOG: checkpoint is requested due to xlog filling.
861 * (This affects logging, and in particular enables CheckPointWarning.)
863 void
864 RequestCheckpoint(int flags)
866 /* use volatile pointer to prevent code rearrangement */
867 volatile BgWriterShmemStruct *bgs = BgWriterShmem;
868 int old_failed, old_started;
871 * If in a standalone backend, just do it ourselves.
873 if (!IsPostmasterEnvironment)
876 * There's no point in doing slow checkpoints in a standalone
877 * backend, because there's no other backends the checkpoint could
878 * disrupt.
880 CreateCheckPoint(flags | CHECKPOINT_IMMEDIATE);
883 * After any checkpoint, close all smgr files. This is so we won't
884 * hang onto smgr references to deleted files indefinitely.
886 smgrcloseall();
888 return;
892 * Atomically set the request flags, and take a snapshot of the counters.
893 * When we see ckpt_started > old_started, we know the flags we set here
894 * have been seen by bgwriter.
896 * Note that we OR the flags with any existing flags, to avoid overriding
897 * a "stronger" request by another backend. The flag senses must be
898 * chosen to make this work!
900 SpinLockAcquire(&bgs->ckpt_lck);
902 old_failed = bgs->ckpt_failed;
903 old_started = bgs->ckpt_started;
904 bgs->ckpt_flags |= flags;
906 SpinLockRelease(&bgs->ckpt_lck);
909 * Send signal to request checkpoint. When not waiting, we
910 * consider failure to send the signal to be nonfatal.
912 if (BgWriterShmem->bgwriter_pid == 0)
913 elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
914 "could not request checkpoint because bgwriter not running");
915 if (kill(BgWriterShmem->bgwriter_pid, SIGINT) != 0)
916 elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
917 "could not signal for checkpoint: %m");
920 * If requested, wait for completion. We detect completion according to
921 * the algorithm given above.
923 if (flags & CHECKPOINT_WAIT)
925 int new_started, new_failed;
927 /* Wait for a new checkpoint to start. */
928 for(;;)
930 SpinLockAcquire(&bgs->ckpt_lck);
931 new_started = bgs->ckpt_started;
932 SpinLockRelease(&bgs->ckpt_lck);
934 if (new_started != old_started)
935 break;
937 CHECK_FOR_INTERRUPTS();
938 pg_usleep(100000L);
942 * We are waiting for ckpt_done >= new_started, in a modulo sense.
944 for(;;)
946 int new_done;
948 SpinLockAcquire(&bgs->ckpt_lck);
949 new_done = bgs->ckpt_done;
950 new_failed = bgs->ckpt_failed;
951 SpinLockRelease(&bgs->ckpt_lck);
953 if (new_done - new_started >= 0)
954 break;
956 CHECK_FOR_INTERRUPTS();
957 pg_usleep(100000L);
960 if (new_failed != old_failed)
961 ereport(ERROR,
962 (errmsg("checkpoint request failed"),
963 errhint("Consult recent messages in the server log for details.")));
968 * ForwardFsyncRequest
969 * Forward a file-fsync request from a backend to the bgwriter
971 * Whenever a backend is compelled to write directly to a relation
972 * (which should be seldom, if the bgwriter is getting its job done),
973 * the backend calls this routine to pass over knowledge that the relation
974 * is dirty and must be fsync'd before next checkpoint. We also use this
975 * opportunity to count such writes for statistical purposes.
977 * segno specifies which segment (not block!) of the relation needs to be
978 * fsync'd. (Since the valid range is much less than BlockNumber, we can
979 * use high values for special flags; that's all internal to md.c, which
980 * see for details.)
982 * If we are unable to pass over the request (at present, this can happen
983 * if the shared memory queue is full), we return false. That forces
984 * the backend to do its own fsync. We hope that will be even more seldom.
986 * Note: we presently make no attempt to eliminate duplicate requests
987 * in the requests[] queue. The bgwriter will have to eliminate dups
988 * internally anyway, so we may as well avoid holding the lock longer
989 * than we have to here.
991 bool
992 ForwardFsyncRequest(RelFileNode rnode, BlockNumber segno)
994 BgWriterRequest *request;
996 if (!IsUnderPostmaster)
997 return false; /* probably shouldn't even get here */
999 Assert(!am_bg_writer);
1001 LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
1003 /* we count non-bgwriter writes even when the request queue overflows */
1004 BgWriterShmem->num_backend_writes++;
1006 if (BgWriterShmem->bgwriter_pid == 0 ||
1007 BgWriterShmem->num_requests >= BgWriterShmem->max_requests)
1009 LWLockRelease(BgWriterCommLock);
1010 return false;
1012 request = &BgWriterShmem->requests[BgWriterShmem->num_requests++];
1013 request->rnode = rnode;
1014 request->segno = segno;
1015 LWLockRelease(BgWriterCommLock);
1016 return true;
1020 * AbsorbFsyncRequests
1021 * Retrieve queued fsync requests and pass them to local smgr.
1023 * This is exported because it must be called during CreateCheckPoint;
1024 * we have to be sure we have accepted all pending requests just before
1025 * we start fsync'ing. Since CreateCheckPoint sometimes runs in
1026 * non-bgwriter processes, do nothing if not bgwriter.
1028 void
1029 AbsorbFsyncRequests(void)
1031 BgWriterRequest *requests = NULL;
1032 BgWriterRequest *request;
1033 int n;
1035 if (!am_bg_writer)
1036 return;
1039 * We have to PANIC if we fail to absorb all the pending requests (eg,
1040 * because our hashtable runs out of memory). This is because the system
1041 * cannot run safely if we are unable to fsync what we have been told to
1042 * fsync. Fortunately, the hashtable is so small that the problem is
1043 * quite unlikely to arise in practice.
1045 START_CRIT_SECTION();
1048 * We try to avoid holding the lock for a long time by copying the request
1049 * array.
1051 LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
1053 /* Transfer write count into pending pgstats message */
1054 BgWriterStats.m_buf_written_backend += BgWriterShmem->num_backend_writes;
1055 BgWriterShmem->num_backend_writes = 0;
1057 n = BgWriterShmem->num_requests;
1058 if (n > 0)
1060 requests = (BgWriterRequest *) palloc(n * sizeof(BgWriterRequest));
1061 memcpy(requests, BgWriterShmem->requests, n * sizeof(BgWriterRequest));
1063 BgWriterShmem->num_requests = 0;
1065 LWLockRelease(BgWriterCommLock);
1067 for (request = requests; n > 0; request++, n--)
1068 RememberFsyncRequest(request->rnode, request->segno);
1070 if (requests)
1071 pfree(requests);
1073 END_CRIT_SECTION();