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