PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pg_checksums.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * pg_checksums.c
4 * Checks, enables or disables page level checksums for an offline
5 * cluster
6 *
7 * Copyright (c) 2010-2026, PostgreSQL Global Development Group
8 *
9 * IDENTIFICATION
10 * src/bin/pg_checksums/pg_checksums.c
11 *
12 *-------------------------------------------------------------------------
13 */
14
15#include "postgres_fe.h"
16
17#include <dirent.h>
18#include <limits.h>
19#include <sys/stat.h>
20#include <time.h>
21#include <unistd.h>
22
24#include "common/file_utils.h"
25#include "common/logging.h"
26#include "common/relpath.h"
28#include "fe_utils/version.h"
29#include "getopt_long.h"
30#include "pg_getopt.h"
31#include "storage/bufpage.h"
32#include "storage/checksum.h"
34
35
40static int64 badblocks = 0;
42
43static char *only_filenode = NULL;
44static bool do_sync = true;
45static bool verbose = false;
46static bool showprogress = false;
48
55
57
58static const char *progname;
59
60/*
61 * Progress status information.
62 */
63static int64 total_size = 0;
66
67static void
68usage(void)
69{
70 printf(_("%s enables, disables, or verifies data checksums in a PostgreSQL database cluster.\n\n"), progname);
71 printf(_("Usage:\n"));
72 printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
73 printf(_("\nOptions:\n"));
74 printf(_(" [-D, --pgdata=]DATADIR data directory\n"));
75 printf(_(" -c, --check check data checksums (default)\n"));
76 printf(_(" -d, --disable disable data checksums\n"));
77 printf(_(" -e, --enable enable data checksums\n"));
78 printf(_(" -f, --filenode=FILENODE check only relation with specified filenode\n"));
79 printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
80 printf(_(" -P, --progress show progress information\n"));
81 printf(_(" --sync-method=METHOD set method for syncing files to disk\n"));
82 printf(_(" -v, --verbose output verbose messages\n"));
83 printf(_(" -V, --version output version information, then exit\n"));
84 printf(_(" -?, --help show this help, then exit\n"));
85 printf(_("\nIf no data directory (DATADIR) is specified, "
86 "the environment variable PGDATA\nis used.\n\n"));
87 printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
88 printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
89}
90
91/*
92 * Definition of one element part of an exclusion list, used for files
93 * to exclude from checksum validation. "name" is the name of the file
94 * or path to check for exclusion. If "match_prefix" is true, any items
95 * matching the name as prefix are excluded.
96 */
98{
99 const char *name;
100 bool match_prefix;
101};
102
103/*
104 * List of files excluded from checksum validation.
105 *
106 * Note: this list should be kept in sync with what basebackup.c includes.
107 */
108static const struct exclude_list_item skip[] = {
109 {"pg_control", false},
110 {"pg_filenode.map", false},
111 {"pg_internal.init", true},
112 {"PG_VERSION", false},
113#ifdef EXEC_BACKEND
114 {"config_exec_params", true},
115#endif
116 {NULL, false}
117};
118
119/*
120 * Report current progress status. Parts borrowed from
121 * src/bin/pg_basebackup/pg_basebackup.c.
122 */
123static void
124progress_report(bool finished)
125{
126 int percent;
128
130
131 now = time(NULL);
132 if (now == last_progress_report && !finished)
133 return; /* Max once per second */
134
135 /* Save current time */
137
138 /* Adjust total size if current_size is larger */
141
142 /* Calculate current percentage of size done */
143 percent = total_size ? (int) ((current_size) * 100 / total_size) : 0;
144
145 fprintf(stderr, _("%" PRId64 "/%" PRId64 " MB (%d%%) computed"),
146 (current_size / (1024 * 1024)),
147 (total_size / (1024 * 1024)),
148 percent);
149
150 /*
151 * Stay on the same line if reporting to a terminal and we're not done
152 * yet.
153 */
154 fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
155}
156
157static bool
158skipfile(const char *fn)
159{
160 int excludeIdx;
161
162 for (excludeIdx = 0; skip[excludeIdx].name != NULL; excludeIdx++)
163 {
165
167 cmplen++;
168 if (strncmp(skip[excludeIdx].name, fn, cmplen) == 0)
169 return true;
170 }
171
172 return false;
173}
174
175static void
176scan_file(const char *fn, int segmentno)
177{
179 PageHeader header = (PageHeader) buf.data;
180 int f;
181 BlockNumber blockno;
182 int flags;
184
187
188 flags = (mode == PG_MODE_ENABLE) ? O_RDWR : O_RDONLY;
189 f = open(fn, PG_BINARY | flags, 0);
190
191 if (f < 0)
192 pg_fatal("could not open file \"%s\": %m", fn);
193
195
196 for (blockno = 0;; blockno++)
197 {
198 uint16 csum;
199 ssize_t r;
200
201 r = read(f, buf.data, BLCKSZ);
202 if (r == 0)
203 break;
204 if (r != BLCKSZ)
205 {
206 if (r < 0)
207 pg_fatal("could not read block %u in file \"%s\": %m",
208 blockno, fn);
209 else
210 pg_fatal("could not read block %u in file \"%s\": read %zd of %zu",
211 blockno, fn, r, (size_t) BLCKSZ);
212 }
214
215 /*
216 * Since the file size is counted as total_size for progress status
217 * information, the sizes of all pages including new ones in the file
218 * should be counted as current_size. Otherwise the progress reporting
219 * calculated using those counters may not reach 100%.
220 */
221 current_size += r;
222
223 /* New pages have no checksum yet */
224 if (PageIsNew(buf.data))
225 continue;
226
227 csum = pg_checksum_page(buf.data, blockno + segmentno * RELSEG_SIZE);
228 if (mode == PG_MODE_CHECK)
229 {
230 if (csum != header->pd_checksum)
231 {
233 pg_log_error("checksum verification failed in file \"%s\", block %u: calculated checksum %X but block contains %X",
234 fn, blockno, csum, header->pd_checksum);
235 badblocks++;
236 }
237 }
238 else if (mode == PG_MODE_ENABLE)
239 {
240 ssize_t w;
241
242 /*
243 * Do not rewrite if the checksum is already set to the expected
244 * value.
245 */
246 if (header->pd_checksum == csum)
247 continue;
248
250
251 /* Set checksum in page header */
252 header->pd_checksum = csum;
253
254 /* Seek back to beginning of block */
255 if (lseek(f, -BLCKSZ, SEEK_CUR) < 0)
256 pg_fatal("seek failed for block %u in file \"%s\": %m", blockno, fn);
257
258 /* Write block with checksum */
259 w = write(f, buf.data, BLCKSZ);
260 if (w != BLCKSZ)
261 {
262 if (w < 0)
263 pg_fatal("could not write block %u in file \"%s\": %m",
264 blockno, fn);
265 else
266 pg_fatal("could not write block %u in file \"%s\": wrote %zd of %zu",
267 blockno, fn, w, (size_t) BLCKSZ);
268 }
269 }
270
271 if (showprogress)
272 progress_report(false);
273 }
274
275 if (verbose)
276 {
277 if (mode == PG_MODE_CHECK)
278 pg_log_info("checksums verified in file \"%s\"", fn);
279 if (mode == PG_MODE_ENABLE)
280 pg_log_info("checksums enabled in file \"%s\"", fn);
281 }
282
283 /* Update write counters if any write activity has happened */
285 {
288 }
289
290 close(f);
291}
292
293/*
294 * Scan the given directory for items which can be checksummed and
295 * operate on each one of them. If "sizeonly" is true, the size of
296 * all the items which have checksums is computed and returned back
297 * to the caller without operating on the files. This is used to compile
298 * the total size of the data directory for progress reports.
299 */
300static int64
301scan_directory(const char *basedir, const char *subdir, bool sizeonly)
302{
303 int64 dirsize = 0;
304 char path[MAXPGPATH];
305 DIR *dir;
306 struct dirent *de;
307
308 snprintf(path, sizeof(path), "%s/%s", basedir, subdir);
309 dir = opendir(path);
310 if (!dir)
311 pg_fatal("could not open directory \"%s\": %m", path);
312 while ((de = readdir(dir)) != NULL)
313 {
314 char fn[MAXPGPATH];
315 struct stat st;
316
317 if (strcmp(de->d_name, ".") == 0 ||
318 strcmp(de->d_name, "..") == 0)
319 continue;
320
321 /* Skip temporary files */
322 if (strncmp(de->d_name,
325 continue;
326
327 /* Skip temporary folders */
328 if (strncmp(de->d_name,
331 continue;
332
333 /* Skip macOS system files */
334 if (strcmp(de->d_name, ".DS_Store") == 0)
335 continue;
336
337 snprintf(fn, sizeof(fn), "%s/%s", path, de->d_name);
338 if (lstat(fn, &st) < 0)
339 pg_fatal("could not stat file \"%s\": %m", fn);
340 if (S_ISREG(st.st_mode))
341 {
342 char fnonly[MAXPGPATH];
343 char *forkpath,
345 int segmentno = 0;
346
347 if (skipfile(de->d_name))
348 continue;
349
350 /*
351 * Cut off at the segment boundary (".") to get the segment number
352 * in order to mix it into the checksum. Then also cut off at the
353 * fork boundary, to get the filenode the file belongs to for
354 * filtering.
355 */
356 strlcpy(fnonly, de->d_name, sizeof(fnonly));
357 segmentpath = strchr(fnonly, '.');
358 if (segmentpath != NULL)
359 {
360 *segmentpath++ = '\0';
362 if (segmentno == 0)
363 pg_fatal("invalid segment number %d in file name \"%s\"",
364 segmentno, fn);
365 }
366
367 forkpath = strchr(fnonly, '_');
368 if (forkpath != NULL)
369 *forkpath++ = '\0';
370
372 /* filenode not to be included */
373 continue;
374
375 dirsize += st.st_size;
376
377 /*
378 * No need to work on the file when calculating only the size of
379 * the items in the data folder.
380 */
381 if (!sizeonly)
383 }
384 else if (S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode))
385 {
386 /*
387 * If going through the entries of pg_tblspc, we assume to operate
388 * on tablespace locations where only TABLESPACE_VERSION_DIRECTORY
389 * is valid, resolving the linked locations and dive into them
390 * directly.
391 */
393 {
395 struct stat tblspc_st;
396
397 /*
398 * Resolve tablespace location path and check whether
399 * TABLESPACE_VERSION_DIRECTORY exists. Not finding a valid
400 * location is unexpected, since there should be no orphaned
401 * links and no links pointing to something else than a
402 * directory.
403 */
404 snprintf(tblspc_path, sizeof(tblspc_path), "%s/%s/%s",
405 path, de->d_name, TABLESPACE_VERSION_DIRECTORY);
406
407 if (lstat(tblspc_path, &tblspc_st) < 0)
408 pg_fatal("could not stat file \"%s\": %m",
410
411 /*
412 * Move backwards once as the scan needs to happen for the
413 * contents of TABLESPACE_VERSION_DIRECTORY.
414 */
415 snprintf(tblspc_path, sizeof(tblspc_path), "%s/%s",
416 path, de->d_name);
417
418 /* Looks like a valid tablespace location */
421 sizeonly);
422 }
423 else
424 {
425 dirsize += scan_directory(path, de->d_name, sizeonly);
426 }
427 }
428 }
429 closedir(dir);
430 return dirsize;
431}
432
433int
434main(int argc, char *argv[])
435{
436 static struct option long_options[] = {
437 {"check", no_argument, NULL, 'c'},
438 {"pgdata", required_argument, NULL, 'D'},
439 {"disable", no_argument, NULL, 'd'},
440 {"enable", no_argument, NULL, 'e'},
441 {"filenode", required_argument, NULL, 'f'},
442 {"no-sync", no_argument, NULL, 'N'},
443 {"progress", no_argument, NULL, 'P'},
444 {"verbose", no_argument, NULL, 'v'},
445 {"sync-method", required_argument, NULL, 1},
446 {NULL, 0, NULL, 0}
447 };
448
449 char *DataDir = NULL;
450 int c;
451 int option_index;
452 bool crc_ok;
453 uint32 major_version;
454 char *version_str;
455
456 pg_logging_init(argv[0]);
457 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_checksums"));
458 progname = get_progname(argv[0]);
459
460 if (argc > 1)
461 {
462 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
463 {
464 usage();
465 exit(0);
466 }
467 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
468 {
469 puts("pg_checksums (PostgreSQL) " PG_VERSION);
470 exit(0);
471 }
472 }
473
474 while ((c = getopt_long(argc, argv, "cdD:ef:NPv", long_options, &option_index)) != -1)
475 {
476 switch (c)
477 {
478 case 'c':
480 break;
481 case 'd':
483 break;
484 case 'D':
485 DataDir = optarg;
486 break;
487 case 'e':
489 break;
490 case 'f':
491 if (!option_parse_int(optarg, "-f/--filenode", 0,
492 INT_MAX,
493 NULL))
494 exit(1);
496 break;
497 case 'N':
498 do_sync = false;
499 break;
500 case 'P':
501 showprogress = true;
502 break;
503 case 'v':
504 verbose = true;
505 break;
506 case 1:
508 exit(1);
509 break;
510 default:
511 /* getopt_long already emitted a complaint */
512 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
513 exit(1);
514 }
515 }
516
517 if (DataDir == NULL)
518 {
519 if (optind < argc)
520 DataDir = argv[optind++];
521 else
522 DataDir = getenv("PGDATA");
523
524 /* If no DataDir was specified, and none could be found, error out */
525 if (DataDir == NULL)
526 {
527 pg_log_error("no data directory specified");
528 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
529 exit(1);
530 }
531 }
532
533 /* Complain if any arguments remain */
534 if (optind < argc)
535 {
536 pg_log_error("too many command-line arguments (first is \"%s\")",
537 argv[optind]);
538 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
539 exit(1);
540 }
541
542 /* filenode checking only works in --check mode */
544 {
545 pg_log_error("option -f/--filenode can only be used with --check");
546 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
547 exit(1);
548 }
549
550 /*
551 * Retrieve the contents of this cluster's PG_VERSION. We require
552 * compatibility with the same major version as the one this tool is
553 * compiled with.
554 */
556 if (major_version != PG_MAJORVERSION_NUM)
557 {
558 pg_log_error("data directory is of wrong version");
559 pg_log_error_detail("File \"%s\" contains \"%s\", which is not compatible with this program's version \"%s\".",
560 "PG_VERSION", version_str, PG_MAJORVERSION);
561 exit(1);
562 }
563
564 /* Read the control file and check compatibility */
566 if (!crc_ok)
567 pg_fatal("pg_control CRC value is incorrect");
568
570 pg_fatal("cluster is not compatible with this version of pg_checksums");
571
572 if (ControlFile->blcksz != BLCKSZ)
573 {
574 pg_log_error("database cluster is not compatible");
575 pg_log_error_detail("The database cluster was initialized with block size %u, but pg_checksums was compiled with block size %u.",
577 exit(1);
578 }
579
580 /*
581 * Check if cluster is running. A clean shutdown is required to avoid
582 * random checksum failures caused by torn pages. Note that this doesn't
583 * guard against someone starting the cluster concurrently.
584 */
587 pg_fatal("cluster must be shut down");
588
591 pg_fatal("data checksums are not enabled in cluster");
592
595 pg_fatal("data checksums are already disabled in cluster");
596
599 pg_fatal("data checksums are already enabled in cluster");
600
601 /* Operate on all files if checking or enabling checksums */
603 {
604 /*
605 * If progress status information is requested, we need to scan the
606 * directory tree twice: once to know how much total data needs to be
607 * processed and once to do the real work.
608 */
609 if (showprogress)
610 {
611 total_size = scan_directory(DataDir, "global", true);
612 total_size += scan_directory(DataDir, "base", true);
614 }
615
616 (void) scan_directory(DataDir, "global", false);
617 (void) scan_directory(DataDir, "base", false);
619
620 if (showprogress)
621 progress_report(true);
622
623 printf(_("Checksum operation completed\n"));
624 printf(_("Files scanned: %" PRId64 "\n"), files_scanned);
625 printf(_("Blocks scanned: %" PRId64 "\n"), blocks_scanned);
626 if (mode == PG_MODE_CHECK)
627 {
628 printf(_("Bad checksums: %" PRId64 "\n"), badblocks);
629 printf(_("Data checksum version: %u\n"), ControlFile->data_checksum_version);
630
631 if (badblocks > 0)
632 exit(1);
633 }
634 else if (mode == PG_MODE_ENABLE)
635 {
636 printf(_("Files written: %" PRId64 "\n"), files_written);
637 printf(_("Blocks written: %" PRId64 "\n"), blocks_written);
638 }
639 }
640
641 /*
642 * Finally make the data durable on disk if enabling or disabling
643 * checksums. Flush first the data directory for safety, and then update
644 * the control file to keep the switch consistent.
645 */
647 {
650
651 if (do_sync)
652 {
653 pg_log_info("syncing data directory");
655 }
656
657 pg_log_info("updating control file");
659
660 if (verbose)
661 printf(_("Data checksum version: %u\n"), ControlFile->data_checksum_version);
662 if (mode == PG_MODE_ENABLE)
663 printf(_("Checksums enabled in cluster\n"));
664 else
665 printf(_("Checksums disabled in cluster\n"));
666 }
667
668 return 0;
669}
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1613
uint32 BlockNumber
Definition block.h:31
PageHeaderData * PageHeader
Definition bufpage.h:199
static bool PageIsNew(const PageData *page)
Definition bufpage.h:258
#define Assert(condition)
Definition c.h:1002
#define PG_TEXTDOMAIN(domain)
Definition c.h:1343
int64_t int64
Definition c.h:680
#define PG_BINARY
Definition c.h:1431
uint16_t uint16
Definition c.h:682
uint32_t uint32
Definition c.h:683
@ PG_DATA_CHECKSUM_VERSION
Definition checksum.h:29
@ PG_DATA_CHECKSUM_OFF
Definition checksum.h:28
uint16 pg_checksum_page(char *page, BlockNumber blkno)
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition exec.c:430
int main(void)
void update_controlfile(const char *DataDir, ControlFileData *ControlFile, bool do_sync)
ControlFileData * get_controlfile(const char *DataDir, bool *crc_ok_p)
#define fprintf(file, fmt, msg)
Definition cubescan.l:21
int closedir(DIR *)
Definition dirent.c:127
struct dirent * readdir(DIR *)
Definition dirent.c:78
DIR * opendir(const char *)
Definition dirent.c:33
#define _(x)
Definition elog.c:96
uint32 get_pg_version(const char *datadir, char **version_str)
Definition version.c:44
#define PG_TEMP_FILES_DIR
Definition file_utils.h:63
#define PG_TEMP_FILE_PREFIX
Definition file_utils.h:64
DataDirSyncMethod
Definition file_utils.h:28
@ DATA_DIR_SYNC_METHOD_FSYNC
Definition file_utils.h:29
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition getopt_long.c:60
#define no_argument
Definition getopt_long.h:25
#define required_argument
Definition getopt_long.h:26
char * DataDir
Definition globals.c:73
#define close(a)
Definition win32.h:12
#define write(a, b, c)
Definition win32.h:14
#define read(a, b, c)
Definition win32.h:13
void pg_logging_init(const char *argv0)
Definition logging.c:85
#define pg_log_error(...)
Definition logging.h:108
#define pg_log_error_hint(...)
Definition logging.h:114
#define pg_log_info(...)
Definition logging.h:126
#define pg_log_error_detail(...)
Definition logging.h:111
char * pstrdup(const char *in)
Definition mcxt.c:1910
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
bool parse_sync_method(const char *optarg, DataDirSyncMethod *sync_method)
#define pg_fatal(...)
static char * basedir
static void scan_file(const char *fn, int segmentno)
static int64 total_size
static PgChecksumMode mode
static char * only_filenode
static int64 blocks_scanned
static int64 current_size
static void progress_report(bool finished)
static pg_time_t last_progress_report
static const struct exclude_list_item skip[]
static int64 scan_directory(const char *basedir, const char *subdir, bool sizeonly)
static int64 files_scanned
static bool do_sync
static bool verbose
static bool skipfile(const char *fn)
static ControlFileData * ControlFile
static DataDirSyncMethod sync_method
static int64 blocks_written
static bool showprogress
static const char * progname
static void usage(void)
static int64 files_written
PgChecksumMode
@ PG_MODE_CHECK
@ PG_MODE_DISABLE
@ PG_MODE_ENABLE
static int64 badblocks
#define MAXPGPATH
#define PG_CONTROL_VERSION
Definition pg_control.h:25
@ DB_SHUTDOWNED_IN_RECOVERY
Definition pg_control.h:101
@ DB_SHUTDOWNED
Definition pg_control.h:100
PGDLLIMPORT int optind
Definition getopt.c:47
PGDLLIMPORT char * optarg
Definition getopt.c:49
static char buf[DEFAULT_XLOG_SEG_SIZE]
int64 pg_time_t
Definition pgtime.h:23
#define snprintf
Definition port.h:261
const char * get_progname(const char *argv0)
Definition path.c:669
#define printf(...)
Definition port.h:267
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
char * c
static int fb(int x)
#define PG_TBLSPC_DIR
Definition relpath.h:41
#define TABLESPACE_VERSION_DIRECTORY
Definition relpath.h:33
uint32 pg_control_version
Definition pg_control.h:133
uint32 data_checksum_version
Definition pg_control.h:232
Definition dirent.c:26
uint16 pd_checksum
Definition bufpage.h:189
const char * name
Definition basebackup.c:145
__int64 st_size
Definition win32_port.h:280
unsigned short st_mode
Definition win32_port.h:275
static void * fn(void *arg)
#define GET_PG_MAJORVERSION_NUM(v)
Definition version.h:19
const char * name
#define lstat(path, sb)
Definition win32_port.h:292
#define S_ISDIR(m)
Definition win32_port.h:332
#define S_ISLNK(m)
Definition win32_port.h:351
#define S_ISREG(m)
Definition win32_port.h:335