LCOV - code coverage report
Current view: top level - src/bin/pg_resetwal - pg_resetwal.c (source / functions) Hit Total Coverage
Test: PostgreSQL 16beta1 Lines: 376 501 75.0 %
Date: 2023-06-01 11:12:20 Functions: 12 12 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * pg_resetwal.c
       4             :  *    A utility to "zero out" the xlog when it's corrupt beyond recovery.
       5             :  *    Can also rebuild pg_control if needed.
       6             :  *
       7             :  * The theory of operation is fairly simple:
       8             :  *    1. Read the existing pg_control (which will include the last
       9             :  *       checkpoint record).  If it is an old format then update to
      10             :  *       current format.
      11             :  *    2. If pg_control is corrupt, attempt to intuit reasonable values,
      12             :  *       by scanning the old xlog if necessary.
      13             :  *    3. Modify pg_control to reflect a "shutdown" state with a checkpoint
      14             :  *       record at the start of xlog.
      15             :  *    4. Flush the existing xlog files and write a new segment with
      16             :  *       just a checkpoint record in it.  The new segment is positioned
      17             :  *       just past the end of the old xlog, so that existing LSNs in
      18             :  *       data pages will appear to be "in the past".
      19             :  * This is all pretty straightforward except for the intuition part of
      20             :  * step 2 ...
      21             :  *
      22             :  *
      23             :  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
      24             :  * Portions Copyright (c) 1994, Regents of the University of California
      25             :  *
      26             :  * src/bin/pg_resetwal/pg_resetwal.c
      27             :  *
      28             :  *-------------------------------------------------------------------------
      29             :  */
      30             : 
      31             : /*
      32             :  * We have to use postgres.h not postgres_fe.h here, because there's so much
      33             :  * backend-only stuff in the XLOG include files we need.  But we need a
      34             :  * frontend-ish environment otherwise.  Hence this ugly hack.
      35             :  */
      36             : #define FRONTEND 1
      37             : 
      38             : #include "postgres.h"
      39             : 
      40             : #include <dirent.h>
      41             : #include <fcntl.h>
      42             : #include <sys/stat.h>
      43             : #include <sys/time.h>
      44             : #include <time.h>
      45             : #include <unistd.h>
      46             : 
      47             : #include "access/heaptoast.h"
      48             : #include "access/multixact.h"
      49             : #include "access/transam.h"
      50             : #include "access/xlog.h"
      51             : #include "access/xlog_internal.h"
      52             : #include "common/controldata_utils.h"
      53             : #include "common/fe_memutils.h"
      54             : #include "common/file_perm.h"
      55             : #include "common/logging.h"
      56             : #include "common/restricted_token.h"
      57             : #include "common/string.h"
      58             : #include "getopt_long.h"
      59             : #include "pg_getopt.h"
      60             : #include "storage/large_object.h"
      61             : 
      62             : static ControlFileData ControlFile; /* pg_control values */
      63             : static XLogSegNo newXlogSegNo;  /* new XLOG segment # */
      64             : static bool guessed = false;    /* T if we had to guess at any values */
      65             : static const char *progname;
      66             : static uint32 set_xid_epoch = (uint32) -1;
      67             : static TransactionId set_oldest_xid = 0;
      68             : static TransactionId set_xid = 0;
      69             : static TransactionId set_oldest_commit_ts_xid = 0;
      70             : static TransactionId set_newest_commit_ts_xid = 0;
      71             : static Oid  set_oid = 0;
      72             : static MultiXactId set_mxid = 0;
      73             : static MultiXactOffset set_mxoff = (MultiXactOffset) -1;
      74             : static TimeLineID minXlogTli = 0;
      75             : static XLogSegNo minXlogSegNo = 0;
      76             : static int  WalSegSz;
      77             : static int  set_wal_segsize;
      78             : 
      79             : static void CheckDataVersion(void);
      80             : static bool read_controlfile(void);
      81             : static void GuessControlValues(void);
      82             : static void PrintControlValues(bool guessed);
      83             : static void PrintNewControlValues(void);
      84             : static void RewriteControlFile(void);
      85             : static void FindEndOfXLOG(void);
      86             : static void KillExistingXLOG(void);
      87             : static void KillExistingArchiveStatus(void);
      88             : static void WriteEmptyXLOG(void);
      89             : static void usage(void);
      90             : 
      91             : 
      92             : int
      93          44 : main(int argc, char *argv[])
      94             : {
      95             :     static struct option long_options[] = {
      96             :         {"commit-timestamp-ids", required_argument, NULL, 'c'},
      97             :         {"pgdata", required_argument, NULL, 'D'},
      98             :         {"epoch", required_argument, NULL, 'e'},
      99             :         {"force", no_argument, NULL, 'f'},
     100             :         {"next-wal-file", required_argument, NULL, 'l'},
     101             :         {"multixact-ids", required_argument, NULL, 'm'},
     102             :         {"dry-run", no_argument, NULL, 'n'},
     103             :         {"next-oid", required_argument, NULL, 'o'},
     104             :         {"multixact-offset", required_argument, NULL, 'O'},
     105             :         {"oldest-transaction-id", required_argument, NULL, 'u'},
     106             :         {"next-transaction-id", required_argument, NULL, 'x'},
     107             :         {"wal-segsize", required_argument, NULL, 1},
     108             :         {NULL, 0, NULL, 0}
     109             :     };
     110             : 
     111             :     int         c;
     112          44 :     bool        force = false;
     113          44 :     bool        noupdate = false;
     114          44 :     MultiXactId set_oldestmxid = 0;
     115             :     char       *endptr;
     116             :     char       *endptr2;
     117          44 :     char       *DataDir = NULL;
     118          44 :     char       *log_fname = NULL;
     119             :     int         fd;
     120             : 
     121          44 :     pg_logging_init(argv[0]);
     122          44 :     set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_resetwal"));
     123          44 :     progname = get_progname(argv[0]);
     124             : 
     125          44 :     if (argc > 1)
     126             :     {
     127          44 :         if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
     128             :         {
     129           2 :             usage();
     130           2 :             exit(0);
     131             :         }
     132          42 :         if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
     133             :         {
     134          10 :             puts("pg_resetwal (PostgreSQL) " PG_VERSION);
     135          10 :             exit(0);
     136             :         }
     137             :     }
     138             : 
     139             : 
     140          72 :     while ((c = getopt_long(argc, argv, "c:D:e:fl:m:no:O:u:x:", long_options, NULL)) != -1)
     141             :     {
     142          42 :         switch (c)
     143             :         {
     144           0 :             case 'D':
     145           0 :                 DataDir = optarg;
     146           0 :                 break;
     147             : 
     148           8 :             case 'f':
     149           8 :                 force = true;
     150           8 :                 break;
     151             : 
     152          14 :             case 'n':
     153          14 :                 noupdate = true;
     154          14 :                 break;
     155             : 
     156           4 :             case 'e':
     157           4 :                 errno = 0;
     158           4 :                 set_xid_epoch = strtoul(optarg, &endptr, 0);
     159           4 :                 if (endptr == optarg || *endptr != '\0' || errno != 0)
     160             :                 {
     161             :                     /*------
     162             :                       translator: the second %s is a command line argument (-e, etc) */
     163           0 :                     pg_log_error("invalid argument for option %s", "-e");
     164           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     165           0 :                     exit(1);
     166             :                 }
     167           4 :                 if (set_xid_epoch == -1)
     168           0 :                     pg_fatal("transaction ID epoch (-e) must not be -1");
     169           4 :                 break;
     170             : 
     171           2 :             case 'u':
     172           2 :                 errno = 0;
     173           2 :                 set_oldest_xid = strtoul(optarg, &endptr, 0);
     174           2 :                 if (endptr == optarg || *endptr != '\0' || errno != 0)
     175             :                 {
     176           0 :                     pg_log_error("invalid argument for option %s", "-u");
     177           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     178           0 :                     exit(1);
     179             :                 }
     180           2 :                 if (!TransactionIdIsNormal(set_oldest_xid))
     181           0 :                     pg_fatal("oldest transaction ID (-u) must be greater than or equal to %u", FirstNormalTransactionId);
     182           2 :                 break;
     183             : 
     184           2 :             case 'x':
     185           2 :                 errno = 0;
     186           2 :                 set_xid = strtoul(optarg, &endptr, 0);
     187           2 :                 if (endptr == optarg || *endptr != '\0' || errno != 0)
     188             :                 {
     189           0 :                     pg_log_error("invalid argument for option %s", "-x");
     190           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     191           0 :                     exit(1);
     192             :                 }
     193           2 :                 if (!TransactionIdIsNormal(set_xid))
     194           0 :                     pg_fatal("transaction ID (-x) must be greater than or equal to %u", FirstNormalTransactionId);
     195           2 :                 break;
     196             : 
     197           2 :             case 'c':
     198           2 :                 errno = 0;
     199           2 :                 set_oldest_commit_ts_xid = strtoul(optarg, &endptr, 0);
     200           2 :                 if (endptr == optarg || *endptr != ',' || errno != 0)
     201             :                 {
     202           0 :                     pg_log_error("invalid argument for option %s", "-c");
     203           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     204           0 :                     exit(1);
     205             :                 }
     206           2 :                 set_newest_commit_ts_xid = strtoul(endptr + 1, &endptr2, 0);
     207           2 :                 if (endptr2 == endptr + 1 || *endptr2 != '\0' || errno != 0)
     208             :                 {
     209           0 :                     pg_log_error("invalid argument for option %s", "-c");
     210           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     211           0 :                     exit(1);
     212             :                 }
     213             : 
     214           2 :                 if (set_oldest_commit_ts_xid < 2 &&
     215           0 :                     set_oldest_commit_ts_xid != 0)
     216           0 :                     pg_fatal("transaction ID (-c) must be either 0 or greater than or equal to 2");
     217             : 
     218           2 :                 if (set_newest_commit_ts_xid < 2 &&
     219           0 :                     set_newest_commit_ts_xid != 0)
     220           0 :                     pg_fatal("transaction ID (-c) must be either 0 or greater than or equal to 2");
     221           2 :                 break;
     222             : 
     223           2 :             case 'o':
     224           2 :                 errno = 0;
     225           2 :                 set_oid = strtoul(optarg, &endptr, 0);
     226           2 :                 if (endptr == optarg || *endptr != '\0' || errno != 0)
     227             :                 {
     228           0 :                     pg_log_error("invalid argument for option %s", "-o");
     229           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     230           0 :                     exit(1);
     231             :                 }
     232           2 :                 if (set_oid == 0)
     233           0 :                     pg_fatal("OID (-o) must not be 0");
     234           2 :                 break;
     235             : 
     236           2 :             case 'm':
     237           2 :                 errno = 0;
     238           2 :                 set_mxid = strtoul(optarg, &endptr, 0);
     239           2 :                 if (endptr == optarg || *endptr != ',' || errno != 0)
     240             :                 {
     241           0 :                     pg_log_error("invalid argument for option %s", "-m");
     242           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     243           0 :                     exit(1);
     244             :                 }
     245             : 
     246           2 :                 set_oldestmxid = strtoul(endptr + 1, &endptr2, 0);
     247           2 :                 if (endptr2 == endptr + 1 || *endptr2 != '\0' || errno != 0)
     248             :                 {
     249           0 :                     pg_log_error("invalid argument for option %s", "-m");
     250           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     251           0 :                     exit(1);
     252             :                 }
     253           2 :                 if (set_mxid == 0)
     254           0 :                     pg_fatal("multitransaction ID (-m) must not be 0");
     255             : 
     256             :                 /*
     257             :                  * XXX It'd be nice to have more sanity checks here, e.g. so
     258             :                  * that oldest is not wrapped around w.r.t. nextMulti.
     259             :                  */
     260           2 :                 if (set_oldestmxid == 0)
     261           0 :                     pg_fatal("oldest multitransaction ID (-m) must not be 0");
     262           2 :                 break;
     263             : 
     264           2 :             case 'O':
     265           2 :                 errno = 0;
     266           2 :                 set_mxoff = strtoul(optarg, &endptr, 0);
     267           2 :                 if (endptr == optarg || *endptr != '\0' || errno != 0)
     268             :                 {
     269           0 :                     pg_log_error("invalid argument for option %s", "-O");
     270           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     271           0 :                     exit(1);
     272             :                 }
     273           2 :                 if (set_mxoff == -1)
     274           0 :                     pg_fatal("multitransaction offset (-O) must not be -1");
     275           2 :                 break;
     276             : 
     277           2 :             case 'l':
     278           2 :                 if (strspn(optarg, "01234567890ABCDEFabcdef") != XLOG_FNAME_LEN)
     279             :                 {
     280           0 :                     pg_log_error("invalid argument for option %s", "-l");
     281           0 :                     pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     282           0 :                     exit(1);
     283             :                 }
     284             : 
     285             :                 /*
     286             :                  * XLogFromFileName requires wal segment size which is not yet
     287             :                  * set. Hence wal details are set later on.
     288             :                  */
     289           2 :                 log_fname = pg_strdup(optarg);
     290           2 :                 break;
     291             : 
     292           0 :             case 1:
     293           0 :                 errno = 0;
     294           0 :                 set_wal_segsize = strtol(optarg, &endptr, 10) * 1024 * 1024;
     295           0 :                 if (endptr == optarg || *endptr != '\0' || errno != 0)
     296           0 :                     pg_fatal("argument of --wal-segsize must be a number");
     297           0 :                 if (!IsValidWalSegSize(set_wal_segsize))
     298           0 :                     pg_fatal("argument of --wal-segsize must be a power of 2 between 1 and 1024");
     299           0 :                 break;
     300             : 
     301           2 :             default:
     302             :                 /* getopt_long already emitted a complaint */
     303           2 :                 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     304           2 :                 exit(1);
     305             :         }
     306             :     }
     307             : 
     308          30 :     if (DataDir == NULL && optind < argc)
     309          30 :         DataDir = argv[optind++];
     310             : 
     311             :     /* Complain if any arguments remain */
     312          30 :     if (optind < argc)
     313             :     {
     314           0 :         pg_log_error("too many command-line arguments (first is \"%s\")",
     315             :                      argv[optind]);
     316           0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     317           0 :         exit(1);
     318             :     }
     319             : 
     320          30 :     if (DataDir == NULL)
     321             :     {
     322           0 :         pg_log_error("no data directory specified");
     323           0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     324           0 :         exit(1);
     325             :     }
     326             : 
     327             :     /*
     328             :      * Don't allow pg_resetwal to be run as root, to avoid overwriting the
     329             :      * ownership of files in the data directory. We need only check for root
     330             :      * -- any other user won't have sufficient permissions to modify files in
     331             :      * the data directory.
     332             :      */
     333             : #ifndef WIN32
     334          30 :     if (geteuid() == 0)
     335             :     {
     336           0 :         pg_log_error("cannot be executed by \"root\"");
     337           0 :         pg_log_error_hint("You must run %s as the PostgreSQL superuser.",
     338             :                           progname);
     339           0 :         exit(1);
     340             :     }
     341             : #endif
     342             : 
     343          30 :     get_restricted_token();
     344             : 
     345             :     /* Set mask based on PGDATA permissions */
     346          30 :     if (!GetDataDirectoryCreatePerm(DataDir))
     347           0 :         pg_fatal("could not read permissions of directory \"%s\": %m",
     348             :                  DataDir);
     349             : 
     350          30 :     umask(pg_mode_mask);
     351             : 
     352          30 :     if (chdir(DataDir) < 0)
     353           0 :         pg_fatal("could not change directory to \"%s\": %m",
     354             :                  DataDir);
     355             : 
     356             :     /* Check that data directory matches our server version */
     357          30 :     CheckDataVersion();
     358             : 
     359             :     /*
     360             :      * Check for a postmaster lock file --- if there is one, refuse to
     361             :      * proceed, on grounds we might be interfering with a live installation.
     362             :      */
     363          30 :     if ((fd = open("postmaster.pid", O_RDONLY, 0)) < 0)
     364             :     {
     365          30 :         if (errno != ENOENT)
     366           0 :             pg_fatal("could not open file \"%s\" for reading: %m",
     367             :                      "postmaster.pid");
     368             :     }
     369             :     else
     370             :     {
     371           0 :         pg_log_error("lock file \"%s\" exists", "postmaster.pid");
     372           0 :         pg_log_error_hint("Is a server running?  If not, delete the lock file and try again.");
     373           0 :         exit(1);
     374             :     }
     375             : 
     376             :     /*
     377             :      * Attempt to read the existing pg_control file
     378             :      */
     379          30 :     if (!read_controlfile())
     380           4 :         GuessControlValues();
     381             : 
     382             :     /*
     383             :      * If no new WAL segment size was specified, use the control file value.
     384             :      */
     385          30 :     if (set_wal_segsize != 0)
     386           0 :         WalSegSz = set_wal_segsize;
     387             :     else
     388          30 :         WalSegSz = ControlFile.xlog_seg_size;
     389             : 
     390          30 :     if (log_fname != NULL)
     391           2 :         XLogFromFileName(log_fname, &minXlogTli, &minXlogSegNo, WalSegSz);
     392             : 
     393             :     /*
     394             :      * Also look at existing segment files to set up newXlogSegNo
     395             :      */
     396          30 :     FindEndOfXLOG();
     397             : 
     398             :     /*
     399             :      * If we're not going to proceed with the reset, print the current control
     400             :      * file parameters.
     401             :      */
     402          30 :     if ((guessed && !force) || noupdate)
     403          14 :         PrintControlValues(guessed);
     404             : 
     405             :     /*
     406             :      * Adjust fields if required by switches.  (Do this now so that printout,
     407             :      * if any, includes these values.)
     408             :      */
     409          30 :     if (set_xid_epoch != -1)
     410             :         ControlFile.checkPointCopy.nextXid =
     411           4 :             FullTransactionIdFromEpochAndXid(set_xid_epoch,
     412           4 :                                              XidFromFullTransactionId(ControlFile.checkPointCopy.nextXid));
     413             : 
     414          30 :     if (set_oldest_xid != 0)
     415             :     {
     416           2 :         ControlFile.checkPointCopy.oldestXid = set_oldest_xid;
     417           2 :         ControlFile.checkPointCopy.oldestXidDB = InvalidOid;
     418             :     }
     419             : 
     420          30 :     if (set_xid != 0)
     421             :         ControlFile.checkPointCopy.nextXid =
     422           2 :             FullTransactionIdFromEpochAndXid(EpochFromFullTransactionId(ControlFile.checkPointCopy.nextXid),
     423             :                                              set_xid);
     424             : 
     425          30 :     if (set_oldest_commit_ts_xid != 0)
     426           2 :         ControlFile.checkPointCopy.oldestCommitTsXid = set_oldest_commit_ts_xid;
     427          30 :     if (set_newest_commit_ts_xid != 0)
     428           2 :         ControlFile.checkPointCopy.newestCommitTsXid = set_newest_commit_ts_xid;
     429             : 
     430          30 :     if (set_oid != 0)
     431           2 :         ControlFile.checkPointCopy.nextOid = set_oid;
     432             : 
     433          30 :     if (set_mxid != 0)
     434             :     {
     435           2 :         ControlFile.checkPointCopy.nextMulti = set_mxid;
     436             : 
     437           2 :         ControlFile.checkPointCopy.oldestMulti = set_oldestmxid;
     438           2 :         if (ControlFile.checkPointCopy.oldestMulti < FirstMultiXactId)
     439           0 :             ControlFile.checkPointCopy.oldestMulti += FirstMultiXactId;
     440           2 :         ControlFile.checkPointCopy.oldestMultiDB = InvalidOid;
     441             :     }
     442             : 
     443          30 :     if (set_mxoff != -1)
     444           2 :         ControlFile.checkPointCopy.nextMultiOffset = set_mxoff;
     445             : 
     446          30 :     if (minXlogTli > ControlFile.checkPointCopy.ThisTimeLineID)
     447             :     {
     448           0 :         ControlFile.checkPointCopy.ThisTimeLineID = minXlogTli;
     449           0 :         ControlFile.checkPointCopy.PrevTimeLineID = minXlogTli;
     450             :     }
     451             : 
     452          30 :     if (set_wal_segsize != 0)
     453           0 :         ControlFile.xlog_seg_size = WalSegSz;
     454             : 
     455          30 :     if (minXlogSegNo > newXlogSegNo)
     456           2 :         newXlogSegNo = minXlogSegNo;
     457             : 
     458             :     /*
     459             :      * If we had to guess anything, and -f was not given, just print the
     460             :      * guessed values and exit.  Also print if -n is given.
     461             :      */
     462          30 :     if ((guessed && !force) || noupdate)
     463             :     {
     464          14 :         PrintNewControlValues();
     465          14 :         if (!noupdate)
     466             :         {
     467           0 :             printf(_("\nIf these values seem acceptable, use -f to force reset.\n"));
     468           0 :             exit(1);
     469             :         }
     470             :         else
     471          14 :             exit(0);
     472             :     }
     473             : 
     474             :     /*
     475             :      * Don't reset from a dirty pg_control without -f, either.
     476             :      */
     477          16 :     if (ControlFile.state != DB_SHUTDOWNED && !force)
     478             :     {
     479           0 :         printf(_("The database server was not shut down cleanly.\n"
     480             :                  "Resetting the write-ahead log might cause data to be lost.\n"
     481             :                  "If you want to proceed anyway, use -f to force reset.\n"));
     482           0 :         exit(1);
     483             :     }
     484             : 
     485             :     /*
     486             :      * Else, do the dirty deed.
     487             :      */
     488          16 :     RewriteControlFile();
     489          16 :     KillExistingXLOG();
     490          16 :     KillExistingArchiveStatus();
     491          16 :     WriteEmptyXLOG();
     492             : 
     493          16 :     printf(_("Write-ahead log reset\n"));
     494          16 :     return 0;
     495             : }
     496             : 
     497             : 
     498             : /*
     499             :  * Look at the version string stored in PG_VERSION and decide if this utility
     500             :  * can be run safely or not.
     501             :  *
     502             :  * We don't want to inject pg_control and WAL files that are for a different
     503             :  * major version; that can't do anything good.  Note that we don't treat
     504             :  * mismatching version info in pg_control as a reason to bail out, because
     505             :  * recovering from a corrupted pg_control is one of the main reasons for this
     506             :  * program to exist at all.  However, PG_VERSION is unlikely to get corrupted,
     507             :  * and if it were it would be easy to fix by hand.  So let's make this check
     508             :  * to prevent simple user errors.
     509             :  */
     510             : static void
     511          30 : CheckDataVersion(void)
     512             : {
     513          30 :     const char *ver_file = "PG_VERSION";
     514             :     FILE       *ver_fd;
     515             :     char        rawline[64];
     516             : 
     517          30 :     if ((ver_fd = fopen(ver_file, "r")) == NULL)
     518           0 :         pg_fatal("could not open file \"%s\" for reading: %m",
     519             :                  ver_file);
     520             : 
     521             :     /* version number has to be the first line read */
     522          30 :     if (!fgets(rawline, sizeof(rawline), ver_fd))
     523             :     {
     524           0 :         if (!ferror(ver_fd))
     525           0 :             pg_fatal("unexpected empty file \"%s\"", ver_file);
     526             :         else
     527           0 :             pg_fatal("could not read file \"%s\": %m", ver_file);
     528             :     }
     529             : 
     530             :     /* strip trailing newline and carriage return */
     531          30 :     (void) pg_strip_crlf(rawline);
     532             : 
     533          30 :     if (strcmp(rawline, PG_MAJORVERSION) != 0)
     534             :     {
     535           0 :         pg_log_error("data directory is of wrong version");
     536           0 :         pg_log_error_detail("File \"%s\" contains \"%s\", which is not compatible with this program's version \"%s\".",
     537             :                             ver_file, rawline, PG_MAJORVERSION);
     538           0 :         exit(1);
     539             :     }
     540             : 
     541          30 :     fclose(ver_fd);
     542          30 : }
     543             : 
     544             : 
     545             : /*
     546             :  * Try to read the existing pg_control file.
     547             :  *
     548             :  * This routine is also responsible for updating old pg_control versions
     549             :  * to the current format.  (Currently we don't do anything of the sort.)
     550             :  */
     551             : static bool
     552          30 : read_controlfile(void)
     553             : {
     554             :     int         fd;
     555             :     int         len;
     556             :     char       *buffer;
     557             :     pg_crc32c   crc;
     558             : 
     559          30 :     if ((fd = open(XLOG_CONTROL_FILE, O_RDONLY | PG_BINARY, 0)) < 0)
     560             :     {
     561             :         /*
     562             :          * If pg_control is not there at all, or we can't read it, the odds
     563             :          * are we've been handed a bad DataDir path, so give up. User can do
     564             :          * "touch pg_control" to force us to proceed.
     565             :          */
     566           0 :         pg_log_error("could not open file \"%s\" for reading: %m",
     567             :                      XLOG_CONTROL_FILE);
     568           0 :         if (errno == ENOENT)
     569           0 :             pg_log_error_hint("If you are sure the data directory path is correct, execute\n"
     570             :                               "  touch %s\n"
     571             :                               "and try again.",
     572             :                               XLOG_CONTROL_FILE);
     573           0 :         exit(1);
     574             :     }
     575             : 
     576             :     /* Use malloc to ensure we have a maxaligned buffer */
     577          30 :     buffer = (char *) pg_malloc(PG_CONTROL_FILE_SIZE);
     578             : 
     579          30 :     len = read(fd, buffer, PG_CONTROL_FILE_SIZE);
     580          30 :     if (len < 0)
     581           0 :         pg_fatal("could not read file \"%s\": %m", XLOG_CONTROL_FILE);
     582          30 :     close(fd);
     583             : 
     584          30 :     if (len >= sizeof(ControlFileData) &&
     585          30 :         ((ControlFileData *) buffer)->pg_control_version == PG_CONTROL_VERSION)
     586             :     {
     587             :         /* Check the CRC. */
     588          28 :         INIT_CRC32C(crc);
     589          28 :         COMP_CRC32C(crc,
     590             :                     buffer,
     591             :                     offsetof(ControlFileData, crc));
     592          28 :         FIN_CRC32C(crc);
     593             : 
     594          28 :         if (!EQ_CRC32C(crc, ((ControlFileData *) buffer)->crc))
     595             :         {
     596             :             /* We will use the data but treat it as guessed. */
     597           2 :             pg_log_warning("pg_control exists but has invalid CRC; proceed with caution");
     598           2 :             guessed = true;
     599             :         }
     600             : 
     601          28 :         memcpy(&ControlFile, buffer, sizeof(ControlFile));
     602             : 
     603             :         /* return false if WAL segment size is not valid */
     604          28 :         if (!IsValidWalSegSize(ControlFile.xlog_seg_size))
     605             :         {
     606           2 :             pg_log_warning(ngettext("pg_control specifies invalid WAL segment size (%d byte); proceed with caution",
     607             :                                     "pg_control specifies invalid WAL segment size (%d bytes); proceed with caution",
     608             :                                     ControlFile.xlog_seg_size),
     609             :                            ControlFile.xlog_seg_size);
     610           2 :             return false;
     611             :         }
     612             : 
     613          26 :         return true;
     614             :     }
     615             : 
     616             :     /* Looks like it's a mess. */
     617           2 :     pg_log_warning("pg_control exists but is broken or wrong version; ignoring it");
     618           2 :     return false;
     619             : }
     620             : 
     621             : 
     622             : /*
     623             :  * Guess at pg_control values when we can't read the old ones.
     624             :  */
     625             : static void
     626           4 : GuessControlValues(void)
     627             : {
     628             :     uint64      sysidentifier;
     629             :     struct timeval tv;
     630             : 
     631             :     /*
     632             :      * Set up a completely default set of pg_control values.
     633             :      */
     634           4 :     guessed = true;
     635           4 :     memset(&ControlFile, 0, sizeof(ControlFile));
     636             : 
     637           4 :     ControlFile.pg_control_version = PG_CONTROL_VERSION;
     638           4 :     ControlFile.catalog_version_no = CATALOG_VERSION_NO;
     639             : 
     640             :     /*
     641             :      * Create a new unique installation identifier, since we can no longer use
     642             :      * any old XLOG records.  See notes in xlog.c about the algorithm.
     643             :      */
     644           4 :     gettimeofday(&tv, NULL);
     645           4 :     sysidentifier = ((uint64) tv.tv_sec) << 32;
     646           4 :     sysidentifier |= ((uint64) tv.tv_usec) << 12;
     647           4 :     sysidentifier |= getpid() & 0xFFF;
     648             : 
     649           4 :     ControlFile.system_identifier = sysidentifier;
     650             : 
     651           4 :     ControlFile.checkPointCopy.redo = SizeOfXLogLongPHD;
     652           4 :     ControlFile.checkPointCopy.ThisTimeLineID = 1;
     653           4 :     ControlFile.checkPointCopy.PrevTimeLineID = 1;
     654           4 :     ControlFile.checkPointCopy.fullPageWrites = false;
     655             :     ControlFile.checkPointCopy.nextXid =
     656           4 :         FullTransactionIdFromEpochAndXid(0, FirstNormalTransactionId);
     657           4 :     ControlFile.checkPointCopy.nextOid = FirstGenbkiObjectId;
     658           4 :     ControlFile.checkPointCopy.nextMulti = FirstMultiXactId;
     659           4 :     ControlFile.checkPointCopy.nextMultiOffset = 0;
     660           4 :     ControlFile.checkPointCopy.oldestXid = FirstNormalTransactionId;
     661           4 :     ControlFile.checkPointCopy.oldestXidDB = InvalidOid;
     662           4 :     ControlFile.checkPointCopy.oldestMulti = FirstMultiXactId;
     663           4 :     ControlFile.checkPointCopy.oldestMultiDB = InvalidOid;
     664           4 :     ControlFile.checkPointCopy.time = (pg_time_t) time(NULL);
     665           4 :     ControlFile.checkPointCopy.oldestActiveXid = InvalidTransactionId;
     666             : 
     667           4 :     ControlFile.state = DB_SHUTDOWNED;
     668           4 :     ControlFile.time = (pg_time_t) time(NULL);
     669           4 :     ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
     670           4 :     ControlFile.unloggedLSN = FirstNormalUnloggedLSN;
     671             : 
     672             :     /* minRecoveryPoint, backupStartPoint and backupEndPoint can be left zero */
     673             : 
     674           4 :     ControlFile.wal_level = WAL_LEVEL_MINIMAL;
     675           4 :     ControlFile.wal_log_hints = false;
     676           4 :     ControlFile.track_commit_timestamp = false;
     677           4 :     ControlFile.MaxConnections = 100;
     678           4 :     ControlFile.max_wal_senders = 10;
     679           4 :     ControlFile.max_worker_processes = 8;
     680           4 :     ControlFile.max_prepared_xacts = 0;
     681           4 :     ControlFile.max_locks_per_xact = 64;
     682             : 
     683           4 :     ControlFile.maxAlign = MAXIMUM_ALIGNOF;
     684           4 :     ControlFile.floatFormat = FLOATFORMAT_VALUE;
     685           4 :     ControlFile.blcksz = BLCKSZ;
     686           4 :     ControlFile.relseg_size = RELSEG_SIZE;
     687           4 :     ControlFile.xlog_blcksz = XLOG_BLCKSZ;
     688           4 :     ControlFile.xlog_seg_size = DEFAULT_XLOG_SEG_SIZE;
     689           4 :     ControlFile.nameDataLen = NAMEDATALEN;
     690           4 :     ControlFile.indexMaxKeys = INDEX_MAX_KEYS;
     691           4 :     ControlFile.toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
     692           4 :     ControlFile.loblksize = LOBLKSIZE;
     693           4 :     ControlFile.float8ByVal = FLOAT8PASSBYVAL;
     694             : 
     695             :     /*
     696             :      * XXX eventually, should try to grovel through old XLOG to develop more
     697             :      * accurate values for TimeLineID, nextXID, etc.
     698             :      */
     699           4 : }
     700             : 
     701             : 
     702             : /*
     703             :  * Print the guessed pg_control values when we had to guess.
     704             :  *
     705             :  * NB: this display should be just those fields that will not be
     706             :  * reset by RewriteControlFile().
     707             :  */
     708             : static void
     709          14 : PrintControlValues(bool guessed)
     710             : {
     711          14 :     if (guessed)
     712           4 :         printf(_("Guessed pg_control values:\n\n"));
     713             :     else
     714          10 :         printf(_("Current pg_control values:\n\n"));
     715             : 
     716          14 :     printf(_("pg_control version number:            %u\n"),
     717             :            ControlFile.pg_control_version);
     718          14 :     printf(_("Catalog version number:               %u\n"),
     719             :            ControlFile.catalog_version_no);
     720          14 :     printf(_("Database system identifier:           %llu\n"),
     721             :            (unsigned long long) ControlFile.system_identifier);
     722          14 :     printf(_("Latest checkpoint's TimeLineID:       %u\n"),
     723             :            ControlFile.checkPointCopy.ThisTimeLineID);
     724          14 :     printf(_("Latest checkpoint's full_page_writes: %s\n"),
     725             :            ControlFile.checkPointCopy.fullPageWrites ? _("on") : _("off"));
     726          14 :     printf(_("Latest checkpoint's NextXID:          %u:%u\n"),
     727             :            EpochFromFullTransactionId(ControlFile.checkPointCopy.nextXid),
     728             :            XidFromFullTransactionId(ControlFile.checkPointCopy.nextXid));
     729          14 :     printf(_("Latest checkpoint's NextOID:          %u\n"),
     730             :            ControlFile.checkPointCopy.nextOid);
     731          14 :     printf(_("Latest checkpoint's NextMultiXactId:  %u\n"),
     732             :            ControlFile.checkPointCopy.nextMulti);
     733          14 :     printf(_("Latest checkpoint's NextMultiOffset:  %u\n"),
     734             :            ControlFile.checkPointCopy.nextMultiOffset);
     735          14 :     printf(_("Latest checkpoint's oldestXID:        %u\n"),
     736             :            ControlFile.checkPointCopy.oldestXid);
     737          14 :     printf(_("Latest checkpoint's oldestXID's DB:   %u\n"),
     738             :            ControlFile.checkPointCopy.oldestXidDB);
     739          14 :     printf(_("Latest checkpoint's oldestActiveXID:  %u\n"),
     740             :            ControlFile.checkPointCopy.oldestActiveXid);
     741          14 :     printf(_("Latest checkpoint's oldestMultiXid:   %u\n"),
     742             :            ControlFile.checkPointCopy.oldestMulti);
     743          14 :     printf(_("Latest checkpoint's oldestMulti's DB: %u\n"),
     744             :            ControlFile.checkPointCopy.oldestMultiDB);
     745          14 :     printf(_("Latest checkpoint's oldestCommitTsXid:%u\n"),
     746             :            ControlFile.checkPointCopy.oldestCommitTsXid);
     747          14 :     printf(_("Latest checkpoint's newestCommitTsXid:%u\n"),
     748             :            ControlFile.checkPointCopy.newestCommitTsXid);
     749          14 :     printf(_("Maximum data alignment:               %u\n"),
     750             :            ControlFile.maxAlign);
     751             :     /* we don't print floatFormat since can't say much useful about it */
     752          14 :     printf(_("Database block size:                  %u\n"),
     753             :            ControlFile.blcksz);
     754          14 :     printf(_("Blocks per segment of large relation: %u\n"),
     755             :            ControlFile.relseg_size);
     756          14 :     printf(_("WAL block size:                       %u\n"),
     757             :            ControlFile.xlog_blcksz);
     758          14 :     printf(_("Bytes per WAL segment:                %u\n"),
     759             :            ControlFile.xlog_seg_size);
     760          14 :     printf(_("Maximum length of identifiers:        %u\n"),
     761             :            ControlFile.nameDataLen);
     762          14 :     printf(_("Maximum columns in an index:          %u\n"),
     763             :            ControlFile.indexMaxKeys);
     764          14 :     printf(_("Maximum size of a TOAST chunk:        %u\n"),
     765             :            ControlFile.toast_max_chunk_size);
     766          14 :     printf(_("Size of a large-object chunk:         %u\n"),
     767             :            ControlFile.loblksize);
     768             :     /* This is no longer configurable, but users may still expect to see it: */
     769          14 :     printf(_("Date/time type storage:               %s\n"),
     770             :            _("64-bit integers"));
     771          14 :     printf(_("Float8 argument passing:              %s\n"),
     772             :            (ControlFile.float8ByVal ? _("by value") : _("by reference")));
     773          14 :     printf(_("Data page checksum version:           %u\n"),
     774             :            ControlFile.data_checksum_version);
     775          14 : }
     776             : 
     777             : 
     778             : /*
     779             :  * Print the values to be changed.
     780             :  */
     781             : static void
     782          14 : PrintNewControlValues(void)
     783             : {
     784             :     char        fname[MAXFNAMELEN];
     785             : 
     786             :     /* This will be always printed in order to keep format same. */
     787          14 :     printf(_("\n\nValues to be changed:\n\n"));
     788             : 
     789          14 :     XLogFileName(fname, ControlFile.checkPointCopy.ThisTimeLineID,
     790             :                  newXlogSegNo, WalSegSz);
     791          14 :     printf(_("First log segment after reset:        %s\n"), fname);
     792             : 
     793          14 :     if (set_mxid != 0)
     794             :     {
     795           0 :         printf(_("NextMultiXactId:                      %u\n"),
     796             :                ControlFile.checkPointCopy.nextMulti);
     797           0 :         printf(_("OldestMultiXid:                       %u\n"),
     798             :                ControlFile.checkPointCopy.oldestMulti);
     799           0 :         printf(_("OldestMulti's DB:                     %u\n"),
     800             :                ControlFile.checkPointCopy.oldestMultiDB);
     801             :     }
     802             : 
     803          14 :     if (set_mxoff != -1)
     804             :     {
     805           0 :         printf(_("NextMultiOffset:                      %u\n"),
     806             :                ControlFile.checkPointCopy.nextMultiOffset);
     807             :     }
     808             : 
     809          14 :     if (set_oid != 0)
     810             :     {
     811           0 :         printf(_("NextOID:                              %u\n"),
     812             :                ControlFile.checkPointCopy.nextOid);
     813             :     }
     814             : 
     815          14 :     if (set_xid != 0)
     816             :     {
     817           0 :         printf(_("NextXID:                              %u\n"),
     818             :                XidFromFullTransactionId(ControlFile.checkPointCopy.nextXid));
     819           0 :         printf(_("OldestXID:                            %u\n"),
     820             :                ControlFile.checkPointCopy.oldestXid);
     821           0 :         printf(_("OldestXID's DB:                       %u\n"),
     822             :                ControlFile.checkPointCopy.oldestXidDB);
     823             :     }
     824             : 
     825          14 :     if (set_xid_epoch != -1)
     826             :     {
     827           0 :         printf(_("NextXID epoch:                        %u\n"),
     828             :                EpochFromFullTransactionId(ControlFile.checkPointCopy.nextXid));
     829             :     }
     830             : 
     831          14 :     if (set_oldest_commit_ts_xid != 0)
     832             :     {
     833           0 :         printf(_("oldestCommitTsXid:                    %u\n"),
     834             :                ControlFile.checkPointCopy.oldestCommitTsXid);
     835             :     }
     836          14 :     if (set_newest_commit_ts_xid != 0)
     837             :     {
     838           0 :         printf(_("newestCommitTsXid:                    %u\n"),
     839             :                ControlFile.checkPointCopy.newestCommitTsXid);
     840             :     }
     841             : 
     842          14 :     if (set_wal_segsize != 0)
     843             :     {
     844           0 :         printf(_("Bytes per WAL segment:                %u\n"),
     845             :                ControlFile.xlog_seg_size);
     846             :     }
     847          14 : }
     848             : 
     849             : 
     850             : /*
     851             :  * Write out the new pg_control file.
     852             :  */
     853             : static void
     854          16 : RewriteControlFile(void)
     855             : {
     856             :     /*
     857             :      * Adjust fields as needed to force an empty XLOG starting at
     858             :      * newXlogSegNo.
     859             :      */
     860          16 :     XLogSegNoOffsetToRecPtr(newXlogSegNo, SizeOfXLogLongPHD, WalSegSz,
     861             :                             ControlFile.checkPointCopy.redo);
     862          16 :     ControlFile.checkPointCopy.time = (pg_time_t) time(NULL);
     863             : 
     864          16 :     ControlFile.state = DB_SHUTDOWNED;
     865          16 :     ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
     866          16 :     ControlFile.minRecoveryPoint = 0;
     867          16 :     ControlFile.minRecoveryPointTLI = 0;
     868          16 :     ControlFile.backupStartPoint = 0;
     869          16 :     ControlFile.backupEndPoint = 0;
     870          16 :     ControlFile.backupEndRequired = false;
     871             : 
     872             :     /*
     873             :      * Force the defaults for max_* settings. The values don't really matter
     874             :      * as long as wal_level='minimal'; the postmaster will reset these fields
     875             :      * anyway at startup.
     876             :      */
     877          16 :     ControlFile.wal_level = WAL_LEVEL_MINIMAL;
     878          16 :     ControlFile.wal_log_hints = false;
     879          16 :     ControlFile.track_commit_timestamp = false;
     880          16 :     ControlFile.MaxConnections = 100;
     881          16 :     ControlFile.max_wal_senders = 10;
     882          16 :     ControlFile.max_worker_processes = 8;
     883          16 :     ControlFile.max_prepared_xacts = 0;
     884          16 :     ControlFile.max_locks_per_xact = 64;
     885             : 
     886             :     /* The control file gets flushed here. */
     887          16 :     update_controlfile(".", &ControlFile, true);
     888          16 : }
     889             : 
     890             : 
     891             : /*
     892             :  * Scan existing XLOG files and determine the highest existing WAL address
     893             :  *
     894             :  * On entry, ControlFile.checkPointCopy.redo and ControlFile.xlog_seg_size
     895             :  * are assumed valid (note that we allow the old xlog seg size to differ
     896             :  * from what we're using).  On exit, newXlogSegNo is set to suitable
     897             :  * value for the beginning of replacement WAL (in our seg size).
     898             :  */
     899             : static void
     900          30 : FindEndOfXLOG(void)
     901             : {
     902             :     DIR        *xldir;
     903             :     struct dirent *xlde;
     904             :     uint64      xlogbytepos;
     905             : 
     906             :     /*
     907             :      * Initialize the max() computation using the last checkpoint address from
     908             :      * old pg_control.  Note that for the moment we are working with segment
     909             :      * numbering according to the old xlog seg size.
     910             :      */
     911          30 :     XLByteToSeg(ControlFile.checkPointCopy.redo, newXlogSegNo,
     912             :                 ControlFile.xlog_seg_size);
     913             : 
     914             :     /*
     915             :      * Scan the pg_wal directory to find existing WAL segment files. We assume
     916             :      * any present have been used; in most scenarios this should be
     917             :      * conservative, because of xlog.c's attempts to pre-create files.
     918             :      */
     919          30 :     xldir = opendir(XLOGDIR);
     920          30 :     if (xldir == NULL)
     921           0 :         pg_fatal("could not open directory \"%s\": %m", XLOGDIR);
     922             : 
     923         464 :     while (errno = 0, (xlde = readdir(xldir)) != NULL)
     924             :     {
     925         524 :         if (IsXLogFileName(xlde->d_name) ||
     926          90 :             IsPartialXLogFileName(xlde->d_name))
     927             :         {
     928             :             TimeLineID  tli;
     929             :             XLogSegNo   segno;
     930             : 
     931             :             /* Use the segment size from the control file */
     932         344 :             XLogFromFileName(xlde->d_name, &tli, &segno,
     933         344 :                              ControlFile.xlog_seg_size);
     934             : 
     935             :             /*
     936             :              * Note: we take the max of all files found, regardless of their
     937             :              * timelines.  Another possibility would be to ignore files of
     938             :              * timelines other than the target TLI, but this seems safer.
     939             :              * Better too large a result than too small...
     940             :              */
     941         344 :             if (segno > newXlogSegNo)
     942          34 :                 newXlogSegNo = segno;
     943             :         }
     944             :     }
     945             : 
     946          30 :     if (errno)
     947           0 :         pg_fatal("could not read directory \"%s\": %m", XLOGDIR);
     948             : 
     949          30 :     if (closedir(xldir))
     950           0 :         pg_fatal("could not close directory \"%s\": %m", XLOGDIR);
     951             : 
     952             :     /*
     953             :      * Finally, convert to new xlog seg size, and advance by one to ensure we
     954             :      * are in virgin territory.
     955             :      */
     956          30 :     xlogbytepos = newXlogSegNo * ControlFile.xlog_seg_size;
     957          30 :     newXlogSegNo = (xlogbytepos + ControlFile.xlog_seg_size - 1) / WalSegSz;
     958          30 :     newXlogSegNo++;
     959          30 : }
     960             : 
     961             : 
     962             : /*
     963             :  * Remove existing XLOG files
     964             :  */
     965             : static void
     966          16 : KillExistingXLOG(void)
     967             : {
     968             :     DIR        *xldir;
     969             :     struct dirent *xlde;
     970             :     char        path[MAXPGPATH + sizeof(XLOGDIR)];
     971             : 
     972          16 :     xldir = opendir(XLOGDIR);
     973          16 :     if (xldir == NULL)
     974           0 :         pg_fatal("could not open directory \"%s\": %m", XLOGDIR);
     975             : 
     976         186 :     while (errno = 0, (xlde = readdir(xldir)) != NULL)
     977             :     {
     978         218 :         if (IsXLogFileName(xlde->d_name) ||
     979          48 :             IsPartialXLogFileName(xlde->d_name))
     980             :         {
     981         122 :             snprintf(path, sizeof(path), "%s/%s", XLOGDIR, xlde->d_name);
     982         122 :             if (unlink(path) < 0)
     983           0 :                 pg_fatal("could not delete file \"%s\": %m", path);
     984             :         }
     985             :     }
     986             : 
     987          16 :     if (errno)
     988           0 :         pg_fatal("could not read directory \"%s\": %m", XLOGDIR);
     989             : 
     990          16 :     if (closedir(xldir))
     991           0 :         pg_fatal("could not close directory \"%s\": %m", XLOGDIR);
     992          16 : }
     993             : 
     994             : 
     995             : /*
     996             :  * Remove existing archive status files
     997             :  */
     998             : static void
     999          16 : KillExistingArchiveStatus(void)
    1000             : {
    1001             : #define ARCHSTATDIR XLOGDIR "/archive_status"
    1002             : 
    1003             :     DIR        *xldir;
    1004             :     struct dirent *xlde;
    1005             :     char        path[MAXPGPATH + sizeof(ARCHSTATDIR)];
    1006             : 
    1007          16 :     xldir = opendir(ARCHSTATDIR);
    1008          16 :     if (xldir == NULL)
    1009           0 :         pg_fatal("could not open directory \"%s\": %m", ARCHSTATDIR);
    1010             : 
    1011          48 :     while (errno = 0, (xlde = readdir(xldir)) != NULL)
    1012             :     {
    1013          32 :         if (strspn(xlde->d_name, "0123456789ABCDEF") == XLOG_FNAME_LEN &&
    1014           0 :             (strcmp(xlde->d_name + XLOG_FNAME_LEN, ".ready") == 0 ||
    1015           0 :              strcmp(xlde->d_name + XLOG_FNAME_LEN, ".done") == 0 ||
    1016           0 :              strcmp(xlde->d_name + XLOG_FNAME_LEN, ".partial.ready") == 0 ||
    1017           0 :              strcmp(xlde->d_name + XLOG_FNAME_LEN, ".partial.done") == 0))
    1018             :         {
    1019           0 :             snprintf(path, sizeof(path), "%s/%s", ARCHSTATDIR, xlde->d_name);
    1020           0 :             if (unlink(path) < 0)
    1021           0 :                 pg_fatal("could not delete file \"%s\": %m", path);
    1022             :         }
    1023             :     }
    1024             : 
    1025          16 :     if (errno)
    1026           0 :         pg_fatal("could not read directory \"%s\": %m", ARCHSTATDIR);
    1027             : 
    1028          16 :     if (closedir(xldir))
    1029           0 :         pg_fatal("could not close directory \"%s\": %m", ARCHSTATDIR);
    1030          16 : }
    1031             : 
    1032             : 
    1033             : /*
    1034             :  * Write an empty XLOG file, containing only the checkpoint record
    1035             :  * already set up in ControlFile.
    1036             :  */
    1037             : static void
    1038          16 : WriteEmptyXLOG(void)
    1039             : {
    1040             :     PGAlignedXLogBlock buffer;
    1041             :     XLogPageHeader page;
    1042             :     XLogLongPageHeader longpage;
    1043             :     XLogRecord *record;
    1044             :     pg_crc32c   crc;
    1045             :     char        path[MAXPGPATH];
    1046             :     int         fd;
    1047             :     int         nbytes;
    1048             :     char       *recptr;
    1049             : 
    1050          16 :     memset(buffer.data, 0, XLOG_BLCKSZ);
    1051             : 
    1052             :     /* Set up the XLOG page header */
    1053          16 :     page = (XLogPageHeader) buffer.data;
    1054          16 :     page->xlp_magic = XLOG_PAGE_MAGIC;
    1055          16 :     page->xlp_info = XLP_LONG_HEADER;
    1056          16 :     page->xlp_tli = ControlFile.checkPointCopy.ThisTimeLineID;
    1057          16 :     page->xlp_pageaddr = ControlFile.checkPointCopy.redo - SizeOfXLogLongPHD;
    1058          16 :     longpage = (XLogLongPageHeader) page;
    1059          16 :     longpage->xlp_sysid = ControlFile.system_identifier;
    1060          16 :     longpage->xlp_seg_size = WalSegSz;
    1061          16 :     longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
    1062             : 
    1063             :     /* Insert the initial checkpoint record */
    1064          16 :     recptr = (char *) page + SizeOfXLogLongPHD;
    1065          16 :     record = (XLogRecord *) recptr;
    1066          16 :     record->xl_prev = 0;
    1067          16 :     record->xl_xid = InvalidTransactionId;
    1068          16 :     record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(CheckPoint);
    1069          16 :     record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
    1070          16 :     record->xl_rmid = RM_XLOG_ID;
    1071             : 
    1072          16 :     recptr += SizeOfXLogRecord;
    1073          16 :     *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
    1074          16 :     *(recptr++) = sizeof(CheckPoint);
    1075          16 :     memcpy(recptr, &ControlFile.checkPointCopy,
    1076             :            sizeof(CheckPoint));
    1077             : 
    1078          16 :     INIT_CRC32C(crc);
    1079          16 :     COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
    1080          16 :     COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
    1081          16 :     FIN_CRC32C(crc);
    1082          16 :     record->xl_crc = crc;
    1083             : 
    1084             :     /* Write the first page */
    1085          16 :     XLogFilePath(path, ControlFile.checkPointCopy.ThisTimeLineID,
    1086             :                  newXlogSegNo, WalSegSz);
    1087             : 
    1088          16 :     unlink(path);
    1089             : 
    1090          16 :     fd = open(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
    1091             :               pg_file_create_mode);
    1092          16 :     if (fd < 0)
    1093           0 :         pg_fatal("could not open file \"%s\": %m", path);
    1094             : 
    1095          16 :     errno = 0;
    1096          16 :     if (write(fd, buffer.data, XLOG_BLCKSZ) != XLOG_BLCKSZ)
    1097             :     {
    1098             :         /* if write didn't set errno, assume problem is no disk space */
    1099           0 :         if (errno == 0)
    1100           0 :             errno = ENOSPC;
    1101           0 :         pg_fatal("could not write file \"%s\": %m", path);
    1102             :     }
    1103             : 
    1104             :     /* Fill the rest of the file with zeroes */
    1105          16 :     memset(buffer.data, 0, XLOG_BLCKSZ);
    1106        5888 :     for (nbytes = XLOG_BLCKSZ; nbytes < WalSegSz; nbytes += XLOG_BLCKSZ)
    1107             :     {
    1108        5872 :         errno = 0;
    1109        5872 :         if (write(fd, buffer.data, XLOG_BLCKSZ) != XLOG_BLCKSZ)
    1110             :         {
    1111           0 :             if (errno == 0)
    1112           0 :                 errno = ENOSPC;
    1113           0 :             pg_fatal("could not write file \"%s\": %m", path);
    1114             :         }
    1115             :     }
    1116             : 
    1117          16 :     if (fsync(fd) != 0)
    1118           0 :         pg_fatal("fsync error: %m");
    1119             : 
    1120          16 :     close(fd);
    1121          16 : }
    1122             : 
    1123             : 
    1124             : static void
    1125           2 : usage(void)
    1126             : {
    1127           2 :     printf(_("%s resets the PostgreSQL write-ahead log.\n\n"), progname);
    1128           2 :     printf(_("Usage:\n  %s [OPTION]... DATADIR\n\n"), progname);
    1129           2 :     printf(_("Options:\n"));
    1130           2 :     printf(_("  -c, --commit-timestamp-ids=XID,XID\n"
    1131             :              "                                   set oldest and newest transactions bearing\n"
    1132             :              "                                   commit timestamp (zero means no change)\n"));
    1133           2 :     printf(_(" [-D, --pgdata=]DATADIR            data directory\n"));
    1134           2 :     printf(_("  -e, --epoch=XIDEPOCH             set next transaction ID epoch\n"));
    1135           2 :     printf(_("  -f, --force                      force update to be done\n"));
    1136           2 :     printf(_("  -l, --next-wal-file=WALFILE      set minimum starting location for new WAL\n"));
    1137           2 :     printf(_("  -m, --multixact-ids=MXID,MXID    set next and oldest multitransaction ID\n"));
    1138           2 :     printf(_("  -n, --dry-run                    no update, just show what would be done\n"));
    1139           2 :     printf(_("  -o, --next-oid=OID               set next OID\n"));
    1140           2 :     printf(_("  -O, --multixact-offset=OFFSET    set next multitransaction offset\n"));
    1141           2 :     printf(_("  -u, --oldest-transaction-id=XID  set oldest transaction ID\n"));
    1142           2 :     printf(_("  -V, --version                    output version information, then exit\n"));
    1143           2 :     printf(_("  -x, --next-transaction-id=XID    set next transaction ID\n"));
    1144           2 :     printf(_("      --wal-segsize=SIZE           size of WAL segments, in megabytes\n"));
    1145           2 :     printf(_("  -?, --help                       show this help, then exit\n"));
    1146           2 :     printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
    1147           2 :     printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
    1148           2 : }

Generated by: LCOV version 1.14