PostgreSQL Source Code  git master
autoprewarm.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * autoprewarm.c
4  * Periodically dump information about the blocks present in
5  * shared_buffers, and reload them on server restart.
6  *
7  * Due to locking considerations, we can't actually begin prewarming
8  * until the server reaches a consistent state. We need the catalogs
9  * to be consistent so that we can figure out which relation to lock,
10  * and we need to lock the relations so that we don't try to prewarm
11  * pages from a relation that is in the process of being dropped.
12  *
13  * While prewarming, autoprewarm will use two workers. There's a
14  * leader worker that reads and sorts the list of blocks to be
15  * prewarmed and then launches a per-database worker for each
16  * relevant database in turn. The former keeps running after the
17  * initial prewarm is complete to update the dump file periodically.
18  *
19  * Copyright (c) 2016-2024, PostgreSQL Global Development Group
20  *
21  * IDENTIFICATION
22  * contrib/pg_prewarm/autoprewarm.c
23  *
24  *-------------------------------------------------------------------------
25  */
26 
27 #include "postgres.h"
28 
29 #include <unistd.h>
30 
31 #include "access/relation.h"
32 #include "access/xact.h"
33 #include "catalog/pg_class.h"
34 #include "catalog/pg_type.h"
35 #include "pgstat.h"
36 #include "postmaster/bgworker.h"
37 #include "postmaster/interrupt.h"
38 #include "storage/buf_internals.h"
39 #include "storage/dsm.h"
40 #include "storage/dsm_registry.h"
41 #include "storage/fd.h"
42 #include "storage/ipc.h"
43 #include "storage/latch.h"
44 #include "storage/lwlock.h"
45 #include "storage/proc.h"
46 #include "storage/procsignal.h"
47 #include "storage/shmem.h"
48 #include "storage/smgr.h"
49 #include "tcop/tcopprot.h"
50 #include "utils/acl.h"
51 #include "utils/datetime.h"
52 #include "utils/guc.h"
53 #include "utils/memutils.h"
54 #include "utils/rel.h"
55 #include "utils/relfilenumbermap.h"
56 #include "utils/resowner.h"
57 
58 #define AUTOPREWARM_FILE "autoprewarm.blocks"
59 
60 /* Metadata for each block we dump. */
61 typedef struct BlockInfoRecord
62 {
69 
70 /* Shared state information for autoprewarm bgworker. */
71 typedef struct AutoPrewarmSharedState
72 {
73  LWLock lock; /* mutual exclusion */
74  pid_t bgworker_pid; /* for main bgworker */
75  pid_t pid_using_dumpfile; /* for autoprewarm or block dump */
76 
77  /* Following items are for communication with per-database worker */
84 
85 PGDLLEXPORT void autoprewarm_main(Datum main_arg);
87 
90 
91 static void apw_load_buffers(void);
92 static int apw_dump_now(bool is_bgworker, bool dump_unlogged);
93 static void apw_start_leader_worker(void);
94 static void apw_start_database_worker(void);
95 static bool apw_init_shmem(void);
96 static void apw_detach_shmem(int code, Datum arg);
97 static int apw_compare_blockinfo(const void *p, const void *q);
98 
99 /* Pointer to shared-memory state. */
101 
102 /* GUC variables. */
103 static bool autoprewarm = true; /* start worker? */
104 static int autoprewarm_interval = 300; /* dump interval */
105 
106 /*
107  * Module load callback.
108  */
109 void
110 _PG_init(void)
111 {
112  DefineCustomIntVariable("pg_prewarm.autoprewarm_interval",
113  "Sets the interval between dumps of shared buffers",
114  "If set to zero, time-based dumping is disabled.",
116  300,
117  0, INT_MAX / 1000,
118  PGC_SIGHUP,
119  GUC_UNIT_S,
120  NULL,
121  NULL,
122  NULL);
123 
125  return;
126 
127  /* can't define PGC_POSTMASTER variable after startup */
128  DefineCustomBoolVariable("pg_prewarm.autoprewarm",
129  "Starts the autoprewarm worker.",
130  NULL,
131  &autoprewarm,
132  true,
134  0,
135  NULL,
136  NULL,
137  NULL);
138 
139  MarkGUCPrefixReserved("pg_prewarm");
140 
141  /* Register autoprewarm worker, if enabled. */
142  if (autoprewarm)
144 }
145 
146 /*
147  * Main entry point for the leader autoprewarm process. Per-database workers
148  * have a separate entry point.
149  */
150 void
152 {
153  bool first_time = true;
154  bool final_dump_allowed = true;
155  TimestampTz last_dump_time = 0;
156 
157  /* Establish signal handlers; once that's done, unblock signals. */
162 
163  /* Create (if necessary) and attach to our shared memory area. */
164  if (apw_init_shmem())
165  first_time = false;
166 
167  /*
168  * Set on-detach hook so that our PID will be cleared on exit.
169  *
170  * NB: Autoprewarm's state is stored in a DSM segment, and DSM segments
171  * are detached before calling the on_shmem_exit callbacks, so we must put
172  * apw_detach_shmem in the before_shmem_exit callback list.
173  */
175 
176  /*
177  * Store our PID in the shared memory area --- unless there's already
178  * another worker running, in which case just exit.
179  */
182  {
184  ereport(LOG,
185  (errmsg("autoprewarm worker is already running under PID %d",
186  (int) apw_state->bgworker_pid)));
187  return;
188  }
191 
192  /*
193  * Preload buffers from the dump file only if we just created the shared
194  * memory region. Otherwise, it's either already been done or shouldn't
195  * be done - e.g. because the old dump file has been overwritten since the
196  * server was started.
197  *
198  * There's not much point in performing a dump immediately after we finish
199  * preloading; so, if we do end up preloading, consider the last dump time
200  * to be equal to the current time.
201  *
202  * If apw_load_buffers() is terminated early by a shutdown request,
203  * prevent dumping out our state below the loop, because we'd effectively
204  * just truncate the saved state to however much we'd managed to preload.
205  */
206  if (first_time)
207  {
209  final_dump_allowed = !ShutdownRequestPending;
210  last_dump_time = GetCurrentTimestamp();
211  }
212 
213  /* Periodically dump buffers until terminated. */
214  while (!ShutdownRequestPending)
215  {
216  /* In case of a SIGHUP, just reload the configuration. */
218  {
219  ConfigReloadPending = false;
221  }
222 
223  if (autoprewarm_interval <= 0)
224  {
225  /* We're only dumping at shutdown, so just wait forever. */
226  (void) WaitLatch(MyLatch,
228  -1L,
230  }
231  else
232  {
233  TimestampTz next_dump_time;
234  long delay_in_ms;
235 
236  /* Compute the next dump time. */
237  next_dump_time =
238  TimestampTzPlusMilliseconds(last_dump_time,
239  autoprewarm_interval * 1000);
240  delay_in_ms =
242  next_dump_time);
243 
244  /* Perform a dump if it's time. */
245  if (delay_in_ms <= 0)
246  {
247  last_dump_time = GetCurrentTimestamp();
248  apw_dump_now(true, false);
249  continue;
250  }
251 
252  /* Sleep until the next dump time. */
253  (void) WaitLatch(MyLatch,
255  delay_in_ms,
257  }
258 
259  /* Reset the latch, loop. */
261  }
262 
263  /*
264  * Dump one last time. We assume this is probably the result of a system
265  * shutdown, although it's possible that we've merely been terminated.
266  */
267  if (final_dump_allowed)
268  apw_dump_now(true, true);
269 }
270 
271 /*
272  * Read the dump file and launch per-database workers one at a time to
273  * prewarm the buffers found there.
274  */
275 static void
277 {
278  FILE *file = NULL;
279  int num_elements,
280  i;
281  BlockInfoRecord *blkinfo;
282  dsm_segment *seg;
283 
284  /*
285  * Skip the prewarm if the dump file is in use; otherwise, prevent any
286  * other process from writing it while we're using it.
287  */
291  else
292  {
294  ereport(LOG,
295  (errmsg("skipping prewarm because block dump file is being written by PID %d",
296  (int) apw_state->pid_using_dumpfile)));
297  return;
298  }
300 
301  /*
302  * Open the block dump file. Exit quietly if it doesn't exist, but report
303  * any other error.
304  */
305  file = AllocateFile(AUTOPREWARM_FILE, "r");
306  if (!file)
307  {
308  if (errno == ENOENT)
309  {
313  return; /* No file to load. */
314  }
315  ereport(ERROR,
317  errmsg("could not read file \"%s\": %m",
318  AUTOPREWARM_FILE)));
319  }
320 
321  /* First line of the file is a record count. */
322  if (fscanf(file, "<<%d>>\n", &num_elements) != 1)
323  ereport(ERROR,
325  errmsg("could not read from file \"%s\": %m",
326  AUTOPREWARM_FILE)));
327 
328  /* Allocate a dynamic shared memory segment to store the record data. */
329  seg = dsm_create(sizeof(BlockInfoRecord) * num_elements, 0);
330  blkinfo = (BlockInfoRecord *) dsm_segment_address(seg);
331 
332  /* Read records, one per line. */
333  for (i = 0; i < num_elements; i++)
334  {
335  unsigned forknum;
336 
337  if (fscanf(file, "%u,%u,%u,%u,%u\n", &blkinfo[i].database,
338  &blkinfo[i].tablespace, &blkinfo[i].filenumber,
339  &forknum, &blkinfo[i].blocknum) != 5)
340  ereport(ERROR,
341  (errmsg("autoprewarm block dump file is corrupted at line %d",
342  i + 1)));
343  blkinfo[i].forknum = forknum;
344  }
345 
346  FreeFile(file);
347 
348  /* Sort the blocks to be loaded. */
349  qsort(blkinfo, num_elements, sizeof(BlockInfoRecord),
351 
352  /* Populate shared memory state. */
356 
357  /* Get the info position of the first block of the next database. */
358  while (apw_state->prewarm_start_idx < num_elements)
359  {
361  Oid current_db = blkinfo[j].database;
362 
363  /*
364  * Advance the prewarm_stop_idx to the first BlockInfoRecord that does
365  * not belong to this database.
366  */
367  j++;
368  while (j < num_elements)
369  {
370  if (current_db != blkinfo[j].database)
371  {
372  /*
373  * Combine BlockInfoRecords for global objects with those of
374  * the database.
375  */
376  if (current_db != InvalidOid)
377  break;
378  current_db = blkinfo[j].database;
379  }
380 
381  j++;
382  }
383 
384  /*
385  * If we reach this point with current_db == InvalidOid, then only
386  * BlockInfoRecords belonging to global objects exist. We can't
387  * prewarm without a database connection, so just bail out.
388  */
389  if (current_db == InvalidOid)
390  break;
391 
392  /* Configure stop point and database for next per-database worker. */
394  apw_state->database = current_db;
396 
397  /* If we've run out of free buffers, don't launch another worker. */
398  if (!have_free_buffer())
399  break;
400 
401  /*
402  * Likewise, don't launch if we've already been told to shut down.
403  * (The launch would fail anyway, but we might as well skip it.)
404  */
406  break;
407 
408  /*
409  * Start a per-database worker to load blocks for this database; this
410  * function will return once the per-database worker exits.
411  */
413 
414  /* Prepare for next database. */
416  }
417 
418  /* Clean up. */
419  dsm_detach(seg);
424 
425  /* Report our success, if we were able to finish. */
427  ereport(LOG,
428  (errmsg("autoprewarm successfully prewarmed %d of %d previously-loaded blocks",
429  apw_state->prewarmed_blocks, num_elements)));
430 }
431 
432 /*
433  * Prewarm all blocks for one database (and possibly also global objects, if
434  * those got grouped with this database).
435  */
436 void
438 {
439  int pos;
440  BlockInfoRecord *block_info;
441  Relation rel = NULL;
442  BlockNumber nblocks = 0;
443  BlockInfoRecord *old_blk = NULL;
444  dsm_segment *seg;
445 
446  /* Establish signal handlers; once that's done, unblock signals. */
447  pqsignal(SIGTERM, die);
449 
450  /* Connect to correct database and get block information. */
451  apw_init_shmem();
453  if (seg == NULL)
454  ereport(ERROR,
455  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
456  errmsg("could not map dynamic shared memory segment")));
458  block_info = (BlockInfoRecord *) dsm_segment_address(seg);
460 
461  /*
462  * Loop until we run out of blocks to prewarm or until we run out of free
463  * buffers.
464  */
465  while (pos < apw_state->prewarm_stop_idx && have_free_buffer())
466  {
467  BlockInfoRecord *blk = &block_info[pos++];
468  Buffer buf;
469 
471 
472  /*
473  * Quit if we've reached records for another database. If previous
474  * blocks are of some global objects, then continue pre-warming.
475  */
476  if (old_blk != NULL && old_blk->database != blk->database &&
477  old_blk->database != 0)
478  break;
479 
480  /*
481  * As soon as we encounter a block of a new relation, close the old
482  * relation. Note that rel will be NULL if try_relation_open failed
483  * previously; in that case, there is nothing to close.
484  */
485  if (old_blk != NULL && old_blk->filenumber != blk->filenumber &&
486  rel != NULL)
487  {
489  rel = NULL;
491  }
492 
493  /*
494  * Try to open each new relation, but only once, when we first
495  * encounter it. If it's been dropped, skip the associated blocks.
496  */
497  if (old_blk == NULL || old_blk->filenumber != blk->filenumber)
498  {
499  Oid reloid;
500 
501  Assert(rel == NULL);
503  reloid = RelidByRelfilenumber(blk->tablespace, blk->filenumber);
504  if (OidIsValid(reloid))
505  rel = try_relation_open(reloid, AccessShareLock);
506 
507  if (!rel)
509  }
510  if (!rel)
511  {
512  old_blk = blk;
513  continue;
514  }
515 
516  /* Once per fork, check for fork existence and size. */
517  if (old_blk == NULL ||
518  old_blk->filenumber != blk->filenumber ||
519  old_blk->forknum != blk->forknum)
520  {
521  /*
522  * smgrexists is not safe for illegal forknum, hence check whether
523  * the passed forknum is valid before using it in smgrexists.
524  */
525  if (blk->forknum > InvalidForkNumber &&
526  blk->forknum <= MAX_FORKNUM &&
527  smgrexists(RelationGetSmgr(rel), blk->forknum))
528  nblocks = RelationGetNumberOfBlocksInFork(rel, blk->forknum);
529  else
530  nblocks = 0;
531  }
532 
533  /* Check whether blocknum is valid and within fork file size. */
534  if (blk->blocknum >= nblocks)
535  {
536  /* Move to next forknum. */
537  old_blk = blk;
538  continue;
539  }
540 
541  /* Prewarm buffer. */
542  buf = ReadBufferExtended(rel, blk->forknum, blk->blocknum, RBM_NORMAL,
543  NULL);
544  if (BufferIsValid(buf))
545  {
548  }
549 
550  old_blk = blk;
551  }
552 
553  dsm_detach(seg);
554 
555  /* Release lock on previous relation. */
556  if (rel)
557  {
560  }
561 }
562 
563 /*
564  * Dump information on blocks in shared buffers. We use a text format here
565  * so that it's easy to understand and even change the file contents if
566  * necessary.
567  * Returns the number of blocks dumped.
568  */
569 static int
570 apw_dump_now(bool is_bgworker, bool dump_unlogged)
571 {
572  int num_blocks;
573  int i;
574  int ret;
575  BlockInfoRecord *block_info_array;
576  BufferDesc *bufHdr;
577  FILE *file;
578  char transient_dump_file_path[MAXPGPATH];
579  pid_t pid;
580 
586 
587  if (pid != InvalidPid)
588  {
589  if (!is_bgworker)
590  ereport(ERROR,
591  (errmsg("could not perform block dump because dump file is being used by PID %d",
592  (int) apw_state->pid_using_dumpfile)));
593 
594  ereport(LOG,
595  (errmsg("skipping block dump because it is already being performed by PID %d",
596  (int) apw_state->pid_using_dumpfile)));
597  return 0;
598  }
599 
600  block_info_array =
602 
603  for (num_blocks = 0, i = 0; i < NBuffers; i++)
604  {
605  uint32 buf_state;
606 
608 
609  bufHdr = GetBufferDescriptor(i);
610 
611  /* Lock each buffer header before inspecting. */
612  buf_state = LockBufHdr(bufHdr);
613 
614  /*
615  * Unlogged tables will be automatically truncated after a crash or
616  * unclean shutdown. In such cases we need not prewarm them. Dump them
617  * only if requested by caller.
618  */
619  if (buf_state & BM_TAG_VALID &&
620  ((buf_state & BM_PERMANENT) || dump_unlogged))
621  {
622  block_info_array[num_blocks].database = bufHdr->tag.dbOid;
623  block_info_array[num_blocks].tablespace = bufHdr->tag.spcOid;
624  block_info_array[num_blocks].filenumber =
625  BufTagGetRelNumber(&bufHdr->tag);
626  block_info_array[num_blocks].forknum =
627  BufTagGetForkNum(&bufHdr->tag);
628  block_info_array[num_blocks].blocknum = bufHdr->tag.blockNum;
629  ++num_blocks;
630  }
631 
632  UnlockBufHdr(bufHdr, buf_state);
633  }
634 
635  snprintf(transient_dump_file_path, MAXPGPATH, "%s.tmp", AUTOPREWARM_FILE);
636  file = AllocateFile(transient_dump_file_path, "w");
637  if (!file)
638  ereport(ERROR,
640  errmsg("could not open file \"%s\": %m",
641  transient_dump_file_path)));
642 
643  ret = fprintf(file, "<<%d>>\n", num_blocks);
644  if (ret < 0)
645  {
646  int save_errno = errno;
647 
648  FreeFile(file);
649  unlink(transient_dump_file_path);
650  errno = save_errno;
651  ereport(ERROR,
653  errmsg("could not write to file \"%s\": %m",
654  transient_dump_file_path)));
655  }
656 
657  for (i = 0; i < num_blocks; i++)
658  {
660 
661  ret = fprintf(file, "%u,%u,%u,%u,%u\n",
662  block_info_array[i].database,
663  block_info_array[i].tablespace,
664  block_info_array[i].filenumber,
665  (uint32) block_info_array[i].forknum,
666  block_info_array[i].blocknum);
667  if (ret < 0)
668  {
669  int save_errno = errno;
670 
671  FreeFile(file);
672  unlink(transient_dump_file_path);
673  errno = save_errno;
674  ereport(ERROR,
676  errmsg("could not write to file \"%s\": %m",
677  transient_dump_file_path)));
678  }
679  }
680 
681  pfree(block_info_array);
682 
683  /*
684  * Rename transient_dump_file_path to AUTOPREWARM_FILE to make things
685  * permanent.
686  */
687  ret = FreeFile(file);
688  if (ret != 0)
689  {
690  int save_errno = errno;
691 
692  unlink(transient_dump_file_path);
693  errno = save_errno;
694  ereport(ERROR,
696  errmsg("could not close file \"%s\": %m",
697  transient_dump_file_path)));
698  }
699 
700  (void) durable_rename(transient_dump_file_path, AUTOPREWARM_FILE, ERROR);
702 
703  ereport(DEBUG1,
704  (errmsg_internal("wrote block details for %d blocks", num_blocks)));
705  return num_blocks;
706 }
707 
708 /*
709  * SQL-callable function to launch autoprewarm.
710  */
711 Datum
713 {
714  pid_t pid;
715 
716  if (!autoprewarm)
717  ereport(ERROR,
718  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
719  errmsg("autoprewarm is disabled")));
720 
721  apw_init_shmem();
723  pid = apw_state->bgworker_pid;
725 
726  if (pid != InvalidPid)
727  ereport(ERROR,
728  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
729  errmsg("autoprewarm worker is already running under PID %d",
730  (int) pid)));
731 
733 
734  PG_RETURN_VOID();
735 }
736 
737 /*
738  * SQL-callable function to perform an immediate block dump.
739  *
740  * Note: this is declared to return int8, as insurance against some
741  * very distant day when we might make NBuffers wider than int.
742  */
743 Datum
745 {
746  int num_blocks;
747 
748  apw_init_shmem();
749 
751  {
752  num_blocks = apw_dump_now(false, true);
753  }
755 
756  PG_RETURN_INT64((int64) num_blocks);
757 }
758 
759 static void
760 apw_init_state(void *ptr)
761 {
763 
765  state->bgworker_pid = InvalidPid;
766  state->pid_using_dumpfile = InvalidPid;
767 }
768 
769 /*
770  * Allocate and initialize autoprewarm related shared memory, if not already
771  * done, and set up backend-local pointer to that state. Returns true if an
772  * existing shared memory segment was found.
773  */
774 static bool
776 {
777  bool found;
778 
779  apw_state = GetNamedDSMSegment("autoprewarm",
780  sizeof(AutoPrewarmSharedState),
782  &found);
783  LWLockRegisterTranche(apw_state->lock.tranche, "autoprewarm");
784 
785  return found;
786 }
787 
788 /*
789  * Clear our PID from autoprewarm shared state.
790  */
791 static void
793 {
800 }
801 
802 /*
803  * Start autoprewarm leader worker process.
804  */
805 static void
807 {
808  BackgroundWorker worker;
809  BackgroundWorkerHandle *handle;
810  BgwHandleStatus status;
811  pid_t pid;
812 
813  MemSet(&worker, 0, sizeof(BackgroundWorker));
816  strcpy(worker.bgw_library_name, "pg_prewarm");
817  strcpy(worker.bgw_function_name, "autoprewarm_main");
818  strcpy(worker.bgw_name, "autoprewarm leader");
819  strcpy(worker.bgw_type, "autoprewarm leader");
820 
822  {
823  RegisterBackgroundWorker(&worker);
824  return;
825  }
826 
827  /* must set notify PID to wait for startup */
828  worker.bgw_notify_pid = MyProcPid;
829 
830  if (!RegisterDynamicBackgroundWorker(&worker, &handle))
831  ereport(ERROR,
832  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
833  errmsg("could not register background process"),
834  errhint("You may need to increase max_worker_processes.")));
835 
836  status = WaitForBackgroundWorkerStartup(handle, &pid);
837  if (status != BGWH_STARTED)
838  ereport(ERROR,
839  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
840  errmsg("could not start background process"),
841  errhint("More details may be available in the server log.")));
842 }
843 
844 /*
845  * Start autoprewarm per-database worker process.
846  */
847 static void
849 {
850  BackgroundWorker worker;
851  BackgroundWorkerHandle *handle;
852 
853  MemSet(&worker, 0, sizeof(BackgroundWorker));
854  worker.bgw_flags =
858  strcpy(worker.bgw_library_name, "pg_prewarm");
859  strcpy(worker.bgw_function_name, "autoprewarm_database_main");
860  strcpy(worker.bgw_name, "autoprewarm worker");
861  strcpy(worker.bgw_type, "autoprewarm worker");
862 
863  /* must set notify PID to wait for shutdown */
864  worker.bgw_notify_pid = MyProcPid;
865 
866  if (!RegisterDynamicBackgroundWorker(&worker, &handle))
867  ereport(ERROR,
868  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
869  errmsg("registering dynamic bgworker autoprewarm failed"),
870  errhint("Consider increasing configuration parameter max_worker_processes.")));
871 
872  /*
873  * Ignore return value; if it fails, postmaster has died, but we have
874  * checks for that elsewhere.
875  */
877 }
878 
879 /* Compare member elements to check whether they are not equal. */
880 #define cmp_member_elem(fld) \
881 do { \
882  if (a->fld < b->fld) \
883  return -1; \
884  else if (a->fld > b->fld) \
885  return 1; \
886 } while(0)
887 
888 /*
889  * apw_compare_blockinfo
890  *
891  * We depend on all records for a particular database being consecutive
892  * in the dump file; each per-database worker will preload blocks until
893  * it sees a block for some other database. Sorting by tablespace,
894  * filenumber, forknum, and blocknum isn't critical for correctness, but
895  * helps us get a sequential I/O pattern.
896  */
897 static int
898 apw_compare_blockinfo(const void *p, const void *q)
899 {
900  const BlockInfoRecord *a = (const BlockInfoRecord *) p;
901  const BlockInfoRecord *b = (const BlockInfoRecord *) q;
902 
903  cmp_member_elem(database);
905  cmp_member_elem(filenumber);
906  cmp_member_elem(forknum);
907  cmp_member_elem(blocknum);
908 
909  return 0;
910 }
static int apw_compare_blockinfo(const void *p, const void *q)
Definition: autoprewarm.c:898
Datum autoprewarm_start_worker(PG_FUNCTION_ARGS)
Definition: autoprewarm.c:712
static AutoPrewarmSharedState * apw_state
Definition: autoprewarm.c:100
static void apw_detach_shmem(int code, Datum arg)
Definition: autoprewarm.c:792
void _PG_init(void)
Definition: autoprewarm.c:110
PGDLLEXPORT void autoprewarm_main(Datum main_arg)
Definition: autoprewarm.c:151
#define cmp_member_elem(fld)
Definition: autoprewarm.c:880
static bool apw_init_shmem(void)
Definition: autoprewarm.c:775
static bool autoprewarm
Definition: autoprewarm.c:103
#define AUTOPREWARM_FILE
Definition: autoprewarm.c:58
static void apw_start_leader_worker(void)
Definition: autoprewarm.c:806
PGDLLEXPORT void autoprewarm_database_main(Datum main_arg)
Definition: autoprewarm.c:437
static void apw_start_database_worker(void)
Definition: autoprewarm.c:848
static void apw_load_buffers(void)
Definition: autoprewarm.c:276
static void apw_init_state(void *ptr)
Definition: autoprewarm.c:760
Datum autoprewarm_dump_now(PG_FUNCTION_ARGS)
Definition: autoprewarm.c:744
static int autoprewarm_interval
Definition: autoprewarm.c:104
static int apw_dump_now(bool is_bgworker, bool dump_unlogged)
Definition: autoprewarm.c:570
struct AutoPrewarmSharedState AutoPrewarmSharedState
PG_FUNCTION_INFO_V1(autoprewarm_start_worker)
struct BlockInfoRecord BlockInfoRecord
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1766
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:862
BgwHandleStatus WaitForBackgroundWorkerStartup(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1137
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1182
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:970
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_STARTED
Definition: bgworker.h:105
@ BgWorkerStart_ConsistentState
Definition: bgworker.h:80
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:53
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
#define BM_TAG_VALID
Definition: buf_internals.h:63
#define BM_PERMANENT
Definition: buf_internals.h:69
static ForkNumber BufTagGetForkNum(const BufferTag *tag)
static BufferDesc * GetBufferDescriptor(uint32 id)
static void UnlockBufHdr(BufferDesc *desc, uint32 buf_state)
static RelFileNumber BufTagGetRelNumber(const BufferTag *tag)
BlockNumber RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
Definition: bufmgr.c:3866
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4850
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:792
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:5688
@ RBM_NORMAL
Definition: bufmgr.h:45
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:359
unsigned int uint32
Definition: c.h:506
#define Assert(condition)
Definition: c.h:858
#define PGDLLEXPORT
Definition: c.h:1331
#define MemSet(start, val, len)
Definition: c.h:1020
#define OidIsValid(objectId)
Definition: c.h:775
int64 TimestampTz
Definition: timestamp.h:39
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:1123
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:1095
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:803
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:665
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:516
uint32 dsm_handle
Definition: dsm_impl.h:55
#define DSM_HANDLE_INVALID
Definition: dsm_impl.h:58
void * GetNamedDSMSegment(const char *name, size_t size, void(*init_callback)(void *ptr), bool *found)
Definition: dsm_registry.c:131
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
int errcode_for_file_access(void)
Definition: elog.c:882
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define LOG
Definition: elog.h:31
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2583
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:782
int FreeFile(FILE *file)
Definition: fd.c:2781
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_RETURN_INT64(x)
Definition: fmgr.h:368
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
bool have_free_buffer(void)
Definition: freelist.c:175
int NBuffers
Definition: globals.c:139
int MyProcPid
Definition: globals.c:45
struct Latch * MyLatch
Definition: globals.c:60
void DefineCustomBoolVariable(const char *name, const char *short_desc, const char *long_desc, bool *valueAddr, bool bootValue, GucContext context, int flags, GucBoolCheckHook check_hook, GucBoolAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5075
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5222
void DefineCustomIntVariable(const char *name, const char *short_desc, const char *long_desc, int *valueAddr, int bootValue, int minValue, int maxValue, GucContext context, int flags, GucIntCheckHook check_hook, GucIntAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5101
@ PGC_POSTMASTER
Definition: guc.h:70
@ PGC_SIGHUP
Definition: guc.h:71
#define GUC_UNIT_S
Definition: guc.h:235
void ProcessConfigFile(GucContext context)
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:105
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
int b
Definition: isn.c:70
int a
Definition: isn.c:69
int j
Definition: isn.c:74
int i
Definition: isn.c:73
void ResetLatch(Latch *latch)
Definition: latch.c:724
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:517
#define WL_TIMEOUT
Definition: latch.h:130
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
#define AccessShareLock
Definition: lockdefs.h:36
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:630
int LWLockNewTrancheId(void)
Definition: lwlock.c:606
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:709
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void pfree(void *pointer)
Definition: mcxt.c:1520
void * palloc(Size size)
Definition: mcxt.c:1316
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define InvalidPid
Definition: miscadmin.h:32
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1778
void * arg
#define MAXPGPATH
#define die(msg)
static char * buf
Definition: pg_test_fsync.c:73
char * tablespace
Definition: pgbench.c:216
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define snprintf
Definition: port.h:238
#define fprintf
Definition: port.h:242
#define qsort(a, b, c, d)
Definition: port.h:449
uintptr_t Datum
Definition: postgres.h:64
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:4229
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:4189
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:635
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:567
Oid RelidByRelfilenumber(Oid reltablespace, RelFileNumber relfilenumber)
Oid RelFileNumber
Definition: relpath.h:25
ForkNumber
Definition: relpath.h:48
@ InvalidForkNumber
Definition: relpath.h:49
#define MAX_FORKNUM
Definition: relpath.h:62
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:398
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:88
dsm_handle block_info_handle
Definition: autoprewarm.c:78
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:97
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
int bgw_restart_time
Definition: bgworker.h:95
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
pid_t bgw_notify_pid
Definition: bgworker.h:100
char bgw_library_name[MAXPGPATH]
Definition: bgworker.h:96
ForkNumber forknum
Definition: autoprewarm.c:66
RelFileNumber filenumber
Definition: autoprewarm.c:65
BlockNumber blocknum
Definition: autoprewarm.c:67
BufferTag tag
Definition: lwlock.h:42
uint16 tranche
Definition: lwlock.h:43
BlockNumber blockNum
Definition: buf_internals.h:98
Oid spcOid
Definition: buf_internals.h:94
Oid dbOid
Definition: buf_internals.h:95
Definition: regguts.h:323
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
@ WAIT_EVENT_EXTENSION
Definition: wait_event.h:58
#define SIGHUP
Definition: win32_port.h:168
#define SIGUSR1
Definition: win32_port.h:180
void StartTransactionCommand(void)
Definition: xact.c:2995
void CommitTransactionCommand(void)
Definition: xact.c:3093