]> granicus.if.org Git - postgresql/blob - src/backend/postmaster/bgwriter.c
ed1a7b2f2712aa24eef74bfda48ad93596beee86
[postgresql] / src / backend / postmaster / bgwriter.c
1 /*-------------------------------------------------------------------------
2  *
3  * bgwriter.c
4  *
5  * The background writer (bgwriter) is new in 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  * 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.)
20  *
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.
27  *
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.)
34  *
35  *
36  * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
37  *
38  *
39  * IDENTIFICATION
40  *        $PostgreSQL: pgsql/src/backend/postmaster/bgwriter.c,v 1.20 2005/09/12 22:20:16 tgl Exp $
41  *
42  *-------------------------------------------------------------------------
43  */
44 #include "postgres.h"
45
46 #include <signal.h>
47 #include <time.h>
48
49 #include "access/xlog.h"
50 #include "libpq/pqsignal.h"
51 #include "miscadmin.h"
52 #include "postmaster/bgwriter.h"
53 #include "storage/bufmgr.h"
54 #include "storage/freespace.h"
55 #include "storage/ipc.h"
56 #include "storage/pmsignal.h"
57 #include "storage/smgr.h"
58 #include "tcop/tcopprot.h"
59 #include "utils/guc.h"
60 #include "utils/memutils.h"
61
62
63 /*----------
64  * Shared memory area for communication between bgwriter and backends
65  *
66  * The ckpt counters allow backends to watch for completion of a checkpoint
67  * request they send.  Here's how it works:
68  *      * At start of a checkpoint, bgwriter increments ckpt_started.
69  *      * On completion of a checkpoint, bgwriter sets ckpt_done to
70  *        equal ckpt_started.
71  *      * On failure of a checkpoint, bgwrite first increments ckpt_failed,
72  *        then sets ckpt_done to equal ckpt_started.
73  * All three fields are declared sig_atomic_t to ensure they can be read
74  * and written without explicit locking.  The algorithm for backends is:
75  *      1. Record current values of ckpt_failed and ckpt_started (in that
76  *         order!).
77  *      2. Send signal to request checkpoint.
78  *      3. Sleep until ckpt_started changes.  Now you know a checkpoint has
79  *         begun since you started this algorithm (although *not* that it was
80  *         specifically initiated by your signal).
81  *      4. Record new value of ckpt_started.
82  *      5. Sleep until ckpt_done >= saved value of ckpt_started.  (Use modulo
83  *         arithmetic here in case counters wrap around.)  Now you know a
84  *         checkpoint has started and completed, but not whether it was
85  *         successful.
86  *      6. If ckpt_failed is different from the originally saved value,
87  *         assume request failed; otherwise it was definitely successful.
88  *
89  * An additional field is ckpt_time_warn; this is also sig_atomic_t for
90  * simplicity, but is only used as a boolean.  If a backend is requesting
91  * a checkpoint for which a checkpoints-too-close-together warning is
92  * reasonable, it should set this field TRUE just before sending the signal.
93  *
94  * The requests array holds fsync requests sent by backends and not yet
95  * absorbed by the bgwriter.  Unlike the checkpoint fields, the requests
96  * fields are protected by BgWriterCommLock.
97  *----------
98  */
99 typedef struct
100 {
101         RelFileNode rnode;
102         BlockNumber segno;
103         /* might add a request-type field later */
104 } BgWriterRequest;
105
106 typedef struct
107 {
108         pid_t           bgwriter_pid;   /* PID of bgwriter (0 if not started) */
109
110         sig_atomic_t ckpt_started;      /* advances when checkpoint starts */
111         sig_atomic_t ckpt_done;         /* advances when checkpoint done */
112         sig_atomic_t ckpt_failed;       /* advances when checkpoint fails */
113
114         sig_atomic_t ckpt_time_warn;    /* warn if too soon since last ckpt? */
115
116         int                     num_requests;   /* current # of requests */
117         int                     max_requests;   /* allocated array size */
118         BgWriterRequest requests[1];    /* VARIABLE LENGTH ARRAY */
119 } BgWriterShmemStruct;
120
121 static BgWriterShmemStruct *BgWriterShmem;
122
123 /*
124  * GUC parameters
125  */
126 int                     BgWriterDelay = 200;
127 int                     CheckPointTimeout = 300;
128 int                     CheckPointWarning = 30;
129
130 /*
131  * Flags set by interrupt handlers for later service in the main loop.
132  */
133 static volatile sig_atomic_t got_SIGHUP = false;
134 static volatile sig_atomic_t checkpoint_requested = false;
135 static volatile sig_atomic_t shutdown_requested = false;
136
137 /*
138  * Private state
139  */
140 static bool am_bg_writer = false;
141
142 static bool ckpt_active = false;
143
144 static time_t last_checkpoint_time;
145
146
147 static void bg_quickdie(SIGNAL_ARGS);
148 static void BgSigHupHandler(SIGNAL_ARGS);
149 static void ReqCheckpointHandler(SIGNAL_ARGS);
150 static void ReqShutdownHandler(SIGNAL_ARGS);
151
152
153 /*
154  * Main entry point for bgwriter process
155  *
156  * This is invoked from BootstrapMain, which has already created the basic
157  * execution environment, but not enabled signals yet.
158  */
159 void
160 BackgroundWriterMain(void)
161 {
162         sigjmp_buf      local_sigjmp_buf;
163         MemoryContext bgwriter_context;
164
165         Assert(BgWriterShmem != NULL);
166         BgWriterShmem->bgwriter_pid = MyProcPid;
167         am_bg_writer = true;
168
169         /*
170          * Properly accept or ignore signals the postmaster might send us
171          *
172          * Note: we deliberately ignore SIGTERM, because during a standard Unix
173          * system shutdown cycle, init will SIGTERM all processes at once.      We
174          * want to wait for the backends to exit, whereupon the postmaster
175          * will tell us it's okay to shut down (via SIGUSR2).
176          *
177          * SIGUSR1 is presently unused; keep it spare in case someday we want
178          * this process to participate in sinval messaging.
179          */
180         pqsignal(SIGHUP, BgSigHupHandler);      /* set flag to read config file */
181         pqsignal(SIGINT, ReqCheckpointHandler);         /* request checkpoint */
182         pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
183         pqsignal(SIGQUIT, bg_quickdie);         /* hard crash time */
184         pqsignal(SIGALRM, SIG_IGN);
185         pqsignal(SIGPIPE, SIG_IGN);
186         pqsignal(SIGUSR1, SIG_IGN); /* reserve for sinval */
187         pqsignal(SIGUSR2, ReqShutdownHandler);          /* request shutdown */
188
189         /*
190          * Reset some signals that are accepted by postmaster but not here
191          */
192         pqsignal(SIGCHLD, SIG_DFL);
193         pqsignal(SIGTTIN, SIG_DFL);
194         pqsignal(SIGTTOU, SIG_DFL);
195         pqsignal(SIGCONT, SIG_DFL);
196         pqsignal(SIGWINCH, SIG_DFL);
197
198         /* We allow SIGQUIT (quickdie) at all times */
199 #ifdef HAVE_SIGPROCMASK
200         sigdelset(&BlockSig, SIGQUIT);
201 #else
202         BlockSig &= ~(sigmask(SIGQUIT));
203 #endif
204
205         /*
206          * Initialize so that first time-driven checkpoint happens at the
207          * correct time.
208          */
209         last_checkpoint_time = time(NULL);
210
211         /*
212          * Create a memory context that we will do all our work in.  We do this
213          * so that we can reset the context during error recovery and thereby
214          * avoid possible memory leaks.  Formerly this code just ran in
215          * TopMemoryContext, but resetting that would be a really bad idea.
216          */
217         bgwriter_context = AllocSetContextCreate(TopMemoryContext,
218                                                                                          "Background Writer",
219                                                                                          ALLOCSET_DEFAULT_MINSIZE,
220                                                                                          ALLOCSET_DEFAULT_INITSIZE,
221                                                                                          ALLOCSET_DEFAULT_MAXSIZE);
222         MemoryContextSwitchTo(bgwriter_context);
223
224         /*
225          * If an exception is encountered, processing resumes here.
226          *
227          * See notes in postgres.c about the design of this coding.
228          */
229         if (sigsetjmp(local_sigjmp_buf, 1) != 0)
230         {
231                 /* Since not using PG_TRY, must reset error stack by hand */
232                 error_context_stack = NULL;
233
234                 /* Prevent interrupts while cleaning up */
235                 HOLD_INTERRUPTS();
236
237                 /* Report the error to the server log */
238                 EmitErrorReport();
239
240                 /*
241                  * These operations are really just a minimal subset of
242                  * AbortTransaction().  We don't have very many resources to worry
243                  * about in bgwriter, but we do have LWLocks and buffers.
244                  */
245                 LWLockReleaseAll();
246                 AbortBufferIO();
247                 UnlockBuffers();
248
249                 /* Warn any waiting backends that the checkpoint failed. */
250                 if (ckpt_active)
251                 {
252                         /* use volatile pointer to prevent code rearrangement */
253                         volatile BgWriterShmemStruct *bgs = BgWriterShmem;
254
255                         bgs->ckpt_failed++;
256                         bgs->ckpt_done = bgs->ckpt_started;
257                         ckpt_active = false;
258                 }
259
260                 /*
261                  * Now return to normal top-level context and clear ErrorContext
262                  * for next time.
263                  */
264                 MemoryContextSwitchTo(bgwriter_context);
265                 FlushErrorState();
266
267                 /* Flush any leaked data in the top-level context */
268                 MemoryContextResetAndDeleteChildren(bgwriter_context);
269
270                 /* Now we can allow interrupts again */
271                 RESUME_INTERRUPTS();
272
273                 /*
274                  * Sleep at least 1 second after any error.  A write error is
275                  * likely to be repeated, and we don't want to be filling the
276                  * error logs as fast as we can.
277                  */
278                 pg_usleep(1000000L);
279         }
280
281         /* We can now handle ereport(ERROR) */
282         PG_exception_stack = &local_sigjmp_buf;
283
284         /*
285          * Unblock signals (they were blocked when the postmaster forked us)
286          */
287         PG_SETMASK(&UnBlockSig);
288
289         /*
290          * Loop forever
291          */
292         for (;;)
293         {
294                 bool            do_checkpoint = false;
295                 bool            force_checkpoint = false;
296                 time_t          now;
297                 int                     elapsed_secs;
298                 long            udelay;
299
300                 /*
301                  * Emergency bailout if postmaster has died.  This is to avoid the
302                  * necessity for manual cleanup of all postmaster children.
303                  */
304                 if (!PostmasterIsAlive(true))
305                         exit(1);
306
307                 /*
308                  * Process any requests or signals received recently.
309                  */
310                 AbsorbFsyncRequests();
311
312                 if (got_SIGHUP)
313                 {
314                         got_SIGHUP = false;
315                         ProcessConfigFile(PGC_SIGHUP);
316                 }
317                 if (checkpoint_requested)
318                 {
319                         checkpoint_requested = false;
320                         do_checkpoint = true;
321                         force_checkpoint = true;
322                 }
323                 if (shutdown_requested)
324                 {
325                         ShutdownXLOG(0, 0);
326                         DumpFreeSpaceMap(0, 0);
327                         /* Normal exit from the bgwriter is here */
328                         proc_exit(0);           /* done */
329                 }
330
331                 /*
332                  * Do an unforced checkpoint if too much time has elapsed since
333                  * the last one.
334                  */
335                 now = time(NULL);
336                 elapsed_secs = now - last_checkpoint_time;
337                 if (elapsed_secs >= CheckPointTimeout)
338                         do_checkpoint = true;
339
340                 /*
341                  * Do a checkpoint if requested, otherwise do one cycle of
342                  * dirty-buffer writing.
343                  */
344                 if (do_checkpoint)
345                 {
346                         /*
347                          * We will warn if (a) too soon since last checkpoint (whatever
348                          * caused it) and (b) somebody has set the ckpt_time_warn flag
349                          * since the last checkpoint start.  Note in particular that
350                          * this implementation will not generate warnings caused by
351                          * CheckPointTimeout < CheckPointWarning.
352                          */
353                         if (BgWriterShmem->ckpt_time_warn &&
354                                 elapsed_secs < CheckPointWarning)
355                                 ereport(LOG,
356                                                 (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
357                                                                 elapsed_secs),
358                                                  errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
359                         BgWriterShmem->ckpt_time_warn = false;
360
361                         /*
362                          * Indicate checkpoint start to any waiting backends.
363                          */
364                         ckpt_active = true;
365                         BgWriterShmem->ckpt_started++;
366
367                         CreateCheckPoint(false, force_checkpoint);
368
369                         /*
370                          * After any checkpoint, close all smgr files.  This is so we
371                          * won't hang onto smgr references to deleted files
372                          * indefinitely.
373                          */
374                         smgrcloseall();
375
376                         /*
377                          * Indicate checkpoint completion to any waiting backends.
378                          */
379                         BgWriterShmem->ckpt_done = BgWriterShmem->ckpt_started;
380                         ckpt_active = false;
381
382                         /*
383                          * Note we record the checkpoint start time not end time as
384                          * last_checkpoint_time.  This is so that time-driven
385                          * checkpoints happen at a predictable spacing.
386                          */
387                         last_checkpoint_time = now;
388                 }
389                 else
390                         BgBufferSync();
391
392                 /*
393                  * Nap for the configured time, or sleep for 10 seconds if there
394                  * is no bgwriter activity configured.
395                  *
396                  * On some platforms, signals won't interrupt the sleep.  To ensure
397                  * we respond reasonably promptly when someone signals us, break
398                  * down the sleep into 1-second increments, and check for
399                  * interrupts after each nap.
400                  *
401                  * We absorb pending requests after each short sleep.
402                  */
403                 if ((bgwriter_all_percent > 0.0 && bgwriter_all_maxpages > 0) ||
404                         (bgwriter_lru_percent > 0.0 && bgwriter_lru_maxpages > 0))
405                         udelay = BgWriterDelay * 1000L;
406                 else
407                         udelay = 10000000L;
408                 while (udelay > 1000000L)
409                 {
410                         if (got_SIGHUP || checkpoint_requested || shutdown_requested)
411                                 break;
412                         pg_usleep(1000000L);
413                         AbsorbFsyncRequests();
414                         udelay -= 1000000L;
415                 }
416                 if (!(got_SIGHUP || checkpoint_requested || shutdown_requested))
417                         pg_usleep(udelay);
418         }
419 }
420
421
422 /* --------------------------------
423  *              signal handler routines
424  * --------------------------------
425  */
426
427 /*
428  * bg_quickdie() occurs when signalled SIGQUIT by the postmaster.
429  *
430  * Some backend has bought the farm,
431  * so we need to stop what we're doing and exit.
432  */
433 static void
434 bg_quickdie(SIGNAL_ARGS)
435 {
436         PG_SETMASK(&BlockSig);
437
438         /*
439          * DO NOT proc_exit() -- we're here because shared memory may be
440          * corrupted, so we don't want to try to clean up our transaction.
441          * Just nail the windows shut and get out of town.
442          *
443          * Note we do exit(1) not exit(0).      This is to force the postmaster into
444          * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
445          * random backend.      This is necessary precisely because we don't clean
446          * up our shared memory state.
447          */
448         exit(1);
449 }
450
451 /* SIGHUP: set flag to re-read config file at next convenient time */
452 static void
453 BgSigHupHandler(SIGNAL_ARGS)
454 {
455         got_SIGHUP = true;
456 }
457
458 /* SIGINT: set flag to run a normal checkpoint right away */
459 static void
460 ReqCheckpointHandler(SIGNAL_ARGS)
461 {
462         checkpoint_requested = true;
463 }
464
465 /* SIGUSR2: set flag to run a shutdown checkpoint and exit */
466 static void
467 ReqShutdownHandler(SIGNAL_ARGS)
468 {
469         shutdown_requested = true;
470 }
471
472
473 /* --------------------------------
474  *              communication with backends
475  * --------------------------------
476  */
477
478 /*
479  * BgWriterShmemSize
480  *              Compute space needed for bgwriter-related shared memory
481  */
482 Size
483 BgWriterShmemSize(void)
484 {
485         Size            size;
486
487         /*
488          * Currently, the size of the requests[] array is arbitrarily set
489          * equal to NBuffers.  This may prove too large or small ...
490          */
491         size = offsetof(BgWriterShmemStruct, requests);
492         size = add_size(size, mul_size(NBuffers, sizeof(BgWriterRequest)));
493
494         return size;
495 }
496
497 /*
498  * BgWriterShmemInit
499  *              Allocate and initialize bgwriter-related shared memory
500  */
501 void
502 BgWriterShmemInit(void)
503 {
504         bool            found;
505
506         BgWriterShmem = (BgWriterShmemStruct *)
507                 ShmemInitStruct("Background Writer Data",
508                                                 BgWriterShmemSize(),
509                                                 &found);
510         if (BgWriterShmem == NULL)
511                 ereport(FATAL,
512                                 (errcode(ERRCODE_OUT_OF_MEMORY),
513                                  errmsg("not enough shared memory for background writer")));
514         if (found)
515                 return;                                 /* already initialized */
516
517         MemSet(BgWriterShmem, 0, sizeof(BgWriterShmemStruct));
518         BgWriterShmem->max_requests = NBuffers;
519 }
520
521 /*
522  * RequestCheckpoint
523  *              Called in backend processes to request an immediate checkpoint
524  *
525  * If waitforit is true, wait until the checkpoint is completed
526  * before returning; otherwise, just signal the request and return
527  * immediately.
528  *
529  * If warnontime is true, and it's "too soon" since the last checkpoint,
530  * the bgwriter will log a warning.  This should be true only for checkpoints
531  * caused due to xlog filling, else the warning will be misleading.
532  */
533 void
534 RequestCheckpoint(bool waitforit, bool warnontime)
535 {
536         /* use volatile pointer to prevent code rearrangement */
537         volatile BgWriterShmemStruct *bgs = BgWriterShmem;
538         sig_atomic_t old_failed = bgs->ckpt_failed;
539         sig_atomic_t old_started = bgs->ckpt_started;
540
541         /*
542          * If in a standalone backend, just do it ourselves.
543          */
544         if (!IsPostmasterEnvironment)
545         {
546                 CreateCheckPoint(false, true);
547
548                 /*
549                  * After any checkpoint, close all smgr files.  This is so we
550                  * won't hang onto smgr references to deleted files
551                  * indefinitely.
552                  */
553                 smgrcloseall();
554
555                 return;
556         }
557
558         /* Set warning request flag if appropriate */
559         if (warnontime)
560                 bgs->ckpt_time_warn = true;
561
562         /*
563          * Send signal to request checkpoint.  When waitforit is false, we
564          * consider failure to send the signal to be nonfatal.
565          */
566         if (BgWriterShmem->bgwriter_pid == 0)
567                 elog(waitforit ? ERROR : LOG,
568                          "could not request checkpoint because bgwriter not running");
569         if (kill(BgWriterShmem->bgwriter_pid, SIGINT) != 0)
570                 elog(waitforit ? ERROR : LOG,
571                          "could not signal for checkpoint: %m");
572
573         /*
574          * If requested, wait for completion.  We detect completion according
575          * to the algorithm given above.
576          */
577         if (waitforit)
578         {
579                 while (bgs->ckpt_started == old_started)
580                 {
581                         CHECK_FOR_INTERRUPTS();
582                         pg_usleep(100000L);
583                 }
584                 old_started = bgs->ckpt_started;
585
586                 /*
587                  * We are waiting for ckpt_done >= old_started, in a modulo sense.
588                  * This is a little tricky since we don't know the width or
589                  * signedness of sig_atomic_t.  We make the lowest common
590                  * denominator assumption that it is only as wide as "char".  This
591                  * means that this algorithm will cope correctly as long as we
592                  * don't sleep for more than 127 completed checkpoints.  (If we
593                  * do, we will get another chance to exit after 128 more
594                  * checkpoints...)
595                  */
596                 while (((signed char) (bgs->ckpt_done - old_started)) < 0)
597                 {
598                         CHECK_FOR_INTERRUPTS();
599                         pg_usleep(100000L);
600                 }
601                 if (bgs->ckpt_failed != old_failed)
602                         ereport(ERROR,
603                                         (errmsg("checkpoint request failed"),
604                                          errhint("Consult the server log for details.")));
605         }
606 }
607
608 /*
609  * ForwardFsyncRequest
610  *              Forward a file-fsync request from a backend to the bgwriter
611  *
612  * Whenever a backend is compelled to write directly to a relation
613  * (which should be seldom, if the bgwriter is getting its job done),
614  * the backend calls this routine to pass over knowledge that the relation
615  * is dirty and must be fsync'd before next checkpoint.
616  *
617  * If we are unable to pass over the request (at present, this can happen
618  * if the shared memory queue is full), we return false.  That forces
619  * the backend to do its own fsync.  We hope that will be even more seldom.
620  *
621  * Note: we presently make no attempt to eliminate duplicate requests
622  * in the requests[] queue.  The bgwriter will have to eliminate dups
623  * internally anyway, so we may as well avoid holding the lock longer
624  * than we have to here.
625  */
626 bool
627 ForwardFsyncRequest(RelFileNode rnode, BlockNumber segno)
628 {
629         BgWriterRequest *request;
630
631         if (!IsUnderPostmaster)
632                 return false;                   /* probably shouldn't even get here */
633         Assert(BgWriterShmem != NULL);
634
635         LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
636         if (BgWriterShmem->bgwriter_pid == 0 ||
637                 BgWriterShmem->num_requests >= BgWriterShmem->max_requests)
638         {
639                 LWLockRelease(BgWriterCommLock);
640                 return false;
641         }
642         request = &BgWriterShmem->requests[BgWriterShmem->num_requests++];
643         request->rnode = rnode;
644         request->segno = segno;
645         LWLockRelease(BgWriterCommLock);
646         return true;
647 }
648
649 /*
650  * AbsorbFsyncRequests
651  *              Retrieve queued fsync requests and pass them to local smgr.
652  *
653  * This is exported because it must be called during CreateCheckPoint;
654  * we have to be sure we have accepted all pending requests *after* we
655  * establish the checkpoint REDO pointer.  Since CreateCheckPoint
656  * sometimes runs in non-bgwriter processes, do nothing if not bgwriter.
657  */
658 void
659 AbsorbFsyncRequests(void)
660 {
661         BgWriterRequest *requests = NULL;
662         BgWriterRequest *request;
663         int                     n;
664
665         if (!am_bg_writer)
666                 return;
667
668         /*
669          * We have to PANIC if we fail to absorb all the pending requests
670          * (eg, because our hashtable runs out of memory).  This is because
671          * the system cannot run safely if we are unable to fsync what we
672          * have been told to fsync.  Fortunately, the hashtable is so small
673          * that the problem is quite unlikely to arise in practice.
674          */
675         START_CRIT_SECTION();
676
677         /*
678          * We try to avoid holding the lock for a long time by copying the
679          * request array.
680          */
681         LWLockAcquire(BgWriterCommLock, LW_EXCLUSIVE);
682
683         n = BgWriterShmem->num_requests;
684         if (n > 0)
685         {
686                 requests = (BgWriterRequest *) palloc(n * sizeof(BgWriterRequest));
687                 memcpy(requests, BgWriterShmem->requests, n * sizeof(BgWriterRequest));
688         }
689         BgWriterShmem->num_requests = 0;
690
691         LWLockRelease(BgWriterCommLock);
692
693         for (request = requests; n > 0; request++, n--)
694                 RememberFsyncRequest(request->rnode, request->segno);
695
696         if (requests)
697                 pfree(requests);
698
699         END_CRIT_SECTION();
700 }