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