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