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