LCOV - code coverage report
Current view: top level - src/backend/postmaster - bgwriter.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 68.3 % 60 41
Test Date: 2026-03-14 01:15:54 Functions: 100.0 % 1 1
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * bgwriter.c
       4              :  *
       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.
      12              :  *
      13              :  * As of Postgres 9.2 the bgwriter no longer handles checkpoints.
      14              :  *
      15              :  * Normal termination is by SIGTERM, which instructs the bgwriter to exit(0).
      16              :  * Emergency termination is by SIGQUIT; like any backend, the bgwriter will
      17              :  * simply abort and exit on SIGQUIT.
      18              :  *
      19              :  * If the bgwriter exits unexpectedly, the postmaster treats that the same
      20              :  * as a backend crash: shared memory may be corrupted, so remaining backends
      21              :  * should be killed by SIGQUIT and then a recovery cycle started.
      22              :  *
      23              :  *
      24              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      25              :  *
      26              :  *
      27              :  * IDENTIFICATION
      28              :  *    src/backend/postmaster/bgwriter.c
      29              :  *
      30              :  *-------------------------------------------------------------------------
      31              :  */
      32              : #include "postgres.h"
      33              : 
      34              : #include "access/xlog.h"
      35              : #include "libpq/pqsignal.h"
      36              : #include "miscadmin.h"
      37              : #include "pgstat.h"
      38              : #include "postmaster/auxprocess.h"
      39              : #include "postmaster/bgwriter.h"
      40              : #include "postmaster/interrupt.h"
      41              : #include "storage/aio_subsys.h"
      42              : #include "storage/buf_internals.h"
      43              : #include "storage/bufmgr.h"
      44              : #include "storage/condition_variable.h"
      45              : #include "storage/fd.h"
      46              : #include "storage/lwlock.h"
      47              : #include "storage/proc.h"
      48              : #include "storage/procsignal.h"
      49              : #include "storage/smgr.h"
      50              : #include "storage/standby.h"
      51              : #include "utils/memutils.h"
      52              : #include "utils/resowner.h"
      53              : #include "utils/timestamp.h"
      54              : #include "utils/wait_event.h"
      55              : 
      56              : /*
      57              :  * GUC parameters
      58              :  */
      59              : int         BgWriterDelay = 200;
      60              : 
      61              : /*
      62              :  * Multiplier to apply to BgWriterDelay when we decide to hibernate.
      63              :  * (Perhaps this needs to be configurable?)
      64              :  */
      65              : #define HIBERNATE_FACTOR            50
      66              : 
      67              : /*
      68              :  * Interval in which standby snapshots are logged into the WAL stream, in
      69              :  * milliseconds.
      70              :  */
      71              : #define LOG_SNAPSHOT_INTERVAL_MS 15000
      72              : 
      73              : /*
      74              :  * LSN and timestamp at which we last issued a LogStandbySnapshot(), to avoid
      75              :  * doing so too often or repeatedly if there has been no other write activity
      76              :  * in the system.
      77              :  */
      78              : static TimestampTz last_snapshot_ts;
      79              : static XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr;
      80              : 
      81              : 
      82              : /*
      83              :  * Main entry point for bgwriter process
      84              :  *
      85              :  * This is invoked from AuxiliaryProcessMain, which has already created the
      86              :  * basic execution environment, but not enabled signals yet.
      87              :  */
      88              : void
      89          587 : BackgroundWriterMain(const void *startup_data, size_t startup_data_len)
      90              : {
      91              :     sigjmp_buf  local_sigjmp_buf;
      92              :     MemoryContext bgwriter_context;
      93              :     bool        prev_hibernate;
      94              :     WritebackContext wb_context;
      95              : 
      96              :     Assert(startup_data_len == 0);
      97              : 
      98          587 :     AuxiliaryProcessMainCommon();
      99              : 
     100              :     /*
     101              :      * Properly accept or ignore signals that might be sent to us.
     102              :      */
     103          587 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
     104          587 :     pqsignal(SIGINT, SIG_IGN);
     105          587 :     pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
     106              :     /* SIGQUIT handler was already set up by InitPostmasterChild */
     107          587 :     pqsignal(SIGALRM, SIG_IGN);
     108          587 :     pqsignal(SIGPIPE, SIG_IGN);
     109          587 :     pqsignal(SIGUSR1, procsignal_sigusr1_handler);
     110          587 :     pqsignal(SIGUSR2, SIG_IGN);
     111              : 
     112              :     /*
     113              :      * Reset some signals that are accepted by postmaster but not here
     114              :      */
     115          587 :     pqsignal(SIGCHLD, SIG_DFL);
     116              : 
     117              :     /*
     118              :      * We just started, assume there has been either a shutdown or
     119              :      * end-of-recovery snapshot.
     120              :      */
     121          587 :     last_snapshot_ts = GetCurrentTimestamp();
     122              : 
     123              :     /*
     124              :      * Create a memory context that we will do all our work in.  We do this so
     125              :      * that we can reset the context during error recovery and thereby avoid
     126              :      * possible memory leaks.  Formerly this code just ran in
     127              :      * TopMemoryContext, but resetting that would be a really bad idea.
     128              :      */
     129          587 :     bgwriter_context = AllocSetContextCreate(TopMemoryContext,
     130              :                                              "Background Writer",
     131              :                                              ALLOCSET_DEFAULT_SIZES);
     132          587 :     MemoryContextSwitchTo(bgwriter_context);
     133              : 
     134          587 :     WritebackContextInit(&wb_context, &bgwriter_flush_after);
     135              : 
     136              :     /*
     137              :      * If an exception is encountered, processing resumes here.
     138              :      *
     139              :      * You might wonder why this isn't coded as an infinite loop around a
     140              :      * PG_TRY construct.  The reason is that this is the bottom of the
     141              :      * exception stack, and so with PG_TRY there would be no exception handler
     142              :      * in force at all during the CATCH part.  By leaving the outermost setjmp
     143              :      * always active, we have at least some chance of recovering from an error
     144              :      * during error recovery.  (If we get into an infinite loop thereby, it
     145              :      * will soon be stopped by overflow of elog.c's internal state stack.)
     146              :      *
     147              :      * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
     148              :      * (to wit, BlockSig) will be restored when longjmp'ing to here.  Thus,
     149              :      * signals other than SIGQUIT will be blocked until we complete error
     150              :      * recovery.  It might seem that this policy makes the HOLD_INTERRUPTS()
     151              :      * call redundant, but it is not since InterruptPending might be set
     152              :      * already.
     153              :      */
     154          587 :     if (sigsetjmp(local_sigjmp_buf, 1) != 0)
     155              :     {
     156              :         /* Since not using PG_TRY, must reset error stack by hand */
     157            0 :         error_context_stack = NULL;
     158              : 
     159              :         /* Prevent interrupts while cleaning up */
     160            0 :         HOLD_INTERRUPTS();
     161              : 
     162              :         /* Report the error to the server log */
     163            0 :         EmitErrorReport();
     164              : 
     165              :         /*
     166              :          * These operations are really just a minimal subset of
     167              :          * AbortTransaction().  We don't have very many resources to worry
     168              :          * about in bgwriter, but we do have LWLocks, buffers, and temp files.
     169              :          */
     170            0 :         LWLockReleaseAll();
     171            0 :         ConditionVariableCancelSleep();
     172            0 :         pgaio_error_cleanup();
     173            0 :         UnlockBuffers();
     174            0 :         ReleaseAuxProcessResources(false);
     175            0 :         AtEOXact_Buffers(false);
     176            0 :         AtEOXact_SMgr();
     177            0 :         AtEOXact_Files(false);
     178            0 :         AtEOXact_HashTables(false);
     179              : 
     180              :         /*
     181              :          * Now return to normal top-level context and clear ErrorContext for
     182              :          * next time.
     183              :          */
     184            0 :         MemoryContextSwitchTo(bgwriter_context);
     185            0 :         FlushErrorState();
     186              : 
     187              :         /* Flush any leaked data in the top-level context */
     188            0 :         MemoryContextReset(bgwriter_context);
     189              : 
     190              :         /* re-initialize to avoid repeated errors causing problems */
     191            0 :         WritebackContextInit(&wb_context, &bgwriter_flush_after);
     192              : 
     193              :         /* Now we can allow interrupts again */
     194            0 :         RESUME_INTERRUPTS();
     195              : 
     196              :         /*
     197              :          * Sleep at least 1 second after any error.  A write error is likely
     198              :          * to be repeated, and we don't want to be filling the error logs as
     199              :          * fast as we can.
     200              :          */
     201            0 :         pg_usleep(1000000L);
     202              : 
     203              :         /* Report wait end here, when there is no further possibility of wait */
     204            0 :         pgstat_report_wait_end();
     205              :     }
     206              : 
     207              :     /* We can now handle ereport(ERROR) */
     208          587 :     PG_exception_stack = &local_sigjmp_buf;
     209              : 
     210              :     /*
     211              :      * Unblock signals (they were blocked when the postmaster forked us)
     212              :      */
     213          587 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
     214              : 
     215              :     /*
     216              :      * Reset hibernation state after any error.
     217              :      */
     218          587 :     prev_hibernate = false;
     219              : 
     220              :     /*
     221              :      * Loop forever
     222              :      */
     223              :     for (;;)
     224        13346 :     {
     225              :         bool        can_hibernate;
     226              :         int         rc;
     227              : 
     228              :         /* Clear any already-pending wakeups */
     229        13933 :         ResetLatch(MyLatch);
     230              : 
     231        13933 :         ProcessMainLoopInterrupts();
     232              : 
     233              :         /*
     234              :          * Do one cycle of dirty-buffer writing.
     235              :          */
     236        13353 :         can_hibernate = BgBufferSync(&wb_context);
     237              : 
     238              :         /* Report pending statistics to the cumulative stats system */
     239        13353 :         pgstat_report_bgwriter();
     240        13353 :         pgstat_report_wal(true);
     241              : 
     242        13353 :         if (FirstCallSinceLastCheckpoint())
     243              :         {
     244              :             /*
     245              :              * After any checkpoint, free all smgr objects.  Otherwise we
     246              :              * would never do so for dropped relations, as the bgwriter does
     247              :              * not process shared invalidation messages or call
     248              :              * AtEOXact_SMgr().
     249              :              */
     250          663 :             smgrdestroyall();
     251              :         }
     252              : 
     253              :         /*
     254              :          * Log a new xl_running_xacts every now and then so replication can
     255              :          * get into a consistent state faster (think of suboverflowed
     256              :          * snapshots) and clean up resources (locks, KnownXids*) more
     257              :          * frequently. The costs of this are relatively low, so doing it 4
     258              :          * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
     259              :          *
     260              :          * We assume the interval for writing xl_running_xacts is
     261              :          * significantly bigger than BgWriterDelay, so we don't complicate the
     262              :          * overall timeout handling but just assume we're going to get called
     263              :          * often enough even if hibernation mode is active. It's not that
     264              :          * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
     265              :          * sure we're not waking the disk up unnecessarily on an idle system
     266              :          * we check whether there has been any WAL inserted since the last
     267              :          * time we've logged a running xacts.
     268              :          *
     269              :          * We do this logging in the bgwriter as it is the only process that
     270              :          * is run regularly and returns to its mainloop all the time. E.g.
     271              :          * Checkpointer, when active, is barely ever in its mainloop and thus
     272              :          * makes it hard to log regularly.
     273              :          */
     274        13353 :         if (XLogStandbyInfoActive() && !RecoveryInProgress())
     275              :         {
     276         6304 :             TimestampTz timeout = 0;
     277         6304 :             TimestampTz now = GetCurrentTimestamp();
     278              : 
     279         6304 :             timeout = TimestampTzPlusMilliseconds(last_snapshot_ts,
     280              :                                                   LOG_SNAPSHOT_INTERVAL_MS);
     281              : 
     282              :             /*
     283              :              * Only log if enough time has passed and interesting records have
     284              :              * been inserted since the last snapshot.  Have to compare with <=
     285              :              * instead of < because GetLastImportantRecPtr() points at the
     286              :              * start of a record, whereas last_snapshot_lsn points just past
     287              :              * the end of the record.
     288              :              */
     289         6304 :             if (now >= timeout &&
     290           44 :                 last_snapshot_lsn <= GetLastImportantRecPtr())
     291              :             {
     292           44 :                 last_snapshot_lsn = LogStandbySnapshot();
     293           44 :                 last_snapshot_ts = now;
     294              :             }
     295              :         }
     296              : 
     297              :         /*
     298              :          * Sleep until we are signaled or BgWriterDelay has elapsed.
     299              :          *
     300              :          * Note: the feedback control loop in BgBufferSync() expects that we
     301              :          * will call it every BgWriterDelay msec.  While it's not critical for
     302              :          * correctness that that be exact, the feedback loop might misbehave
     303              :          * if we stray too far from that.  Hence, avoid loading this process
     304              :          * down with latch events that are likely to happen frequently during
     305              :          * normal operation.
     306              :          */
     307        13353 :         rc = WaitLatch(MyLatch,
     308              :                        WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     309              :                        BgWriterDelay /* ms */ , WAIT_EVENT_BGWRITER_MAIN);
     310              : 
     311              :         /*
     312              :          * If no latch event and BgBufferSync says nothing's happening, extend
     313              :          * the sleep in "hibernation" mode, where we sleep for much longer
     314              :          * than bgwriter_delay says.  Fewer wakeups save electricity.  When a
     315              :          * backend starts using buffers again, it will wake us up by setting
     316              :          * our latch.  Because the extra sleep will persist only as long as no
     317              :          * buffer allocations happen, this should not distort the behavior of
     318              :          * BgBufferSync's control loop too badly; essentially, it will think
     319              :          * that the system-wide idle interval didn't exist.
     320              :          *
     321              :          * There is a race condition here, in that a backend might allocate a
     322              :          * buffer between the time BgBufferSync saw the alloc count as zero
     323              :          * and the time we call StrategyNotifyBgWriter.  While it's not
     324              :          * critical that we not hibernate anyway, we try to reduce the odds of
     325              :          * that by only hibernating when BgBufferSync says nothing's happening
     326              :          * for two consecutive cycles.  Also, we mitigate any possible
     327              :          * consequences of a missed wakeup by not hibernating forever.
     328              :          */
     329        13346 :         if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
     330              :         {
     331              :             /* Ask for notification at next buffer allocation */
     332          456 :             StrategyNotifyBgWriter(MyProcNumber);
     333              :             /* Sleep ... */
     334          456 :             (void) WaitLatch(MyLatch,
     335              :                              WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     336          456 :                              BgWriterDelay * HIBERNATE_FACTOR,
     337              :                              WAIT_EVENT_BGWRITER_HIBERNATE);
     338              :             /* Reset the notification request in case we timed out */
     339          456 :             StrategyNotifyBgWriter(-1);
     340              :         }
     341              : 
     342        13346 :         prev_hibernate = can_hibernate;
     343              :     }
     344              : }
        

Generated by: LCOV version 2.0-1