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