LCOV - code coverage report
Current view: top level - src/backend/postmaster - walwriter.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 35 52 67.3 %
Date: 2024-11-21 08:14:44 Functions: 1 1 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * walwriter.c
       4             :  *
       5             :  * The WAL writer background process is new as of Postgres 8.3.  It attempts
       6             :  * to keep regular backends from having to write out (and fsync) WAL pages.
       7             :  * Also, it guarantees that transaction commit records that weren't synced
       8             :  * to disk immediately upon commit (ie, were "asynchronously committed")
       9             :  * will reach disk within a knowable time --- which, as it happens, is at
      10             :  * most three times the wal_writer_delay cycle time.
      11             :  *
      12             :  * Note that as with the bgwriter for shared buffers, regular backends are
      13             :  * still empowered to issue WAL writes and fsyncs when the walwriter doesn't
      14             :  * keep up. This means that the WALWriter is not an essential process and
      15             :  * can shutdown quickly when requested.
      16             :  *
      17             :  * Because the walwriter's cycle is directly linked to the maximum delay
      18             :  * before async-commit transactions are guaranteed committed, it's probably
      19             :  * unwise to load additional functionality onto it.  For instance, if you've
      20             :  * got a yen to create xlog segments further in advance, that'd be better done
      21             :  * in bgwriter than in walwriter.
      22             :  *
      23             :  * The walwriter is started by the postmaster as soon as the startup subprocess
      24             :  * finishes.  It remains alive until the postmaster commands it to terminate.
      25             :  * Normal termination is by SIGTERM, which instructs the walwriter to exit(0).
      26             :  * Emergency termination is by SIGQUIT; like any backend, the walwriter will
      27             :  * simply abort and exit on SIGQUIT.
      28             :  *
      29             :  * If the walwriter exits unexpectedly, the postmaster treats that the same
      30             :  * as a backend crash: shared memory may be corrupted, so remaining backends
      31             :  * should be killed by SIGQUIT and then a recovery cycle started.
      32             :  *
      33             :  *
      34             :  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
      35             :  *
      36             :  *
      37             :  * IDENTIFICATION
      38             :  *    src/backend/postmaster/walwriter.c
      39             :  *
      40             :  *-------------------------------------------------------------------------
      41             :  */
      42             : #include "postgres.h"
      43             : 
      44             : #include <signal.h>
      45             : #include <unistd.h>
      46             : 
      47             : #include "access/xlog.h"
      48             : #include "libpq/pqsignal.h"
      49             : #include "miscadmin.h"
      50             : #include "pgstat.h"
      51             : #include "postmaster/auxprocess.h"
      52             : #include "postmaster/interrupt.h"
      53             : #include "postmaster/walwriter.h"
      54             : #include "storage/bufmgr.h"
      55             : #include "storage/condition_variable.h"
      56             : #include "storage/fd.h"
      57             : #include "storage/lwlock.h"
      58             : #include "storage/proc.h"
      59             : #include "storage/procsignal.h"
      60             : #include "storage/smgr.h"
      61             : #include "utils/hsearch.h"
      62             : #include "utils/memutils.h"
      63             : #include "utils/resowner.h"
      64             : 
      65             : 
      66             : /*
      67             :  * GUC parameters
      68             :  */
      69             : int         WalWriterDelay = 200;
      70             : int         WalWriterFlushAfter = DEFAULT_WAL_WRITER_FLUSH_AFTER;
      71             : 
      72             : /*
      73             :  * Number of do-nothing loops before lengthening the delay time, and the
      74             :  * multiplier to apply to WalWriterDelay when we do decide to hibernate.
      75             :  * (Perhaps these need to be configurable?)
      76             :  */
      77             : #define LOOPS_UNTIL_HIBERNATE       50
      78             : #define HIBERNATE_FACTOR            25
      79             : 
      80             : /*
      81             :  * Main entry point for walwriter process
      82             :  *
      83             :  * This is invoked from AuxiliaryProcessMain, which has already created the
      84             :  * basic execution environment, but not enabled signals yet.
      85             :  */
      86             : void
      87         794 : WalWriterMain(char *startup_data, size_t startup_data_len)
      88             : {
      89             :     sigjmp_buf  local_sigjmp_buf;
      90             :     MemoryContext walwriter_context;
      91             :     int         left_till_hibernate;
      92             :     bool        hibernating;
      93             : 
      94             :     Assert(startup_data_len == 0);
      95             : 
      96         794 :     MyBackendType = B_WAL_WRITER;
      97         794 :     AuxiliaryProcessMainCommon();
      98             : 
      99             :     /*
     100             :      * Properly accept or ignore signals the postmaster might send us
     101             :      *
     102             :      * We have no particular use for SIGINT at the moment, but seems
     103             :      * reasonable to treat like SIGTERM.
     104             :      */
     105         794 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
     106         794 :     pqsignal(SIGINT, SignalHandlerForShutdownRequest);
     107         794 :     pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
     108             :     /* SIGQUIT handler was already set up by InitPostmasterChild */
     109         794 :     pqsignal(SIGALRM, SIG_IGN);
     110         794 :     pqsignal(SIGPIPE, SIG_IGN);
     111         794 :     pqsignal(SIGUSR1, procsignal_sigusr1_handler);
     112         794 :     pqsignal(SIGUSR2, SIG_IGN); /* not used */
     113             : 
     114             :     /*
     115             :      * Reset some signals that are accepted by postmaster but not here
     116             :      */
     117         794 :     pqsignal(SIGCHLD, SIG_DFL);
     118             : 
     119             :     /*
     120             :      * Create a memory context that we will do all our work in.  We do this so
     121             :      * that we can reset the context during error recovery and thereby avoid
     122             :      * possible memory leaks.  Formerly this code just ran in
     123             :      * TopMemoryContext, but resetting that would be a really bad idea.
     124             :      */
     125         794 :     walwriter_context = AllocSetContextCreate(TopMemoryContext,
     126             :                                               "Wal Writer",
     127             :                                               ALLOCSET_DEFAULT_SIZES);
     128         794 :     MemoryContextSwitchTo(walwriter_context);
     129             : 
     130             :     /*
     131             :      * If an exception is encountered, processing resumes here.
     132             :      *
     133             :      * You might wonder why this isn't coded as an infinite loop around a
     134             :      * PG_TRY construct.  The reason is that this is the bottom of the
     135             :      * exception stack, and so with PG_TRY there would be no exception handler
     136             :      * in force at all during the CATCH part.  By leaving the outermost setjmp
     137             :      * always active, we have at least some chance of recovering from an error
     138             :      * during error recovery.  (If we get into an infinite loop thereby, it
     139             :      * will soon be stopped by overflow of elog.c's internal state stack.)
     140             :      *
     141             :      * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
     142             :      * (to wit, BlockSig) will be restored when longjmp'ing to here.  Thus,
     143             :      * signals other than SIGQUIT will be blocked until we complete error
     144             :      * recovery.  It might seem that this policy makes the HOLD_INTERRUPTS()
     145             :      * call redundant, but it is not since InterruptPending might be set
     146             :      * already.
     147             :      */
     148         794 :     if (sigsetjmp(local_sigjmp_buf, 1) != 0)
     149             :     {
     150             :         /* Since not using PG_TRY, must reset error stack by hand */
     151           0 :         error_context_stack = NULL;
     152             : 
     153             :         /* Prevent interrupts while cleaning up */
     154           0 :         HOLD_INTERRUPTS();
     155             : 
     156             :         /* Report the error to the server log */
     157           0 :         EmitErrorReport();
     158             : 
     159             :         /*
     160             :          * These operations are really just a minimal subset of
     161             :          * AbortTransaction().  We don't have very many resources to worry
     162             :          * about in walwriter, but we do have LWLocks, and perhaps buffers?
     163             :          */
     164           0 :         LWLockReleaseAll();
     165           0 :         ConditionVariableCancelSleep();
     166           0 :         pgstat_report_wait_end();
     167           0 :         UnlockBuffers();
     168           0 :         ReleaseAuxProcessResources(false);
     169           0 :         AtEOXact_Buffers(false);
     170           0 :         AtEOXact_SMgr();
     171           0 :         AtEOXact_Files(false);
     172           0 :         AtEOXact_HashTables(false);
     173             : 
     174             :         /*
     175             :          * Now return to normal top-level context and clear ErrorContext for
     176             :          * next time.
     177             :          */
     178           0 :         MemoryContextSwitchTo(walwriter_context);
     179           0 :         FlushErrorState();
     180             : 
     181             :         /* Flush any leaked data in the top-level context */
     182           0 :         MemoryContextReset(walwriter_context);
     183             : 
     184             :         /* Now we can allow interrupts again */
     185           0 :         RESUME_INTERRUPTS();
     186             : 
     187             :         /*
     188             :          * Sleep at least 1 second after any error.  A write error is likely
     189             :          * to be repeated, and we don't want to be filling the error logs as
     190             :          * fast as we can.
     191             :          */
     192           0 :         pg_usleep(1000000L);
     193             :     }
     194             : 
     195             :     /* We can now handle ereport(ERROR) */
     196         794 :     PG_exception_stack = &local_sigjmp_buf;
     197             : 
     198             :     /*
     199             :      * Unblock signals (they were blocked when the postmaster forked us)
     200             :      */
     201         794 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
     202             : 
     203             :     /*
     204             :      * Reset hibernation state after any error.
     205             :      */
     206         794 :     left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
     207         794 :     hibernating = false;
     208         794 :     SetWalWriterSleeping(false);
     209             : 
     210             :     /*
     211             :      * Advertise our proc number that backends can use to wake us up while
     212             :      * we're sleeping.
     213             :      */
     214         794 :     ProcGlobal->walwriterProc = MyProcNumber;
     215             : 
     216             :     /*
     217             :      * Loop forever
     218             :      */
     219             :     for (;;)
     220       18042 :     {
     221             :         long        cur_timeout;
     222             : 
     223             :         /*
     224             :          * Advertise whether we might hibernate in this cycle.  We do this
     225             :          * before resetting the latch to ensure that any async commits will
     226             :          * see the flag set if they might possibly need to wake us up, and
     227             :          * that we won't miss any signal they send us.  (If we discover work
     228             :          * to do in the last cycle before we would hibernate, the global flag
     229             :          * will be set unnecessarily, but little harm is done.)  But avoid
     230             :          * touching the global flag if it doesn't need to change.
     231             :          */
     232       18836 :         if (hibernating != (left_till_hibernate <= 1))
     233             :         {
     234          20 :             hibernating = (left_till_hibernate <= 1);
     235          20 :             SetWalWriterSleeping(hibernating);
     236             :         }
     237             : 
     238             :         /* Clear any already-pending wakeups */
     239       18836 :         ResetLatch(MyLatch);
     240             : 
     241             :         /* Process any signals received recently */
     242       18836 :         HandleMainLoopInterrupts();
     243             : 
     244             :         /*
     245             :          * Do what we're here for; then, if XLogBackgroundFlush() found useful
     246             :          * work to do, reset hibernation counter.
     247             :          */
     248       18048 :         if (XLogBackgroundFlush())
     249        7040 :             left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
     250       11008 :         else if (left_till_hibernate > 0)
     251       10994 :             left_till_hibernate--;
     252             : 
     253             :         /* report pending statistics to the cumulative stats system */
     254       18048 :         pgstat_report_wal(false);
     255             : 
     256             :         /*
     257             :          * Sleep until we are signaled or WalWriterDelay has elapsed.  If we
     258             :          * haven't done anything useful for quite some time, lengthen the
     259             :          * sleep time so as to reduce the server's idle power consumption.
     260             :          */
     261       18048 :         if (left_till_hibernate > 0)
     262       18022 :             cur_timeout = WalWriterDelay;   /* in ms */
     263             :         else
     264          26 :             cur_timeout = WalWriterDelay * HIBERNATE_FACTOR;
     265             : 
     266       18048 :         (void) WaitLatch(MyLatch,
     267             :                          WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     268             :                          cur_timeout,
     269             :                          WAIT_EVENT_WAL_WRITER_MAIN);
     270             :     }
     271             : }

Generated by: LCOV version 1.14