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