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