]> granicus.if.org Git - postgresql/blob - src/bin/pg_resetxlog/pg_resetxlog.c
pgindent run for 8.2.
[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-2006, 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.53 2006/10/04 00:30:05 momjian Exp $
27  *
28  *-------------------------------------------------------------------------
29  */
30 #include "postgres.h"
31
32 #include <dirent.h>
33 #include <fcntl.h>
34 #include <locale.h>
35 #include <sys/stat.h>
36 #include <sys/time.h>
37 #include <time.h>
38 #include <unistd.h>
39 #ifdef HAVE_GETOPT_H
40 #include <getopt.h>
41 #endif
42
43 #include "access/transam.h"
44 #include "access/multixact.h"
45 #include "access/xlog_internal.h"
46 #include "catalog/catversion.h"
47 #include "catalog/pg_control.h"
48
49 extern int      optind;
50 extern char *optarg;
51
52
53 static ControlFileData ControlFile;             /* pg_control values */
54 static uint32 newXlogId,
55                         newXlogSeg;                     /* ID/Segment of new XLOG segment */
56 static bool guessed = false;    /* T if we had to guess at any values */
57 static const char *progname;
58
59 static bool ReadControlFile(void);
60 static void GuessControlValues(void);
61 static void PrintControlValues(bool guessed);
62 static void RewriteControlFile(void);
63 static void KillExistingXLOG(void);
64 static void WriteEmptyXLOG(void);
65 static void usage(void);
66
67
68 int
69 main(int argc, char *argv[])
70 {
71         int                     c;
72         bool            force = false;
73         bool            noupdate = false;
74         uint32          set_xid_epoch = -1;
75         TransactionId set_xid = 0;
76         Oid                     set_oid = 0;
77         MultiXactId set_mxid = 0;
78         MultiXactOffset set_mxoff = -1;
79         uint32          minXlogTli = 0,
80                                 minXlogId = 0,
81                                 minXlogSeg = 0;
82         char       *endptr;
83         char       *endptr2;
84         char       *endptr3;
85         char       *DataDir;
86         int                     fd;
87         char            path[MAXPGPATH];
88
89         set_pglocale_pgservice(argv[0], "pg_resetxlog");
90
91         progname = get_progname(argv[0]);
92
93         if (argc > 1)
94         {
95                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
96                 {
97                         usage();
98                         exit(0);
99                 }
100                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
101                 {
102                         puts("pg_resetxlog (PostgreSQL) " PG_VERSION);
103                         exit(0);
104                 }
105         }
106
107
108         while ((c = getopt(argc, argv, "fl:m:no:O:x:e:")) != -1)
109         {
110                 switch (c)
111                 {
112                         case 'f':
113                                 force = true;
114                                 break;
115
116                         case 'n':
117                                 noupdate = true;
118                                 break;
119
120                         case 'e':
121                                 set_xid_epoch = strtoul(optarg, &endptr, 0);
122                                 if (endptr == optarg || *endptr != '\0')
123                                 {
124                                         fprintf(stderr, _("%s: invalid argument for option -e\n"), progname);
125                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
126                                         exit(1);
127                                 }
128                                 if (set_xid_epoch == -1)
129                                 {
130                                         fprintf(stderr, _("%s: transaction ID epoch (-e) must not be -1\n"), progname);
131                                         exit(1);
132                                 }
133                                 break;
134
135                         case 'x':
136                                 set_xid = strtoul(optarg, &endptr, 0);
137                                 if (endptr == optarg || *endptr != '\0')
138                                 {
139                                         fprintf(stderr, _("%s: invalid argument for option -x\n"), progname);
140                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
141                                         exit(1);
142                                 }
143                                 if (set_xid == 0)
144                                 {
145                                         fprintf(stderr, _("%s: transaction ID (-x) must not be 0\n"), progname);
146                                         exit(1);
147                                 }
148                                 break;
149
150                         case 'o':
151                                 set_oid = strtoul(optarg, &endptr, 0);
152                                 if (endptr == optarg || *endptr != '\0')
153                                 {
154                                         fprintf(stderr, _("%s: invalid argument for option -o\n"), progname);
155                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
156                                         exit(1);
157                                 }
158                                 if (set_oid == 0)
159                                 {
160                                         fprintf(stderr, _("%s: OID (-o) must not be 0\n"), progname);
161                                         exit(1);
162                                 }
163                                 break;
164
165                         case 'm':
166                                 set_mxid = strtoul(optarg, &endptr, 0);
167                                 if (endptr == optarg || *endptr != '\0')
168                                 {
169                                         fprintf(stderr, _("%s: invalid argument for option -m\n"), progname);
170                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
171                                         exit(1);
172                                 }
173                                 if (set_mxid == 0)
174                                 {
175                                         fprintf(stderr, _("%s: multitransaction ID (-m) must not be 0\n"), progname);
176                                         exit(1);
177                                 }
178                                 break;
179
180                         case 'O':
181                                 set_mxoff = strtoul(optarg, &endptr, 0);
182                                 if (endptr == optarg || *endptr != '\0')
183                                 {
184                                         fprintf(stderr, _("%s: invalid argument for option -O\n"), progname);
185                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
186                                         exit(1);
187                                 }
188                                 if (set_mxoff == -1)
189                                 {
190                                         fprintf(stderr, _("%s: multitransaction offset (-O) must not be -1\n"), progname);
191                                         exit(1);
192                                 }
193                                 break;
194
195                         case 'l':
196                                 minXlogTli = strtoul(optarg, &endptr, 0);
197                                 if (endptr == optarg || *endptr != ',')
198                                 {
199                                         fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
200                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
201                                         exit(1);
202                                 }
203                                 minXlogId = strtoul(endptr + 1, &endptr2, 0);
204                                 if (endptr2 == endptr + 1 || *endptr2 != ',')
205                                 {
206                                         fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
207                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
208                                         exit(1);
209                                 }
210                                 minXlogSeg = strtoul(endptr2 + 1, &endptr3, 0);
211                                 if (endptr3 == endptr2 + 1 || *endptr3 != '\0')
212                                 {
213                                         fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
214                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
215                                         exit(1);
216                                 }
217                                 break;
218
219                         default:
220                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
221                                 exit(1);
222                 }
223         }
224
225         if (optind == argc)
226         {
227                 fprintf(stderr, _("%s: no data directory specified\n"), progname);
228                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
229                 exit(1);
230         }
231
232         /*
233          * Don't allow pg_resetxlog to be run as root, to avoid overwriting the
234          * ownership of files in the data directory. We need only check for root
235          * -- any other user won't have sufficient permissions to modify files in
236          * the data directory.
237          */
238 #ifndef WIN32
239         if (geteuid() == 0)
240         {
241                 fprintf(stderr, _("%s: cannot be executed by \"root\"\n"),
242                                 progname);
243                 fprintf(stderr, _("You must run %s as the PostgreSQL superuser.\n"),
244                                 progname);
245                 exit(1);
246         }
247 #endif
248
249         DataDir = argv[optind];
250
251         if (chdir(DataDir) < 0)
252         {
253                 fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"),
254                                 progname, DataDir, strerror(errno));
255                 exit(1);
256         }
257
258         /*
259          * Check for a postmaster lock file --- if there is one, refuse to
260          * proceed, on grounds we might be interfering with a live installation.
261          */
262         snprintf(path, MAXPGPATH, "%s/postmaster.pid", DataDir);
263
264         if ((fd = open(path, O_RDONLY, 0)) < 0)
265         {
266                 if (errno != ENOENT)
267                 {
268                         fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"), progname, path, strerror(errno));
269                         exit(1);
270                 }
271         }
272         else
273         {
274                 fprintf(stderr, _("%s: lock file \"%s\" exists\n"
275                                                   "Is a server running?  If not, delete the lock file and try again.\n"),
276                                 progname, path);
277                 exit(1);
278         }
279
280         /*
281          * Attempt to read the existing pg_control file
282          */
283         if (!ReadControlFile())
284                 GuessControlValues();
285
286         /*
287          * Adjust fields if required by switches.  (Do this now so that printout,
288          * if any, includes these values.)
289          */
290         if (set_xid_epoch != -1)
291                 ControlFile.checkPointCopy.nextXidEpoch = set_xid_epoch;
292
293         if (set_xid != 0)
294                 ControlFile.checkPointCopy.nextXid = set_xid;
295
296         if (set_oid != 0)
297                 ControlFile.checkPointCopy.nextOid = set_oid;
298
299         if (set_mxid != 0)
300                 ControlFile.checkPointCopy.nextMulti = set_mxid;
301
302         if (set_mxoff != -1)
303                 ControlFile.checkPointCopy.nextMultiOffset = set_mxoff;
304
305         if (minXlogTli > ControlFile.checkPointCopy.ThisTimeLineID)
306                 ControlFile.checkPointCopy.ThisTimeLineID = minXlogTli;
307
308         if (minXlogId > ControlFile.logId ||
309                 (minXlogId == ControlFile.logId &&
310                  minXlogSeg > ControlFile.logSeg))
311         {
312                 ControlFile.logId = minXlogId;
313                 ControlFile.logSeg = minXlogSeg;
314         }
315
316         /*
317          * If we had to guess anything, and -f was not given, just print the
318          * guessed values and exit.  Also print if -n is given.
319          */
320         if ((guessed && !force) || noupdate)
321         {
322                 PrintControlValues(guessed);
323                 if (!noupdate)
324                 {
325                         printf(_("\nIf these values seem acceptable, use -f to force reset.\n"));
326                         exit(1);
327                 }
328                 else
329                         exit(0);
330         }
331
332         /*
333          * Don't reset from a dirty pg_control without -f, either.
334          */
335         if (ControlFile.state != DB_SHUTDOWNED && !force)
336         {
337                 printf(_("The database server was not shut down cleanly.\n"
338                                  "Resetting the transaction log may cause data to be lost.\n"
339                                  "If you want to proceed anyway, use -f to force reset.\n"));
340                 exit(1);
341         }
342
343         /*
344          * Else, do the dirty deed.
345          */
346         RewriteControlFile();
347         KillExistingXLOG();
348         WriteEmptyXLOG();
349
350         printf(_("Transaction log reset\n"));
351         return 0;
352 }
353
354
355 /*
356  * Try to read the existing pg_control file.
357  *
358  * This routine is also responsible for updating old pg_control versions
359  * to the current format.  (Currently we don't do anything of the sort.)
360  */
361 static bool
362 ReadControlFile(void)
363 {
364         int                     fd;
365         int                     len;
366         char       *buffer;
367         pg_crc32        crc;
368
369         if ((fd = open(XLOG_CONTROL_FILE, O_RDONLY, 0)) < 0)
370         {
371                 /*
372                  * If pg_control is not there at all, or we can't read it, the odds
373                  * are we've been handed a bad DataDir path, so give up. User can do
374                  * "touch pg_control" to force us to proceed.
375                  */
376                 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
377                                 progname, XLOG_CONTROL_FILE, strerror(errno));
378                 if (errno == ENOENT)
379                         fprintf(stderr, _("If you are sure the data directory path is correct, execute\n"
380                                                           "  touch %s\n"
381                                                           "and try again.\n"),
382                                         XLOG_CONTROL_FILE);
383                 exit(1);
384         }
385
386         /* Use malloc to ensure we have a maxaligned buffer */
387         buffer = (char *) malloc(PG_CONTROL_SIZE);
388
389         len = read(fd, buffer, PG_CONTROL_SIZE);
390         if (len < 0)
391         {
392                 fprintf(stderr, _("%s: could not read file \"%s\": %s\n"),
393                                 progname, XLOG_CONTROL_FILE, strerror(errno));
394                 exit(1);
395         }
396         close(fd);
397
398         if (len >= sizeof(ControlFileData) &&
399           ((ControlFileData *) buffer)->pg_control_version == PG_CONTROL_VERSION)
400         {
401                 /* Check the CRC. */
402                 INIT_CRC32(crc);
403                 COMP_CRC32(crc,
404                                    buffer,
405                                    offsetof(ControlFileData, crc));
406                 FIN_CRC32(crc);
407
408                 if (EQ_CRC32(crc, ((ControlFileData *) buffer)->crc))
409                 {
410                         /* Valid data... */
411                         memcpy(&ControlFile, buffer, sizeof(ControlFile));
412                         return true;
413                 }
414
415                 fprintf(stderr, _("%s: pg_control exists but has invalid CRC; proceed with caution\n"),
416                                 progname);
417                 /* We will use the data anyway, but treat it as guessed. */
418                 memcpy(&ControlFile, buffer, sizeof(ControlFile));
419                 guessed = true;
420                 return true;
421         }
422
423         /* Looks like it's a mess. */
424         fprintf(stderr, _("%s: pg_control exists but is broken or unknown version; ignoring it\n"),
425                         progname);
426         return false;
427 }
428
429
430 /*
431  * Guess at pg_control values when we can't read the old ones.
432  */
433 static void
434 GuessControlValues(void)
435 {
436         uint64          sysidentifier;
437         struct timeval tv;
438         char       *localeptr;
439
440         /*
441          * Set up a completely default set of pg_control values.
442          */
443         guessed = true;
444         memset(&ControlFile, 0, sizeof(ControlFile));
445
446         ControlFile.pg_control_version = PG_CONTROL_VERSION;
447         ControlFile.catalog_version_no = CATALOG_VERSION_NO;
448
449         /*
450          * Create a new unique installation identifier, since we can no longer use
451          * any old XLOG records.  See notes in xlog.c about the algorithm.
452          */
453         gettimeofday(&tv, NULL);
454         sysidentifier = ((uint64) tv.tv_sec) << 32;
455         sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
456
457         ControlFile.system_identifier = sysidentifier;
458
459         ControlFile.checkPointCopy.redo.xlogid = 0;
460         ControlFile.checkPointCopy.redo.xrecoff = SizeOfXLogLongPHD;
461         ControlFile.checkPointCopy.undo = ControlFile.checkPointCopy.redo;
462         ControlFile.checkPointCopy.ThisTimeLineID = 1;
463         ControlFile.checkPointCopy.nextXidEpoch = 0;
464         ControlFile.checkPointCopy.nextXid = (TransactionId) 514;       /* XXX */
465         ControlFile.checkPointCopy.nextOid = FirstBootstrapObjectId;
466         ControlFile.checkPointCopy.nextMulti = FirstMultiXactId;
467         ControlFile.checkPointCopy.nextMultiOffset = 0;
468         ControlFile.checkPointCopy.time = time(NULL);
469
470         ControlFile.state = DB_SHUTDOWNED;
471         ControlFile.time = time(NULL);
472         ControlFile.logId = 0;
473         ControlFile.logSeg = 1;
474         ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
475
476         ControlFile.maxAlign = MAXIMUM_ALIGNOF;
477         ControlFile.floatFormat = FLOATFORMAT_VALUE;
478         ControlFile.blcksz = BLCKSZ;
479         ControlFile.relseg_size = RELSEG_SIZE;
480         ControlFile.xlog_blcksz = XLOG_BLCKSZ;
481         ControlFile.xlog_seg_size = XLOG_SEG_SIZE;
482         ControlFile.nameDataLen = NAMEDATALEN;
483         ControlFile.indexMaxKeys = INDEX_MAX_KEYS;
484 #ifdef HAVE_INT64_TIMESTAMP
485         ControlFile.enableIntTimes = TRUE;
486 #else
487         ControlFile.enableIntTimes = FALSE;
488 #endif
489         ControlFile.localeBuflen = LOCALE_NAME_BUFLEN;
490
491         localeptr = setlocale(LC_COLLATE, "");
492         if (!localeptr)
493         {
494                 fprintf(stderr, _("%s: invalid LC_COLLATE setting\n"), progname);
495                 exit(1);
496         }
497         StrNCpy(ControlFile.lc_collate, localeptr, LOCALE_NAME_BUFLEN);
498         localeptr = setlocale(LC_CTYPE, "");
499         if (!localeptr)
500         {
501                 fprintf(stderr, _("%s: invalid LC_CTYPE setting\n"), progname);
502                 exit(1);
503         }
504         StrNCpy(ControlFile.lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
505
506         /*
507          * XXX eventually, should try to grovel through old XLOG to develop more
508          * accurate values for TimeLineID, nextXID, etc.
509          */
510 }
511
512
513 /*
514  * Print the guessed pg_control values when we had to guess.
515  *
516  * NB: this display should be just those fields that will not be
517  * reset by RewriteControlFile().
518  */
519 static void
520 PrintControlValues(bool guessed)
521 {
522         char            sysident_str[32];
523
524         if (guessed)
525                 printf(_("Guessed pg_control values:\n\n"));
526         else
527                 printf(_("pg_control values:\n\n"));
528
529         /*
530          * Format system_identifier separately to keep platform-dependent format
531          * code out of the translatable message string.
532          */
533         snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
534                          ControlFile.system_identifier);
535
536         printf(_("pg_control version number:            %u\n"),
537                    ControlFile.pg_control_version);
538         printf(_("Catalog version number:               %u\n"),
539                    ControlFile.catalog_version_no);
540         printf(_("Database system identifier:           %s\n"),
541                    sysident_str);
542         printf(_("Current log file ID:                  %u\n"),
543                    ControlFile.logId);
544         printf(_("Next log file segment:                %u\n"),
545                    ControlFile.logSeg);
546         printf(_("Latest checkpoint's TimeLineID:       %u\n"),
547                    ControlFile.checkPointCopy.ThisTimeLineID);
548         printf(_("Latest checkpoint's NextXID:          %u/%u\n"),
549                    ControlFile.checkPointCopy.nextXidEpoch,
550                    ControlFile.checkPointCopy.nextXid);
551         printf(_("Latest checkpoint's NextOID:          %u\n"),
552                    ControlFile.checkPointCopy.nextOid);
553         printf(_("Latest checkpoint's NextMultiXactId:  %u\n"),
554                    ControlFile.checkPointCopy.nextMulti);
555         printf(_("Latest checkpoint's NextMultiOffset:  %u\n"),
556                    ControlFile.checkPointCopy.nextMultiOffset);
557         printf(_("Maximum data alignment:               %u\n"),
558                    ControlFile.maxAlign);
559         /* we don't print floatFormat since can't say much useful about it */
560         printf(_("Database block size:                  %u\n"),
561                    ControlFile.blcksz);
562         printf(_("Blocks per segment of large relation: %u\n"),
563                    ControlFile.relseg_size);
564         printf(_("WAL block size:                       %u\n"),
565                    ControlFile.xlog_blcksz);
566         printf(_("Bytes per WAL segment:                %u\n"),
567                    ControlFile.xlog_seg_size);
568         printf(_("Maximum length of identifiers:        %u\n"),
569                    ControlFile.nameDataLen);
570         printf(_("Maximum columns in an index:          %u\n"),
571                    ControlFile.indexMaxKeys);
572         printf(_("Date/time type storage:               %s\n"),
573                    (ControlFile.enableIntTimes ? _("64-bit integers") : _("floating-point numbers")));
574         printf(_("Maximum length of locale name:        %u\n"),
575                    ControlFile.localeBuflen);
576         printf(_("LC_COLLATE:                           %s\n"),
577                    ControlFile.lc_collate);
578         printf(_("LC_CTYPE:                             %s\n"),
579                    ControlFile.lc_ctype);
580 }
581
582
583 /*
584  * Write out the new pg_control file.
585  */
586 static void
587 RewriteControlFile(void)
588 {
589         int                     fd;
590         char            buffer[PG_CONTROL_SIZE];                /* need not be aligned */
591
592         /*
593          * Adjust fields as needed to force an empty XLOG starting at the next
594          * available segment.
595          */
596         newXlogId = ControlFile.logId;
597         newXlogSeg = ControlFile.logSeg;
598
599         /* adjust in case we are changing segment size */
600         newXlogSeg *= ControlFile.xlog_seg_size;
601         newXlogSeg = (newXlogSeg + XLogSegSize - 1) / XLogSegSize;
602
603         /* be sure we wrap around correctly at end of a logfile */
604         NextLogSeg(newXlogId, newXlogSeg);
605
606         /* Now we can force the recorded xlog seg size to the right thing. */
607         ControlFile.xlog_seg_size = XLogSegSize;
608
609         ControlFile.checkPointCopy.redo.xlogid = newXlogId;
610         ControlFile.checkPointCopy.redo.xrecoff =
611                 newXlogSeg * XLogSegSize + SizeOfXLogLongPHD;
612         ControlFile.checkPointCopy.undo = ControlFile.checkPointCopy.redo;
613         ControlFile.checkPointCopy.time = time(NULL);
614
615         ControlFile.state = DB_SHUTDOWNED;
616         ControlFile.time = time(NULL);
617         ControlFile.logId = newXlogId;
618         ControlFile.logSeg = newXlogSeg + 1;
619         ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
620         ControlFile.prevCheckPoint.xlogid = 0;
621         ControlFile.prevCheckPoint.xrecoff = 0;
622         ControlFile.minRecoveryPoint.xlogid = 0;
623         ControlFile.minRecoveryPoint.xrecoff = 0;
624
625         /* Contents are protected with a CRC */
626         INIT_CRC32(ControlFile.crc);
627         COMP_CRC32(ControlFile.crc,
628                            (char *) &ControlFile,
629                            offsetof(ControlFileData, crc));
630         FIN_CRC32(ControlFile.crc);
631
632         /*
633          * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
634          * excess over sizeof(ControlFileData).  This reduces the odds of
635          * premature-EOF errors when reading pg_control.  We'll still fail when we
636          * check the contents of the file, but hopefully with a more specific
637          * error than "couldn't read pg_control".
638          */
639         if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
640         {
641                 fprintf(stderr,
642                                 _("%s: internal error -- sizeof(ControlFileData) is too large ... fix PG_CONTROL_SIZE\n"),
643                                 progname);
644                 exit(1);
645         }
646
647         memset(buffer, 0, PG_CONTROL_SIZE);
648         memcpy(buffer, &ControlFile, sizeof(ControlFileData));
649
650         unlink(XLOG_CONTROL_FILE);
651
652         fd = open(XLOG_CONTROL_FILE,
653                           O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
654                           S_IRUSR | S_IWUSR);
655         if (fd < 0)
656         {
657                 fprintf(stderr, _("%s: could not create pg_control file: %s\n"),
658                                 progname, strerror(errno));
659                 exit(1);
660         }
661
662         errno = 0;
663         if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
664         {
665                 /* if write didn't set errno, assume problem is no disk space */
666                 if (errno == 0)
667                         errno = ENOSPC;
668                 fprintf(stderr, _("%s: could not write pg_control file: %s\n"),
669                                 progname, strerror(errno));
670                 exit(1);
671         }
672
673         if (fsync(fd) != 0)
674         {
675                 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
676                 exit(1);
677         }
678
679         close(fd);
680 }
681
682
683 /*
684  * Remove existing XLOG files
685  */
686 static void
687 KillExistingXLOG(void)
688 {
689         DIR                *xldir;
690         struct dirent *xlde;
691         char            path[MAXPGPATH];
692
693         xldir = opendir(XLOGDIR);
694         if (xldir == NULL)
695         {
696                 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
697                                 progname, XLOGDIR, strerror(errno));
698                 exit(1);
699         }
700
701         errno = 0;
702         while ((xlde = readdir(xldir)) != NULL)
703         {
704                 if (strlen(xlde->d_name) == 24 &&
705                         strspn(xlde->d_name, "0123456789ABCDEF") == 24)
706                 {
707                         snprintf(path, MAXPGPATH, "%s/%s", XLOGDIR, xlde->d_name);
708                         if (unlink(path) < 0)
709                         {
710                                 fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
711                                                 progname, path, strerror(errno));
712                                 exit(1);
713                         }
714                 }
715                 errno = 0;
716         }
717 #ifdef WIN32
718
719         /*
720          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
721          * released version
722          */
723         if (GetLastError() == ERROR_NO_MORE_FILES)
724                 errno = 0;
725 #endif
726
727         if (errno)
728         {
729                 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
730                                 progname, XLOGDIR, strerror(errno));
731                 exit(1);
732         }
733         closedir(xldir);
734 }
735
736
737 /*
738  * Write an empty XLOG file, containing only the checkpoint record
739  * already set up in ControlFile.
740  */
741 static void
742 WriteEmptyXLOG(void)
743 {
744         char       *buffer;
745         XLogPageHeader page;
746         XLogLongPageHeader longpage;
747         XLogRecord *record;
748         pg_crc32        crc;
749         char            path[MAXPGPATH];
750         int                     fd;
751         int                     nbytes;
752
753         /* Use malloc() to ensure buffer is MAXALIGNED */
754         buffer = (char *) malloc(XLOG_BLCKSZ);
755         page = (XLogPageHeader) buffer;
756         memset(buffer, 0, XLOG_BLCKSZ);
757
758         /* Set up the XLOG page header */
759         page->xlp_magic = XLOG_PAGE_MAGIC;
760         page->xlp_info = XLP_LONG_HEADER;
761         page->xlp_tli = ControlFile.checkPointCopy.ThisTimeLineID;
762         page->xlp_pageaddr.xlogid =
763                 ControlFile.checkPointCopy.redo.xlogid;
764         page->xlp_pageaddr.xrecoff =
765                 ControlFile.checkPointCopy.redo.xrecoff - SizeOfXLogLongPHD;
766         longpage = (XLogLongPageHeader) page;
767         longpage->xlp_sysid = ControlFile.system_identifier;
768         longpage->xlp_seg_size = XLogSegSize;
769         longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
770
771         /* Insert the initial checkpoint record */
772         record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
773         record->xl_prev.xlogid = 0;
774         record->xl_prev.xrecoff = 0;
775         record->xl_xid = InvalidTransactionId;
776         record->xl_tot_len = SizeOfXLogRecord + sizeof(CheckPoint);
777         record->xl_len = sizeof(CheckPoint);
778         record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
779         record->xl_rmid = RM_XLOG_ID;
780         memcpy(XLogRecGetData(record), &ControlFile.checkPointCopy,
781                    sizeof(CheckPoint));
782
783         INIT_CRC32(crc);
784         COMP_CRC32(crc, &ControlFile.checkPointCopy, sizeof(CheckPoint));
785         COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
786                            SizeOfXLogRecord - sizeof(pg_crc32));
787         FIN_CRC32(crc);
788         record->xl_crc = crc;
789
790         /* Write the first page */
791         XLogFilePath(path, ControlFile.checkPointCopy.ThisTimeLineID,
792                                  newXlogId, newXlogSeg);
793
794         unlink(path);
795
796         fd = open(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
797                           S_IRUSR | S_IWUSR);
798         if (fd < 0)
799         {
800                 fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
801                                 progname, path, strerror(errno));
802                 exit(1);
803         }
804
805         errno = 0;
806         if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
807         {
808                 /* if write didn't set errno, assume problem is no disk space */
809                 if (errno == 0)
810                         errno = ENOSPC;
811                 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
812                                 progname, path, strerror(errno));
813                 exit(1);
814         }
815
816         /* Fill the rest of the file with zeroes */
817         memset(buffer, 0, XLOG_BLCKSZ);
818         for (nbytes = XLOG_BLCKSZ; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
819         {
820                 errno = 0;
821                 if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
822                 {
823                         if (errno == 0)
824                                 errno = ENOSPC;
825                         fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
826                                         progname, path, strerror(errno));
827                         exit(1);
828                 }
829         }
830
831         if (fsync(fd) != 0)
832         {
833                 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
834                 exit(1);
835         }
836
837         close(fd);
838 }
839
840
841 static void
842 usage(void)
843 {
844         printf(_("%s resets the PostgreSQL transaction log.\n\n"), progname);
845         printf(_("Usage:\n  %s [OPTION]... DATADIR\n\n"), progname);
846         printf(_("Options:\n"));
847         printf(_("  -f              force update to be done\n"));
848         printf(_("  -l TLI,FILE,SEG force minimum WAL starting location for new transaction log\n"));
849         printf(_("  -m XID          set next multitransaction ID\n"));
850         printf(_("  -n              no update, just show extracted control values (for testing)\n"));
851         printf(_("  -o OID          set next OID\n"));
852         printf(_("  -O OFFSET       set next multitransaction offset\n"));
853         printf(_("  -x XID          set next transaction ID\n"));
854         printf(_("  -e XIDEPOCH     set next transaction ID epoch\n"));
855         printf(_("  --help          show this help, then exit\n"));
856         printf(_("  --version       output version information, then exit\n"));
857         printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
858 }