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