]> granicus.if.org Git - postgresql/blob - src/bin/pg_resetxlog/pg_resetxlog.c
Update pg_resetxlog's documentation on multixacts
[postgresql] / src / bin / pg_resetxlog / pg_resetxlog.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_resetxlog.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-2013, PostgreSQL Global Development Group
24  * Portions Copyright (c) 1994, Regents of the University of California
25  *
26  * src/bin/pg_resetxlog/pg_resetxlog.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 <locale.h>
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include <time.h>
46 #include <unistd.h>
47 #ifdef HAVE_GETOPT_H
48 #include <getopt.h>
49 #endif
50
51 #include "access/transam.h"
52 #include "access/tuptoaster.h"
53 #include "access/multixact.h"
54 #include "access/xlog_internal.h"
55 #include "catalog/catversion.h"
56 #include "catalog/pg_control.h"
57 #include "common/fe_memutils.h"
58
59 extern int      optind;
60 extern char *optarg;
61
62
63 static ControlFileData ControlFile;             /* pg_control values */
64 static XLogSegNo newXlogSegNo;  /* new XLOG segment # */
65 static bool guessed = false;    /* T if we had to guess at any values */
66 static const char *progname;
67
68 static bool ReadControlFile(void);
69 static void GuessControlValues(void);
70 static void PrintControlValues(bool guessed);
71 static void RewriteControlFile(void);
72 static void FindEndOfXLOG(void);
73 static void KillExistingXLOG(void);
74 static void KillExistingArchiveStatus(void);
75 static void WriteEmptyXLOG(void);
76 static void usage(void);
77
78
79 int
80 main(int argc, char *argv[])
81 {
82         int                     c;
83         bool            force = false;
84         bool            noupdate = false;
85         uint32          set_xid_epoch = (uint32) -1;
86         TransactionId set_xid = 0;
87         Oid                     set_oid = 0;
88         MultiXactId set_mxid = 0;
89         MultiXactId set_oldestmxid = 0;
90         MultiXactOffset set_mxoff = (MultiXactOffset) -1;
91         uint32          minXlogTli = 0;
92         XLogSegNo       minXlogSegNo = 0;
93         char       *endptr;
94         char       *endptr2;
95         char       *DataDir;
96         int                     fd;
97
98         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_resetxlog"));
99
100         progname = get_progname(argv[0]);
101
102         if (argc > 1)
103         {
104                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
105                 {
106                         usage();
107                         exit(0);
108                 }
109                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
110                 {
111                         puts("pg_resetxlog (PostgreSQL) " PG_VERSION);
112                         exit(0);
113                 }
114         }
115
116
117         while ((c = getopt(argc, argv, "fl:m:no:O:x:e:")) != -1)
118         {
119                 switch (c)
120                 {
121                         case 'f':
122                                 force = true;
123                                 break;
124
125                         case 'n':
126                                 noupdate = true;
127                                 break;
128
129                         case 'e':
130                                 set_xid_epoch = strtoul(optarg, &endptr, 0);
131                                 if (endptr == optarg || *endptr != '\0')
132                                 {
133                                         fprintf(stderr, _("%s: invalid argument for option -e\n"), progname);
134                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
135                                         exit(1);
136                                 }
137                                 if (set_xid_epoch == -1)
138                                 {
139                                         fprintf(stderr, _("%s: transaction ID epoch (-e) must not be -1\n"), progname);
140                                         exit(1);
141                                 }
142                                 break;
143
144                         case 'x':
145                                 set_xid = strtoul(optarg, &endptr, 0);
146                                 if (endptr == optarg || *endptr != '\0')
147                                 {
148                                         fprintf(stderr, _("%s: invalid argument for option -x\n"), progname);
149                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
150                                         exit(1);
151                                 }
152                                 if (set_xid == 0)
153                                 {
154                                         fprintf(stderr, _("%s: transaction ID (-x) must not be 0\n"), progname);
155                                         exit(1);
156                                 }
157                                 break;
158
159                         case 'o':
160                                 set_oid = strtoul(optarg, &endptr, 0);
161                                 if (endptr == optarg || *endptr != '\0')
162                                 {
163                                         fprintf(stderr, _("%s: invalid argument for option -o\n"), progname);
164                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
165                                         exit(1);
166                                 }
167                                 if (set_oid == 0)
168                                 {
169                                         fprintf(stderr, _("%s: OID (-o) must not be 0\n"), progname);
170                                         exit(1);
171                                 }
172                                 break;
173
174                         case 'm':
175                                 set_mxid = strtoul(optarg, &endptr, 0);
176                                 if (endptr == optarg || *endptr != ',')
177                                 {
178                                         fprintf(stderr, _("%s: invalid argument for option -m\n"), progname);
179                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
180                                         exit(1);
181                                 }
182
183                                 set_oldestmxid = strtoul(endptr + 1, &endptr2, 0);
184                                 if (endptr2 == endptr + 1 || *endptr2 != '\0')
185                                 {
186                                         fprintf(stderr, _("%s: invalid argument for option -m\n"), progname);
187                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
188                                         exit(1);
189                                 }
190                                 if (set_mxid == 0)
191                                 {
192                                         fprintf(stderr, _("%s: multitransaction ID (-m) must not be 0\n"), progname);
193                                         exit(1);
194                                 }
195
196                                 /*
197                                  * XXX It'd be nice to have more sanity checks here, e.g. so
198                                  * that oldest is not wrapped around w.r.t. nextMulti.
199                                  */
200                                 if (set_oldestmxid == 0)
201                                 {
202                                         fprintf(stderr, _("%s: oldest multitransaction ID (-m) must not be 0\n"),
203                                                         progname);
204                                         exit(1);
205                                 }
206                                 break;
207
208                         case 'O':
209                                 set_mxoff = strtoul(optarg, &endptr, 0);
210                                 if (endptr == optarg || *endptr != '\0')
211                                 {
212                                         fprintf(stderr, _("%s: invalid argument for option -O\n"), progname);
213                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
214                                         exit(1);
215                                 }
216                                 if (set_mxoff == -1)
217                                 {
218                                         fprintf(stderr, _("%s: multitransaction offset (-O) must not be -1\n"), progname);
219                                         exit(1);
220                                 }
221                                 break;
222
223                         case 'l':
224                                 if (strspn(optarg, "01234567890ABCDEFabcdef") != 24)
225                                 {
226                                         fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
227                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
228                                         exit(1);
229                                 }
230                                 XLogFromFileName(optarg, &minXlogTli, &minXlogSegNo);
231                                 break;
232
233                         default:
234                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
235                                 exit(1);
236                 }
237         }
238
239         if (optind == argc)
240         {
241                 fprintf(stderr, _("%s: no data directory specified\n"), progname);
242                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
243                 exit(1);
244         }
245
246         /*
247          * Don't allow pg_resetxlog to be run as root, to avoid overwriting the
248          * ownership of files in the data directory. We need only check for root
249          * -- any other user won't have sufficient permissions to modify files in
250          * the data directory.
251          */
252 #ifndef WIN32
253         if (geteuid() == 0)
254         {
255                 fprintf(stderr, _("%s: cannot be executed by \"root\"\n"),
256                                 progname);
257                 fprintf(stderr, _("You must run %s as the PostgreSQL superuser.\n"),
258                                 progname);
259                 exit(1);
260         }
261 #endif
262
263         DataDir = argv[optind];
264
265         if (chdir(DataDir) < 0)
266         {
267                 fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"),
268                                 progname, DataDir, strerror(errno));
269                 exit(1);
270         }
271
272         /*
273          * Check for a postmaster lock file --- if there is one, refuse to
274          * proceed, on grounds we might be interfering with a live installation.
275          */
276         if ((fd = open("postmaster.pid", O_RDONLY, 0)) < 0)
277         {
278                 if (errno != ENOENT)
279                 {
280                         fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
281                                         progname, "postmaster.pid", strerror(errno));
282                         exit(1);
283                 }
284         }
285         else
286         {
287                 fprintf(stderr, _("%s: lock file \"%s\" exists\n"
288                                                   "Is a server running?  If not, delete the lock file and try again.\n"),
289                                 progname, "postmaster.pid");
290                 exit(1);
291         }
292
293         /*
294          * Attempt to read the existing pg_control file
295          */
296         if (!ReadControlFile())
297                 GuessControlValues();
298
299         /*
300          * Also look at existing segment files to set up newXlogSegNo
301          */
302         FindEndOfXLOG();
303
304         /*
305          * Adjust fields if required by switches.  (Do this now so that printout,
306          * if any, includes these values.)
307          */
308         if (set_xid_epoch != -1)
309                 ControlFile.checkPointCopy.nextXidEpoch = set_xid_epoch;
310
311         if (set_xid != 0)
312         {
313                 ControlFile.checkPointCopy.nextXid = set_xid;
314
315                 /*
316                  * For the moment, just set oldestXid to a value that will force
317                  * immediate autovacuum-for-wraparound.  It's not clear whether adding
318                  * user control of this is useful, so let's just do something that's
319                  * reasonably safe.  The magic constant here corresponds to the
320                  * maximum allowed value of autovacuum_freeze_max_age.
321                  */
322                 ControlFile.checkPointCopy.oldestXid = set_xid - 2000000000;
323                 if (ControlFile.checkPointCopy.oldestXid < FirstNormalTransactionId)
324                         ControlFile.checkPointCopy.oldestXid += FirstNormalTransactionId;
325                 ControlFile.checkPointCopy.oldestXidDB = InvalidOid;
326         }
327
328         if (set_oid != 0)
329                 ControlFile.checkPointCopy.nextOid = set_oid;
330
331         if (set_mxid != 0)
332         {
333                 ControlFile.checkPointCopy.nextMulti = set_mxid;
334
335                 ControlFile.checkPointCopy.oldestMulti = set_oldestmxid;
336                 if (ControlFile.checkPointCopy.oldestMulti < FirstMultiXactId)
337                         ControlFile.checkPointCopy.oldestMulti += FirstMultiXactId;
338                 ControlFile.checkPointCopy.oldestMultiDB = InvalidOid;
339         }
340
341         if (set_mxoff != -1)
342                 ControlFile.checkPointCopy.nextMultiOffset = set_mxoff;
343
344         if (minXlogTli > ControlFile.checkPointCopy.ThisTimeLineID)
345         {
346                 ControlFile.checkPointCopy.ThisTimeLineID = minXlogTli;
347                 ControlFile.checkPointCopy.PrevTimeLineID = minXlogTli;
348         }
349
350         if (minXlogSegNo > newXlogSegNo)
351                 newXlogSegNo = minXlogSegNo;
352
353         /*
354          * If we had to guess anything, and -f was not given, just print the
355          * guessed values and exit.  Also print if -n is given.
356          */
357         if ((guessed && !force) || noupdate)
358         {
359                 PrintControlValues(guessed);
360                 if (!noupdate)
361                 {
362                         printf(_("\nIf these values seem acceptable, use -f to force reset.\n"));
363                         exit(1);
364                 }
365                 else
366                         exit(0);
367         }
368
369         /*
370          * Don't reset from a dirty pg_control without -f, either.
371          */
372         if (ControlFile.state != DB_SHUTDOWNED && !force)
373         {
374                 printf(_("The database server was not shut down cleanly.\n"
375                            "Resetting the transaction log might cause data to be lost.\n"
376                                  "If you want to proceed anyway, use -f to force reset.\n"));
377                 exit(1);
378         }
379
380         /*
381          * Else, do the dirty deed.
382          */
383         RewriteControlFile();
384         KillExistingXLOG();
385         KillExistingArchiveStatus();
386         WriteEmptyXLOG();
387
388         printf(_("Transaction log reset\n"));
389         return 0;
390 }
391
392
393 /*
394  * Try to read the existing pg_control file.
395  *
396  * This routine is also responsible for updating old pg_control versions
397  * to the current format.  (Currently we don't do anything of the sort.)
398  */
399 static bool
400 ReadControlFile(void)
401 {
402         int                     fd;
403         int                     len;
404         char       *buffer;
405         pg_crc32        crc;
406
407         if ((fd = open(XLOG_CONTROL_FILE, O_RDONLY | PG_BINARY, 0)) < 0)
408         {
409                 /*
410                  * If pg_control is not there at all, or we can't read it, the odds
411                  * are we've been handed a bad DataDir path, so give up. User can do
412                  * "touch pg_control" to force us to proceed.
413                  */
414                 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
415                                 progname, XLOG_CONTROL_FILE, strerror(errno));
416                 if (errno == ENOENT)
417                         fprintf(stderr, _("If you are sure the data directory path is correct, execute\n"
418                                                           "  touch %s\n"
419                                                           "and try again.\n"),
420                                         XLOG_CONTROL_FILE);
421                 exit(1);
422         }
423
424         /* Use malloc to ensure we have a maxaligned buffer */
425         buffer = (char *) pg_malloc(PG_CONTROL_SIZE);
426
427         len = read(fd, buffer, PG_CONTROL_SIZE);
428         if (len < 0)
429         {
430                 fprintf(stderr, _("%s: could not read file \"%s\": %s\n"),
431                                 progname, XLOG_CONTROL_FILE, strerror(errno));
432                 exit(1);
433         }
434         close(fd);
435
436         if (len >= sizeof(ControlFileData) &&
437           ((ControlFileData *) buffer)->pg_control_version == PG_CONTROL_VERSION)
438         {
439                 /* Check the CRC. */
440                 INIT_CRC32(crc);
441                 COMP_CRC32(crc,
442                                    buffer,
443                                    offsetof(ControlFileData, crc));
444                 FIN_CRC32(crc);
445
446                 if (EQ_CRC32(crc, ((ControlFileData *) buffer)->crc))
447                 {
448                         /* Valid data... */
449                         memcpy(&ControlFile, buffer, sizeof(ControlFile));
450                         return true;
451                 }
452
453                 fprintf(stderr, _("%s: pg_control exists but has invalid CRC; proceed with caution\n"),
454                                 progname);
455                 /* We will use the data anyway, but treat it as guessed. */
456                 memcpy(&ControlFile, buffer, sizeof(ControlFile));
457                 guessed = true;
458                 return true;
459         }
460
461         /* Looks like it's a mess. */
462         fprintf(stderr, _("%s: pg_control exists but is broken or unknown version; ignoring it\n"),
463                         progname);
464         return false;
465 }
466
467
468 /*
469  * Guess at pg_control values when we can't read the old ones.
470  */
471 static void
472 GuessControlValues(void)
473 {
474         uint64          sysidentifier;
475         struct timeval tv;
476
477         /*
478          * Set up a completely default set of pg_control values.
479          */
480         guessed = true;
481         memset(&ControlFile, 0, sizeof(ControlFile));
482
483         ControlFile.pg_control_version = PG_CONTROL_VERSION;
484         ControlFile.catalog_version_no = CATALOG_VERSION_NO;
485
486         /*
487          * Create a new unique installation identifier, since we can no longer use
488          * any old XLOG records.  See notes in xlog.c about the algorithm.
489          */
490         gettimeofday(&tv, NULL);
491         sysidentifier = ((uint64) tv.tv_sec) << 32;
492         sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
493
494         ControlFile.system_identifier = sysidentifier;
495
496         ControlFile.checkPointCopy.redo = SizeOfXLogLongPHD;
497         ControlFile.checkPointCopy.ThisTimeLineID = 1;
498         ControlFile.checkPointCopy.PrevTimeLineID = 1;
499         ControlFile.checkPointCopy.fullPageWrites = false;
500         ControlFile.checkPointCopy.nextXidEpoch = 0;
501         ControlFile.checkPointCopy.nextXid = FirstNormalTransactionId;
502         ControlFile.checkPointCopy.nextOid = FirstBootstrapObjectId;
503         ControlFile.checkPointCopy.nextMulti = FirstMultiXactId;
504         ControlFile.checkPointCopy.nextMultiOffset = 0;
505         ControlFile.checkPointCopy.oldestXid = FirstNormalTransactionId;
506         ControlFile.checkPointCopy.oldestXidDB = InvalidOid;
507         ControlFile.checkPointCopy.oldestMulti = FirstMultiXactId;
508         ControlFile.checkPointCopy.oldestMultiDB = InvalidOid;
509         ControlFile.checkPointCopy.time = (pg_time_t) time(NULL);
510         ControlFile.checkPointCopy.oldestActiveXid = InvalidTransactionId;
511
512         ControlFile.state = DB_SHUTDOWNED;
513         ControlFile.time = (pg_time_t) time(NULL);
514         ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
515         ControlFile.unloggedLSN = 1;
516
517         /* minRecoveryPoint, backupStartPoint and backupEndPoint can be left zero */
518
519         ControlFile.wal_level = WAL_LEVEL_MINIMAL;
520         ControlFile.MaxConnections = 100;
521         ControlFile.max_prepared_xacts = 0;
522         ControlFile.max_locks_per_xact = 64;
523
524         ControlFile.maxAlign = MAXIMUM_ALIGNOF;
525         ControlFile.floatFormat = FLOATFORMAT_VALUE;
526         ControlFile.blcksz = BLCKSZ;
527         ControlFile.relseg_size = RELSEG_SIZE;
528         ControlFile.xlog_blcksz = XLOG_BLCKSZ;
529         ControlFile.xlog_seg_size = XLOG_SEG_SIZE;
530         ControlFile.nameDataLen = NAMEDATALEN;
531         ControlFile.indexMaxKeys = INDEX_MAX_KEYS;
532         ControlFile.toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
533 #ifdef HAVE_INT64_TIMESTAMP
534         ControlFile.enableIntTimes = true;
535 #else
536         ControlFile.enableIntTimes = false;
537 #endif
538         ControlFile.float4ByVal = FLOAT4PASSBYVAL;
539         ControlFile.float8ByVal = FLOAT8PASSBYVAL;
540
541         /*
542          * XXX eventually, should try to grovel through old XLOG to develop more
543          * accurate values for TimeLineID, nextXID, etc.
544          */
545 }
546
547
548 /*
549  * Print the guessed pg_control values when we had to guess.
550  *
551  * NB: this display should be just those fields that will not be
552  * reset by RewriteControlFile().
553  */
554 static void
555 PrintControlValues(bool guessed)
556 {
557         char            sysident_str[32];
558         char            fname[MAXFNAMELEN];
559
560         if (guessed)
561                 printf(_("Guessed pg_control values:\n\n"));
562         else
563                 printf(_("pg_control values:\n\n"));
564
565         /*
566          * Format system_identifier separately to keep platform-dependent format
567          * code out of the translatable message string.
568          */
569         snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
570                          ControlFile.system_identifier);
571
572         XLogFileName(fname, ControlFile.checkPointCopy.ThisTimeLineID, newXlogSegNo);
573
574         printf(_("First log segment after reset:        %s\n"),
575                    fname);
576         printf(_("pg_control version number:            %u\n"),
577                    ControlFile.pg_control_version);
578         printf(_("Catalog version number:               %u\n"),
579                    ControlFile.catalog_version_no);
580         printf(_("Database system identifier:           %s\n"),
581                    sysident_str);
582         printf(_("Latest checkpoint's TimeLineID:       %u\n"),
583                    ControlFile.checkPointCopy.ThisTimeLineID);
584         printf(_("Latest checkpoint's full_page_writes: %s\n"),
585                    ControlFile.checkPointCopy.fullPageWrites ? _("on") : _("off"));
586         printf(_("Latest checkpoint's NextXID:          %u/%u\n"),
587                    ControlFile.checkPointCopy.nextXidEpoch,
588                    ControlFile.checkPointCopy.nextXid);
589         printf(_("Latest checkpoint's NextOID:          %u\n"),
590                    ControlFile.checkPointCopy.nextOid);
591         printf(_("Latest checkpoint's NextMultiXactId:  %u\n"),
592                    ControlFile.checkPointCopy.nextMulti);
593         printf(_("Latest checkpoint's NextMultiOffset:  %u\n"),
594                    ControlFile.checkPointCopy.nextMultiOffset);
595         printf(_("Latest checkpoint's oldestXID:        %u\n"),
596                    ControlFile.checkPointCopy.oldestXid);
597         printf(_("Latest checkpoint's oldestXID's DB:   %u\n"),
598                    ControlFile.checkPointCopy.oldestXidDB);
599         printf(_("Latest checkpoint's oldestActiveXID:  %u\n"),
600                    ControlFile.checkPointCopy.oldestActiveXid);
601         printf(_("Latest checkpoint's oldestMultiXid:   %u\n"),
602                    ControlFile.checkPointCopy.oldestMulti);
603         printf(_("Latest checkpoint's oldestMulti's DB: %u\n"),
604                    ControlFile.checkPointCopy.oldestMultiDB);
605         printf(_("Maximum data alignment:               %u\n"),
606                    ControlFile.maxAlign);
607         /* we don't print floatFormat since can't say much useful about it */
608         printf(_("Database block size:                  %u\n"),
609                    ControlFile.blcksz);
610         printf(_("Blocks per segment of large relation: %u\n"),
611                    ControlFile.relseg_size);
612         printf(_("WAL block size:                       %u\n"),
613                    ControlFile.xlog_blcksz);
614         printf(_("Bytes per WAL segment:                %u\n"),
615                    ControlFile.xlog_seg_size);
616         printf(_("Maximum length of identifiers:        %u\n"),
617                    ControlFile.nameDataLen);
618         printf(_("Maximum columns in an index:          %u\n"),
619                    ControlFile.indexMaxKeys);
620         printf(_("Maximum size of a TOAST chunk:        %u\n"),
621                    ControlFile.toast_max_chunk_size);
622         printf(_("Date/time type storage:               %s\n"),
623                    (ControlFile.enableIntTimes ? _("64-bit integers") : _("floating-point numbers")));
624         printf(_("Float4 argument passing:              %s\n"),
625                    (ControlFile.float4ByVal ? _("by value") : _("by reference")));
626         printf(_("Float8 argument passing:              %s\n"),
627                    (ControlFile.float8ByVal ? _("by value") : _("by reference")));
628         printf(_("Data page checksum version:           %u\n"),
629                    ControlFile.data_checksum_version);
630 }
631
632
633 /*
634  * Write out the new pg_control file.
635  */
636 static void
637 RewriteControlFile(void)
638 {
639         int                     fd;
640         char            buffer[PG_CONTROL_SIZE];                /* need not be aligned */
641
642         /*
643          * Adjust fields as needed to force an empty XLOG starting at
644          * newXlogSegNo.
645          */
646         XLogSegNoOffsetToRecPtr(newXlogSegNo, SizeOfXLogLongPHD,
647                                                         ControlFile.checkPointCopy.redo);
648         ControlFile.checkPointCopy.time = (pg_time_t) time(NULL);
649
650         ControlFile.state = DB_SHUTDOWNED;
651         ControlFile.time = (pg_time_t) time(NULL);
652         ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
653         ControlFile.prevCheckPoint = 0;
654         ControlFile.minRecoveryPoint = 0;
655         ControlFile.minRecoveryPointTLI = 0;
656         ControlFile.backupStartPoint = 0;
657         ControlFile.backupEndPoint = 0;
658         ControlFile.backupEndRequired = false;
659
660         /*
661          * Force the defaults for max_* settings. The values don't really matter
662          * as long as wal_level='minimal'; the postmaster will reset these fields
663          * anyway at startup.
664          */
665         ControlFile.wal_level = WAL_LEVEL_MINIMAL;
666         ControlFile.MaxConnections = 100;
667         ControlFile.max_prepared_xacts = 0;
668         ControlFile.max_locks_per_xact = 64;
669
670         /* Now we can force the recorded xlog seg size to the right thing. */
671         ControlFile.xlog_seg_size = XLogSegSize;
672
673         /* Contents are protected with a CRC */
674         INIT_CRC32(ControlFile.crc);
675         COMP_CRC32(ControlFile.crc,
676                            (char *) &ControlFile,
677                            offsetof(ControlFileData, crc));
678         FIN_CRC32(ControlFile.crc);
679
680         /*
681          * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
682          * excess over sizeof(ControlFileData).  This reduces the odds of
683          * premature-EOF errors when reading pg_control.  We'll still fail when we
684          * check the contents of the file, but hopefully with a more specific
685          * error than "couldn't read pg_control".
686          */
687         if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
688         {
689                 fprintf(stderr,
690                                 _("%s: internal error -- sizeof(ControlFileData) is too large ... fix PG_CONTROL_SIZE\n"),
691                                 progname);
692                 exit(1);
693         }
694
695         memset(buffer, 0, PG_CONTROL_SIZE);
696         memcpy(buffer, &ControlFile, sizeof(ControlFileData));
697
698         unlink(XLOG_CONTROL_FILE);
699
700         fd = open(XLOG_CONTROL_FILE,
701                           O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
702                           S_IRUSR | S_IWUSR);
703         if (fd < 0)
704         {
705                 fprintf(stderr, _("%s: could not create pg_control file: %s\n"),
706                                 progname, strerror(errno));
707                 exit(1);
708         }
709
710         errno = 0;
711         if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
712         {
713                 /* if write didn't set errno, assume problem is no disk space */
714                 if (errno == 0)
715                         errno = ENOSPC;
716                 fprintf(stderr, _("%s: could not write pg_control file: %s\n"),
717                                 progname, strerror(errno));
718                 exit(1);
719         }
720
721         if (fsync(fd) != 0)
722         {
723                 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
724                 exit(1);
725         }
726
727         close(fd);
728 }
729
730
731 /*
732  * Scan existing XLOG files and determine the highest existing WAL address
733  *
734  * On entry, ControlFile.checkPointCopy.redo and ControlFile.xlog_seg_size
735  * are assumed valid (note that we allow the old xlog seg size to differ
736  * from what we're using).  On exit, newXlogId and newXlogSeg are set to
737  * suitable values for the beginning of replacement WAL (in our seg size).
738  */
739 static void
740 FindEndOfXLOG(void)
741 {
742         DIR                *xldir;
743         struct dirent *xlde;
744         uint64          segs_per_xlogid;
745         uint64          xlogbytepos;
746
747         /*
748          * Initialize the max() computation using the last checkpoint address from
749          * old pg_control.      Note that for the moment we are working with segment
750          * numbering according to the old xlog seg size.
751          */
752         segs_per_xlogid = (UINT64CONST(0x0000000100000000) / ControlFile.xlog_seg_size);
753         newXlogSegNo = ControlFile.checkPointCopy.redo / ControlFile.xlog_seg_size;
754
755         /*
756          * Scan the pg_xlog directory to find existing WAL segment files. We
757          * assume any present have been used; in most scenarios this should be
758          * conservative, because of xlog.c's attempts to pre-create files.
759          */
760         xldir = opendir(XLOGDIR);
761         if (xldir == NULL)
762         {
763                 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
764                                 progname, XLOGDIR, strerror(errno));
765                 exit(1);
766         }
767
768         errno = 0;
769         while ((xlde = readdir(xldir)) != NULL)
770         {
771                 if (strlen(xlde->d_name) == 24 &&
772                         strspn(xlde->d_name, "0123456789ABCDEF") == 24)
773                 {
774                         unsigned int tli,
775                                                 log,
776                                                 seg;
777                         XLogSegNo       segno;
778
779                         sscanf(xlde->d_name, "%08X%08X%08X", &tli, &log, &seg);
780                         segno = ((uint64) log) * segs_per_xlogid + seg;
781
782                         /*
783                          * Note: we take the max of all files found, regardless of their
784                          * timelines.  Another possibility would be to ignore files of
785                          * timelines other than the target TLI, but this seems safer.
786                          * Better too large a result than too small...
787                          */
788                         if (segno > newXlogSegNo)
789                                 newXlogSegNo = segno;
790                 }
791                 errno = 0;
792         }
793 #ifdef WIN32
794
795         /*
796          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
797          * released version
798          */
799         if (GetLastError() == ERROR_NO_MORE_FILES)
800                 errno = 0;
801 #endif
802
803         if (errno)
804         {
805                 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
806                                 progname, XLOGDIR, strerror(errno));
807                 exit(1);
808         }
809         closedir(xldir);
810
811         /*
812          * Finally, convert to new xlog seg size, and advance by one to ensure we
813          * are in virgin territory.
814          */
815         xlogbytepos = newXlogSegNo * ControlFile.xlog_seg_size;
816         newXlogSegNo = (xlogbytepos + XLogSegSize - 1) / XLogSegSize;
817         newXlogSegNo++;
818 }
819
820
821 /*
822  * Remove existing XLOG files
823  */
824 static void
825 KillExistingXLOG(void)
826 {
827         DIR                *xldir;
828         struct dirent *xlde;
829         char            path[MAXPGPATH];
830
831         xldir = opendir(XLOGDIR);
832         if (xldir == NULL)
833         {
834                 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
835                                 progname, XLOGDIR, strerror(errno));
836                 exit(1);
837         }
838
839         errno = 0;
840         while ((xlde = readdir(xldir)) != NULL)
841         {
842                 if (strlen(xlde->d_name) == 24 &&
843                         strspn(xlde->d_name, "0123456789ABCDEF") == 24)
844                 {
845                         snprintf(path, MAXPGPATH, "%s/%s", XLOGDIR, xlde->d_name);
846                         if (unlink(path) < 0)
847                         {
848                                 fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
849                                                 progname, path, strerror(errno));
850                                 exit(1);
851                         }
852                 }
853                 errno = 0;
854         }
855 #ifdef WIN32
856
857         /*
858          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
859          * released version
860          */
861         if (GetLastError() == ERROR_NO_MORE_FILES)
862                 errno = 0;
863 #endif
864
865         if (errno)
866         {
867                 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
868                                 progname, XLOGDIR, strerror(errno));
869                 exit(1);
870         }
871         closedir(xldir);
872 }
873
874
875 /*
876  * Remove existing archive status files
877  */
878 static void
879 KillExistingArchiveStatus(void)
880 {
881         DIR                *xldir;
882         struct dirent *xlde;
883         char            path[MAXPGPATH];
884
885 #define ARCHSTATDIR XLOGDIR "/archive_status"
886
887         xldir = opendir(ARCHSTATDIR);
888         if (xldir == NULL)
889         {
890                 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
891                                 progname, ARCHSTATDIR, strerror(errno));
892                 exit(1);
893         }
894
895         errno = 0;
896         while ((xlde = readdir(xldir)) != NULL)
897         {
898                 if (strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
899                         (strcmp(xlde->d_name + 24, ".ready") == 0 ||
900                          strcmp(xlde->d_name + 24, ".done") == 0))
901                 {
902                         snprintf(path, MAXPGPATH, "%s/%s", ARCHSTATDIR, xlde->d_name);
903                         if (unlink(path) < 0)
904                         {
905                                 fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
906                                                 progname, path, strerror(errno));
907                                 exit(1);
908                         }
909                 }
910                 errno = 0;
911         }
912 #ifdef WIN32
913
914         /*
915          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
916          * released version
917          */
918         if (GetLastError() == ERROR_NO_MORE_FILES)
919                 errno = 0;
920 #endif
921
922         if (errno)
923         {
924                 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
925                                 progname, ARCHSTATDIR, strerror(errno));
926                 exit(1);
927         }
928         closedir(xldir);
929 }
930
931
932 /*
933  * Write an empty XLOG file, containing only the checkpoint record
934  * already set up in ControlFile.
935  */
936 static void
937 WriteEmptyXLOG(void)
938 {
939         char       *buffer;
940         XLogPageHeader page;
941         XLogLongPageHeader longpage;
942         XLogRecord *record;
943         pg_crc32        crc;
944         char            path[MAXPGPATH];
945         int                     fd;
946         int                     nbytes;
947
948         /* Use malloc() to ensure buffer is MAXALIGNED */
949         buffer = (char *) pg_malloc(XLOG_BLCKSZ);
950         page = (XLogPageHeader) buffer;
951         memset(buffer, 0, XLOG_BLCKSZ);
952
953         /* Set up the XLOG page header */
954         page->xlp_magic = XLOG_PAGE_MAGIC;
955         page->xlp_info = XLP_LONG_HEADER;
956         page->xlp_tli = ControlFile.checkPointCopy.ThisTimeLineID;
957         page->xlp_pageaddr = ControlFile.checkPointCopy.redo - SizeOfXLogLongPHD;
958         longpage = (XLogLongPageHeader) page;
959         longpage->xlp_sysid = ControlFile.system_identifier;
960         longpage->xlp_seg_size = XLogSegSize;
961         longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
962
963         /* Insert the initial checkpoint record */
964         record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
965         record->xl_prev = 0;
966         record->xl_xid = InvalidTransactionId;
967         record->xl_tot_len = SizeOfXLogRecord + sizeof(CheckPoint);
968         record->xl_len = sizeof(CheckPoint);
969         record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
970         record->xl_rmid = RM_XLOG_ID;
971         memcpy(XLogRecGetData(record), &ControlFile.checkPointCopy,
972                    sizeof(CheckPoint));
973
974         INIT_CRC32(crc);
975         COMP_CRC32(crc, &ControlFile.checkPointCopy, sizeof(CheckPoint));
976         COMP_CRC32(crc, (char *) record, offsetof(XLogRecord, xl_crc));
977         FIN_CRC32(crc);
978         record->xl_crc = crc;
979
980         /* Write the first page */
981         XLogFilePath(path, ControlFile.checkPointCopy.ThisTimeLineID, newXlogSegNo);
982
983         unlink(path);
984
985         fd = open(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
986                           S_IRUSR | S_IWUSR);
987         if (fd < 0)
988         {
989                 fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
990                                 progname, path, strerror(errno));
991                 exit(1);
992         }
993
994         errno = 0;
995         if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
996         {
997                 /* if write didn't set errno, assume problem is no disk space */
998                 if (errno == 0)
999                         errno = ENOSPC;
1000                 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
1001                                 progname, path, strerror(errno));
1002                 exit(1);
1003         }
1004
1005         /* Fill the rest of the file with zeroes */
1006         memset(buffer, 0, XLOG_BLCKSZ);
1007         for (nbytes = XLOG_BLCKSZ; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
1008         {
1009                 errno = 0;
1010                 if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
1011                 {
1012                         if (errno == 0)
1013                                 errno = ENOSPC;
1014                         fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
1015                                         progname, path, strerror(errno));
1016                         exit(1);
1017                 }
1018         }
1019
1020         if (fsync(fd) != 0)
1021         {
1022                 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
1023                 exit(1);
1024         }
1025
1026         close(fd);
1027 }
1028
1029
1030 static void
1031 usage(void)
1032 {
1033         printf(_("%s resets the PostgreSQL transaction log.\n\n"), progname);
1034         printf(_("Usage:\n  %s [OPTION]... DATADIR\n\n"), progname);
1035         printf(_("Options:\n"));
1036         printf(_("  -e XIDEPOCH      set next transaction ID epoch\n"));
1037         printf(_("  -f               force update to be done\n"));
1038         printf(_("  -l XLOGFILE      force minimum WAL starting location for new transaction log\n"));
1039         printf(_("  -m XID,XID       set next and oldest multitransaction ID\n"));
1040         printf(_("  -n               no update, just show extracted control values (for testing)\n"));
1041         printf(_("  -o OID           set next OID\n"));
1042         printf(_("  -O OFFSET        set next multitransaction offset\n"));
1043         printf(_("  -V, --version    output version information, then exit\n"));
1044         printf(_("  -x XID           set next transaction ID\n"));
1045         printf(_("  -?, --help       show this help, then exit\n"));
1046         printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1047 }