Header And Logo

| The world's most advanced open source database.

Defines | Functions | Variables

bgwriter.c File Reference

#include "postgres.h"
#include <signal.h>
#include <sys/time.h>
#include <unistd.h>
#include "access/xlog.h"
#include "access/xlog_internal.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgwriter.h"
#include "storage/bufmgr.h"
#include "storage/buf_internals.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/shmem.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/resowner.h"
Include dependency graph for bgwriter.c:

Go to the source code of this file.




static void bg_quickdie (SIGNAL_ARGS)
static void BgSigHupHandler (SIGNAL_ARGS)
static void ReqShutdownHandler (SIGNAL_ARGS)
static void bgwriter_sigusr1_handler (SIGNAL_ARGS)
void BackgroundWriterMain (void)


int BgWriterDelay = 200
static volatile sig_atomic_t got_SIGHUP = false
static volatile sig_atomic_t shutdown_requested = false

Define Documentation


Definition at line 71 of file bgwriter.c.

Referenced by BackgroundWriterMain().

Function Documentation

void BackgroundWriterMain ( void   ) 

Definition at line 94 of file bgwriter.c.

References AbortBufferIO(), ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE, ALLOCSET_DEFAULT_MINSIZE, AllocSetContextCreate(), AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), bg_quickdie(), BgBufferSync(), BgSigHupHandler(), bgwriter_sigusr1_handler(), BgWriterDelay, BlockSig, CurrentResourceOwner, elog, EmitErrorReport(), error_context_stack, ExitOnAnyError, FATAL, FirstCallSinceLastCheckpoint(), FlushErrorState(), got_SIGHUP, HIBERNATE_FACTOR, HOLD_INTERRUPTS, LWLockReleaseAll(), MemoryContextResetAndDeleteChildren(), MemoryContextSwitchTo(), MyProc, NULL, PG_exception_stack, PG_SETMASK, pg_usleep(), PGC_SIGHUP, pgstat_send_bgwriter(), pqsignal(), proc_exit(), ProcessConfigFile(), PGPROC::procLatch, ReqShutdownHandler(), ResetLatch(), RESOURCE_RELEASE_BEFORE_LOCKS, ResourceOwnerCreate(), ResourceOwnerRelease(), RESUME_INTERRUPTS, shutdown_requested, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGCONT, sigdelset, SIGHUP, sigjmp_buf, SIGPIPE, SIGQUIT, sigsetjmp, SIGTTIN, SIGTTOU, SIGUSR1, SIGUSR2, SIGWINCH, smgrcloseall(), StrategyNotifyBgWriter(), TopMemoryContext, UnBlockSig, UnlockBuffers(), WaitLatch(), WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_TIMEOUT.

