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