Referenced by AuxiliaryProcessMain().

    sigjmp_buf  local_sigjmp_buf;
    MemoryContext bgwriter_context;
    bool        prev_hibernate;

     * If possible, make this process a group leader, so that the postmaster
     * can signal any child processes too.  (bgwriter probably never has any
     * child processes, but for consistency we make all postmaster child
     * processes do this.)
    if (setsid() < 0)
        elog(FATAL, "setsid() failed: %m");

     * Properly accept or ignore signals the postmaster might send us.
     * bgwriter doesn't participate in ProcSignal signalling, but a SIGUSR1
     * handler is still needed for latch wakeups.
    pqsignal(SIGHUP, BgSigHupHandler);  /* set flag to read config file */
    pqsignal(SIGINT, SIG_IGN);
    pqsignal(SIGTERM, ReqShutdownHandler);      /* shutdown */
    pqsignal(SIGQUIT, bg_quickdie);     /* hard crash time */
    pqsignal(SIGALRM, SIG_IGN);
    pqsignal(SIGPIPE, SIG_IGN);
    pqsignal(SIGUSR1, bgwriter_sigusr1_handler);
    pqsignal(SIGUSR2, SIG_IGN);

     * Reset some signals that are accepted by postmaster but not here
    pqsignal(SIGCHLD, SIG_DFL);
    pqsignal(SIGTTIN, SIG_DFL);
    pqsignal(SIGTTOU, SIG_DFL);
    pqsignal(SIGCONT, SIG_DFL);
    pqsignal(SIGWINCH, SIG_DFL);

    /* We allow SIGQUIT (quickdie) at all times */
    sigdelset(&BlockSig, SIGQUIT);

     * Create a resource owner to keep track of our resources (currently only
     * buffer pins).
    CurrentResourceOwner = ResourceOwnerCreate(NULL, "Background Writer");

     * Create a memory context that we will do all our work in.  We do this so
     * that we can reset the context during error recovery and thereby avoid
     * possible memory leaks.  Formerly this code just ran in
     * TopMemoryContext, but resetting that would be a really bad idea.
    bgwriter_context = AllocSetContextCreate(TopMemoryContext,
                                             "Background Writer",

     * If an exception is encountered, processing resumes here.
     * See notes in postgres.c about the design of this coding.
    if (sigsetjmp(local_sigjmp_buf, 1) != 0)
        /* Since not using PG_TRY, must reset error stack by hand */
        error_context_stack = NULL;

        /* Prevent interrupts while cleaning up */

        /* Report the error to the server log */

         * These operations are really just a minimal subset of
         * AbortTransaction().  We don't have very many resources to worry
         * about in bgwriter, but we do have LWLocks, buffers, and temp files.
        /* buffer pins are released here: */
                             false, true);
        /* we needn't bother with the other ResourceOwnerRelease phases */

         * Now return to normal top-level context and clear ErrorContext for
         * next time.

        /* Flush any leaked data in the top-level context */

        /* Now we can allow interrupts again */

         * Sleep at least 1 second after any error.  A write error is likely
         * to be repeated, and we don't want to be filling the error logs as
         * fast as we can.

         * Close all open files after any error.  This is helpful on Windows,
         * where holding deleted files open causes various strange errors.
         * It's not clear we need it elsewhere, but shouldn't hurt.

    /* We can now handle ereport(ERROR) */
    PG_exception_stack = &local_sigjmp_buf;

     * Unblock signals (they were blocked when the postmaster forked us)

     * Reset hibernation state after any error.
    prev_hibernate = false;

     * Loop forever
    for (;;)
        bool        can_hibernate;
        int         rc;

        /* Clear any already-pending wakeups */

        if (got_SIGHUP)
            got_SIGHUP = false;
        if (shutdown_requested)
             * From here on, elog(ERROR) should end with exit(1), not send
             * control back to the sigsetjmp block above
            ExitOnAnyError = true;
            /* Normal exit from the bgwriter is here */
            proc_exit(0);       /* done */

         * Do one cycle of dirty-buffer writing.
        can_hibernate = BgBufferSync();

         * Send off activity statistics to the stats collector

        if (FirstCallSinceLastCheckpoint())
             * After any checkpoint, close all smgr files.  This is so we
             * won't hang onto smgr references to deleted files indefinitely.

         * Sleep until we are signaled or BgWriterDelay has elapsed.
         * Note: the feedback control loop in BgBufferSync() expects that we
         * will call it every BgWriterDelay msec.  While it's not critical for
         * correctness that that be exact, the feedback loop might misbehave
         * if we stray too far from that.  Hence, avoid loading this process
         * down with latch events that are likely to happen frequently during
         * normal operation.
        rc = WaitLatch(&MyProc->procLatch,
                       BgWriterDelay /* ms */ );

         * If no latch event and BgBufferSync says nothing's happening, extend
         * the sleep in "hibernation" mode, where we sleep for much longer
         * than bgwriter_delay says.  Fewer wakeups save electricity.  When a
         * backend starts using buffers again, it will wake us up by setting
         * our latch.  Because the extra sleep will persist only as long as no
         * buffer allocations happen, this should not distort the behavior of
         * BgBufferSync's control loop too badly; essentially, it will think
         * that the system-wide idle interval didn't exist.
         * There is a race condition here, in that a backend might allocate a
         * buffer between the time BgBufferSync saw the alloc count as zero
         * and the time we call StrategyNotifyBgWriter.  While it's not
         * critical that we not hibernate anyway, we try to reduce the odds of
         * that by only hibernating when BgBufferSync says nothing's happening
         * for two consecutive cycles.  Also, we mitigate any possible
         * consequences of a missed wakeup by not hibernating forever.
        if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
            /* Ask for notification at next buffer allocation */
            /* Sleep ... */
            rc = WaitLatch(&MyProc->procLatch,
                           WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
                           BgWriterDelay * HIBERNATE_FACTOR);
            /* Reset the notification request in case we timed out */

         * Emergency bailout if postmaster has died.  This is to avoid the
         * necessity for manual cleanup of all postmaster children.
        if (rc & WL_POSTMASTER_DEATH)

        prev_hibernate = can_hibernate;

static void bg_quickdie ( SIGNAL_ARGS   )  [static]

Definition at line 346 of file bgwriter.c.

References BlockSig, on_exit_reset(), and PG_SETMASK.

Referenced by BackgroundWriterMain().


     * We DO NOT want to run proc_exit() callbacks -- we're here because
     * shared memory may be corrupted, so we don't want to try to clean up our
     * transaction.  Just nail the windows shut and get out of town.  Now that
     * there's an atexit callback to prevent third-party code from breaking
     * things by calling exit() directly, we have to reset the callbacks
     * explicitly to make this work as intended.

     * Note we do exit(2) not exit(0).  This is to force the postmaster into a
     * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
     * backend.  This is necessary precisely because we don't clean up our
     * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
     * should ensure the postmaster sees this as a crash, too, but no harm in
     * being doubly sure.)

static void BgSigHupHandler ( SIGNAL_ARGS   )  [static]

Definition at line 373 of file bgwriter.c.

References got_SIGHUP, MyProc, PGPROC::procLatch, and SetLatch().

Referenced by BackgroundWriterMain().

    int         save_errno = errno;

    got_SIGHUP = true;
    if (MyProc)

    errno = save_errno;

static void bgwriter_sigusr1_handler ( SIGNAL_ARGS   )  [static]

Definition at line 399 of file bgwriter.c.

References latch_sigusr1_handler().

Referenced by BackgroundWriterMain().

    int         save_errno = errno;


    errno = save_errno;

static void ReqShutdownHandler ( SIGNAL_ARGS   )  [static]

Definition at line 386 of file bgwriter.c.

References MyProc, PGPROC::procLatch, SetLatch(), and shutdown_requested.

Referenced by BackgroundWriterMain().

    int         save_errno = errno;

    shutdown_requested = true;
    if (MyProc)

    errno = save_errno;

Variable Documentation

int BgWriterDelay = 200

Definition at line 65 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

volatile sig_atomic_t got_SIGHUP = false [static]

Definition at line 76 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgSigHupHandler().

volatile sig_atomic_t shutdown_requested = false [static]

Definition at line 77 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and ReqShutdownHandler().