LCOV - differential code coverage report
Current view: top level - src/bin/pg_checksums - pg_checksums.c (source / functions) Coverage Total Hit UNC UBC GNC CBC
Current: a2387c32f2f8a1643c7d71b951587e6bcb2d4744 vs 371a302eecdc82274b0ae2967d18fd726a0aa6a1 Lines: 77.0 % 265 204 3 58 2 202
Current Date: 2025-10-26 12:31:50 -0700 Functions: 83.3 % 6 5 1 1 4
Baseline: lcov-20251027-010456-baseline Branches: 68.1 % 188 128 1 59 1 127
Baseline Date: 2025-10-26 11:01:32 +1300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 40.0 % 5 2 3 2
(30,360] days: 85.7 % 7 6 1 6
(360..) days: 77.5 % 253 196 57 196
Function coverage date bins:
(360..) days: 83.3 % 6 5 1 1 4
Branch coverage date bins:
(1,7] days: 50.0 % 2 1 1 1
(360..) days: 68.3 % 186 127 59 127

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * pg_checksums.c
                                  4                 :                :  *    Checks, enables or disables page level checksums for an offline
                                  5                 :                :  *    cluster
                                  6                 :                :  *
                                  7                 :                :  * Copyright (c) 2010-2025, 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                 :                : 
                                 23                 :                : #include "common/controldata_utils.h"
                                 24                 :                : #include "common/file_utils.h"
                                 25                 :                : #include "common/logging.h"
                                 26                 :                : #include "common/relpath.h"
                                 27                 :                : #include "fe_utils/option_utils.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"
                                 33                 :                : #include "storage/checksum_impl.h"
                                 34                 :                : 
                                 35                 :                : 
                                 36                 :                : static int64 files_scanned = 0;
                                 37                 :                : static int64 files_written = 0;
                                 38                 :                : static int64 blocks_scanned = 0;
                                 39                 :                : static int64 blocks_written = 0;
                                 40                 :                : static int64 badblocks = 0;
                                 41                 :                : static ControlFileData *ControlFile;
                                 42                 :                : 
                                 43                 :                : static char *only_filenode = NULL;
                                 44                 :                : static bool do_sync = true;
                                 45                 :                : static bool verbose = false;
                                 46                 :                : static bool showprogress = false;
                                 47                 :                : static DataDirSyncMethod sync_method = DATA_DIR_SYNC_METHOD_FSYNC;
                                 48                 :                : 
                                 49                 :                : typedef enum
                                 50                 :                : {
                                 51                 :                :     PG_MODE_CHECK,
                                 52                 :                :     PG_MODE_DISABLE,
                                 53                 :                :     PG_MODE_ENABLE,
                                 54                 :                : } PgChecksumMode;
                                 55                 :                : 
                                 56                 :                : static PgChecksumMode mode = PG_MODE_CHECK;
                                 57                 :                : 
                                 58                 :                : static const char *progname;
                                 59                 :                : 
                                 60                 :                : /*
                                 61                 :                :  * Progress status information.
                                 62                 :                :  */
                                 63                 :                : static int64 total_size = 0;
                                 64                 :                : static int64 current_size = 0;
                                 65                 :                : static pg_time_t last_progress_report = 0;
                                 66                 :                : 
                                 67                 :                : static void
 2614 tgl@sss.pgh.pa.us          68                 :CBC           1 : usage(void)
                                 69                 :                : {
 2310 peter@eisentraut.org       70                 :              1 :     printf(_("%s enables, disables, or verifies data checksums in a PostgreSQL database cluster.\n\n"), progname);
 2762 magnus@hagander.net        71                 :              1 :     printf(_("Usage:\n"));
 2622 peter_e@gmx.net            72                 :              1 :     printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
 2762 magnus@hagander.net        73                 :              1 :     printf(_("\nOptions:\n"));
 2342 michael@paquier.xyz        74                 :              1 :     printf(_(" [-D, --pgdata=]DATADIR    data directory\n"));
                                 75                 :              1 :     printf(_("  -c, --check              check data checksums (default)\n"));
                                 76                 :              1 :     printf(_("  -d, --disable            disable data checksums\n"));
                                 77                 :              1 :     printf(_("  -e, --enable             enable data checksums\n"));
                                 78                 :              1 :     printf(_("  -f, --filenode=FILENODE  check only relation with specified filenode\n"));
                                 79                 :              1 :     printf(_("  -N, --no-sync            do not wait for changes to be written safely to disk\n"));
                                 80                 :              1 :     printf(_("  -P, --progress           show progress information\n"));
  782 nathan@postgresql.or       81                 :              1 :     printf(_("      --sync-method=METHOD set method for syncing files to disk\n"));
 2342 michael@paquier.xyz        82                 :              1 :     printf(_("  -v, --verbose            output verbose messages\n"));
                                 83                 :              1 :     printf(_("  -V, --version            output version information, then exit\n"));
                                 84                 :              1 :     printf(_("  -?, --help               show this help, then exit\n"));
 2762 magnus@hagander.net        85                 :              1 :     printf(_("\nIf no data directory (DATADIR) is specified, "
                                 86                 :                :              "the environment variable PGDATA\nis used.\n\n"));
 2068 peter@eisentraut.org       87                 :              1 :     printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
                                 88                 :              1 :     printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
 2762 magnus@hagander.net        89                 :              1 : }
                                 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                 :                :  */
                                 97                 :                : struct exclude_list_item
                                 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                 :                :  */
                                108                 :                : static 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                 :                :  */
                                123                 :                : static void
 1897 heikki.linnakangas@i      124                 :UBC           0 : progress_report(bool finished)
                                125                 :                : {
                                126                 :                :     int         percent;
                                127                 :                :     pg_time_t   now;
                                128                 :                : 
 2400 michael@paquier.xyz       129         [ #  # ]:              0 :     Assert(showprogress);
                                130                 :                : 
                                131                 :              0 :     now = time(NULL);
 1897 heikki.linnakangas@i      132   [ #  #  #  # ]:              0 :     if (now == last_progress_report && !finished)
 2400 michael@paquier.xyz       133                 :              0 :         return;                 /* Max once per second */
                                134                 :                : 
                                135                 :                :     /* Save current time */
                                136                 :              0 :     last_progress_report = now;
                                137                 :                : 
                                138                 :                :     /* Adjust total size if current_size is larger */
                                139         [ #  # ]:              0 :     if (current_size > total_size)
                                140                 :              0 :         total_size = current_size;
                                141                 :                : 
                                142                 :                :     /* Calculate current percentage of size done */
                                143         [ #  # ]:              0 :     percent = total_size ? (int) ((current_size) * 100 / total_size) : 0;
                                144                 :                : 
  239 peter@eisentraut.org      145                 :              0 :     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                 :                :      */
 1896 heikki.linnakangas@i      154   [ #  #  #  # ]:              0 :     fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
                                155                 :                : }
                                156                 :                : 
                                157                 :                : static bool
 2523 michael@paquier.xyz       158                 :CBC       12799 : skipfile(const char *fn)
                                159                 :                : {
                                160                 :                :     int         excludeIdx;
                                161                 :                : 
 2072                           162         [ +  + ]:          63669 :     for (excludeIdx = 0; skip[excludeIdx].name != NULL; excludeIdx++)
                                163                 :                :     {
                                164                 :          51011 :         int         cmplen = strlen(skip[excludeIdx].name);
                                165                 :                : 
                                166         [ +  + ]:          51011 :         if (!skip[excludeIdx].match_prefix)
                                167                 :          38281 :             cmplen++;
                                168         [ +  + ]:          51011 :         if (strncmp(skip[excludeIdx].name, fn, cmplen) == 0)
 2523                           169                 :            141 :             return true;
                                170                 :                :     }
                                171                 :                : 
                                172                 :          12658 :     return false;
                                173                 :                : }
                                174                 :                : 
                                175                 :                : static void
 1412 peter@eisentraut.org      176                 :           8826 : scan_file(const char *fn, int segmentno)
                                177                 :                : {
                                178                 :                :     PGIOAlignedBlock buf;
 2613 tgl@sss.pgh.pa.us         179                 :           8826 :     PageHeader  header = (PageHeader) buf.data;
                                180                 :                :     int         f;
                                181                 :                :     BlockNumber blockno;
                                182                 :                :     int         flags;
 1580 michael@paquier.xyz       183                 :           8826 :     int64       blocks_written_in_file = 0;
                                184                 :                : 
 2410                           185   [ +  +  -  + ]:           8826 :     Assert(mode == PG_MODE_ENABLE ||
                                186                 :                :            mode == PG_MODE_CHECK);
                                187                 :                : 
                                188         [ +  + ]:           8826 :     flags = (mode == PG_MODE_ENABLE) ? O_RDWR : O_RDONLY;
                                189                 :           8826 :     f = open(fn, PG_BINARY | flags, 0);
                                190                 :                : 
 2762 magnus@hagander.net       191         [ -  + ]:           8826 :     if (f < 0)
 1298 tgl@sss.pgh.pa.us         192                 :UBC           0 :         pg_fatal("could not open file \"%s\": %m", fn);
                                193                 :                : 
 1580 michael@paquier.xyz       194                 :CBC        8826 :     files_scanned++;
                                195                 :                : 
 2762 magnus@hagander.net       196                 :           8826 :     for (blockno = 0;; blockno++)
                                197                 :          27065 :     {
                                198                 :                :         uint16      csum;
 2613 tgl@sss.pgh.pa.us         199                 :          35891 :         int         r = read(f, buf.data, BLCKSZ);
                                200                 :                : 
 2762 magnus@hagander.net       201         [ +  + ]:          35891 :         if (r == 0)
                                202                 :           8818 :             break;
                                203         [ +  + ]:          27073 :         if (r != BLCKSZ)
                                204                 :                :         {
 2246 peter@eisentraut.org      205         [ -  + ]:              8 :             if (r < 0)
 1298 tgl@sss.pgh.pa.us         206                 :UBC           0 :                 pg_fatal("could not read block %u in file \"%s\": %m",
                                207                 :                :                          blockno, fn);
                                208                 :                :             else
 1298 tgl@sss.pgh.pa.us         209                 :CBC           8 :                 pg_fatal("could not read block %u in file \"%s\": read %d of %d",
                                210                 :                :                          blockno, fn, r, BLCKSZ);
                                211                 :                :         }
 1580 michael@paquier.xyz       212                 :          27065 :         blocks_scanned++;
                                213                 :                : 
                                214                 :                :         /*
                                215                 :                :          * Since the file size is counted as total_size for progress status
                                216                 :                :          * information, the sizes of all pages including new ones in the file
                                217                 :                :          * should be counted as current_size. Otherwise the progress reporting
                                218                 :                :          * calculated using those counters may not reach 100%.
                                219                 :                :          */
 1668 fujii@postgresql.org      220                 :          27065 :         current_size += r;
                                221                 :                : 
                                222                 :                :         /* New pages have no checksum yet */
 1204 peter@eisentraut.org      223         [ +  + ]:          27065 :         if (PageIsNew(buf.data))
 2752 magnus@hagander.net       224                 :            114 :             continue;
                                225                 :                : 
 2613 tgl@sss.pgh.pa.us         226                 :          26951 :         csum = pg_checksum_page(buf.data, blockno + segmentno * RELSEG_SIZE);
 2410 michael@paquier.xyz       227         [ +  + ]:          26951 :         if (mode == PG_MODE_CHECK)
                                228                 :                :         {
                                229         [ +  + ]:          21057 :             if (csum != header->pd_checksum)
                                230                 :                :             {
                                231         [ +  - ]:              4 :                 if (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_VERSION)
 2401 peter@eisentraut.org      232                 :              4 :                     pg_log_error("checksum verification failed in file \"%s\", block %u: calculated checksum %X but block contains %X",
                                233                 :                :                                  fn, blockno, csum, header->pd_checksum);
 2410 michael@paquier.xyz       234                 :              4 :                 badblocks++;
                                235                 :                :             }
                                236                 :                :         }
                                237         [ +  - ]:           5894 :         else if (mode == PG_MODE_ENABLE)
                                238                 :                :         {
                                239                 :                :             int         w;
                                240                 :                : 
                                241                 :                :             /*
                                242                 :                :              * Do not rewrite if the checksum is already set to the expected
                                243                 :                :              * value.
                                244                 :                :              */
 1580                           245         [ +  + ]:           5894 :             if (header->pd_checksum == csum)
                                246                 :           2947 :                 continue;
                                247                 :                : 
                                248                 :           2947 :             blocks_written_in_file++;
                                249                 :                : 
                                250                 :                :             /* Set checksum in page header */
 2410                           251                 :           2947 :             header->pd_checksum = csum;
                                252                 :                : 
                                253                 :                :             /* Seek back to beginning of block */
                                254         [ -  + ]:           2947 :             if (lseek(f, -BLCKSZ, SEEK_CUR) < 0)
 1298 tgl@sss.pgh.pa.us         255                 :UBC           0 :                 pg_fatal("seek failed for block %u in file \"%s\": %m", blockno, fn);
                                256                 :                : 
                                257                 :                :             /* Write block with checksum */
 2246 peter@eisentraut.org      258                 :CBC        2947 :             w = write(f, buf.data, BLCKSZ);
                                259         [ -  + ]:           2947 :             if (w != BLCKSZ)
                                260                 :                :             {
 2246 peter@eisentraut.org      261         [ #  # ]:UBC           0 :                 if (w < 0)
 1298 tgl@sss.pgh.pa.us         262                 :              0 :                     pg_fatal("could not write block %u in file \"%s\": %m",
                                263                 :                :                              blockno, fn);
                                264                 :                :                 else
                                265                 :              0 :                     pg_fatal("could not write block %u in file \"%s\": wrote %d of %d",
                                266                 :                :                              blockno, fn, w, BLCKSZ);
                                267                 :                :             }
                                268                 :                :         }
                                269                 :                : 
 2400 michael@paquier.xyz       270         [ -  + ]:CBC       24004 :         if (showprogress)
 2400 michael@paquier.xyz       271                 :UBC           0 :             progress_report(false);
                                272                 :                :     }
                                273                 :                : 
 2615 alvherre@alvh.no-ip.      274         [ -  + ]:CBC        8818 :     if (verbose)
                                275                 :                :     {
 2410 michael@paquier.xyz       276         [ #  # ]:UBC           0 :         if (mode == PG_MODE_CHECK)
 2401 peter@eisentraut.org      277                 :              0 :             pg_log_info("checksums verified in file \"%s\"", fn);
 2410 michael@paquier.xyz       278         [ #  # ]:              0 :         if (mode == PG_MODE_ENABLE)
 2401 peter@eisentraut.org      279                 :              0 :             pg_log_info("checksums enabled in file \"%s\"", fn);
                                280                 :                :     }
                                281                 :                : 
                                282                 :                :     /* Update write counters if any write activity has happened */
 1580 michael@paquier.xyz       283         [ +  + ]:CBC        8818 :     if (blocks_written_in_file > 0)
                                284                 :                :     {
                                285                 :            781 :         files_written++;
                                286                 :            781 :         blocks_written += blocks_written_in_file;
                                287                 :                :     }
                                288                 :                : 
 2762 magnus@hagander.net       289                 :           8818 :     close(f);
                                290                 :           8818 : }
                                291                 :                : 
                                292                 :                : /*
                                293                 :                :  * Scan the given directory for items which can be checksummed and
                                294                 :                :  * operate on each one of them.  If "sizeonly" is true, the size of
                                295                 :                :  * all the items which have checksums is computed and returned back
                                296                 :                :  * to the caller without operating on the files.  This is used to compile
                                297                 :                :  * the total size of the data directory for progress reports.
                                298                 :                :  */
                                299                 :                : static int64
 2400 michael@paquier.xyz       300                 :             96 : scan_directory(const char *basedir, const char *subdir, bool sizeonly)
                                301                 :                : {
                                302                 :             96 :     int64       dirsize = 0;
                                303                 :                :     char        path[MAXPGPATH];
                                304                 :                :     DIR        *dir;
                                305                 :                :     struct dirent *de;
                                306                 :                : 
 2761 peter_e@gmx.net           307                 :             96 :     snprintf(path, sizeof(path), "%s/%s", basedir, subdir);
 2762 magnus@hagander.net       308                 :             96 :     dir = opendir(path);
                                309         [ -  + ]:             96 :     if (!dir)
 1298 tgl@sss.pgh.pa.us         310                 :UBC           0 :         pg_fatal("could not open directory \"%s\": %m", path);
 2762 magnus@hagander.net       311         [ +  + ]:CBC       13160 :     while ((de = readdir(dir)) != NULL)
                                312                 :                :     {
                                313                 :                :         char        fn[MAXPGPATH];
                                314                 :                :         struct stat st;
                                315                 :                : 
 2523 michael@paquier.xyz       316         [ +  + ]:          13072 :         if (strcmp(de->d_name, ".") == 0 ||
                                317         [ +  + ]:          12984 :             strcmp(de->d_name, "..") == 0)
 2762 magnus@hagander.net       318                 :           4197 :             continue;
                                319                 :                : 
                                320                 :                :         /* Skip temporary files */
 2523 michael@paquier.xyz       321         [ +  + ]:          12895 :         if (strncmp(de->d_name,
                                322                 :                :                     PG_TEMP_FILE_PREFIX,
                                323                 :                :                     strlen(PG_TEMP_FILE_PREFIX)) == 0)
                                324                 :             30 :             continue;
                                325                 :                : 
                                326                 :                :         /* Skip temporary folders */
                                327         [ -  + ]:          12865 :         if (strncmp(de->d_name,
                                328                 :                :                     PG_TEMP_FILES_DIR,
                                329                 :                :                     strlen(PG_TEMP_FILES_DIR)) == 0)
 2419 michael@paquier.xyz       330                 :UBC           0 :             continue;
                                331                 :                : 
                                332                 :                :         /* Skip macOS system files */
  622 dgustafsson@postgres      333         [ +  + ]:CBC       12865 :         if (strcmp(de->d_name, ".DS_Store") == 0)
                                334                 :             17 :             continue;
                                335                 :                : 
 2761 peter_e@gmx.net           336                 :          12848 :         snprintf(fn, sizeof(fn), "%s/%s", path, de->d_name);
 2762 magnus@hagander.net       337         [ -  + ]:          12848 :         if (lstat(fn, &st) < 0)
 1298 tgl@sss.pgh.pa.us         338                 :UBC           0 :             pg_fatal("could not stat file \"%s\": %m", fn);
 2762 magnus@hagander.net       339         [ +  + ]:CBC       12848 :         if (S_ISREG(st.st_mode))
                                340                 :                :         {
                                341                 :                :             char        fnonly[MAXPGPATH];
                                342                 :                :             char       *forkpath,
                                343                 :                :                        *segmentpath;
 1412 peter@eisentraut.org      344                 :          12799 :             int         segmentno = 0;
                                345                 :                : 
 2523 michael@paquier.xyz       346         [ +  + ]:          12799 :             if (skipfile(de->d_name))
                                347                 :           3973 :                 continue;
                                348                 :                : 
                                349                 :                :             /*
                                350                 :                :              * Cut off at the segment boundary (".") to get the segment number
                                351                 :                :              * in order to mix it into the checksum. Then also cut off at the
                                352                 :                :              * fork boundary, to get the filenode the file belongs to for
                                353                 :                :              * filtering.
                                354                 :                :              */
 2614 tgl@sss.pgh.pa.us         355                 :          12658 :             strlcpy(fnonly, de->d_name, sizeof(fnonly));
                                356                 :          12658 :             segmentpath = strchr(fnonly, '.');
 2762 magnus@hagander.net       357         [ +  + ]:          12658 :             if (segmentpath != NULL)
                                358                 :                :             {
                                359                 :             65 :                 *segmentpath++ = '\0';
                                360                 :             65 :                 segmentno = atoi(segmentpath);
                                361         [ -  + ]:             65 :                 if (segmentno == 0)
 1298 tgl@sss.pgh.pa.us         362                 :UBC           0 :                     pg_fatal("invalid segment number %d in file name \"%s\"",
                                363                 :                :                              segmentno, fn);
                                364                 :                :             }
                                365                 :                : 
 2614 tgl@sss.pgh.pa.us         366                 :CBC       12658 :             forkpath = strchr(fnonly, '_');
 2762 magnus@hagander.net       367         [ +  + ]:          12658 :             if (forkpath != NULL)
                                368                 :           3165 :                 *forkpath++ = '\0';
                                369                 :                : 
 2342 michael@paquier.xyz       370   [ +  +  +  + ]:          12658 :             if (only_filenode && strcmp(only_filenode, fnonly) != 0)
                                371                 :                :                 /* filenode not to be included */
 2762 magnus@hagander.net       372                 :           3832 :                 continue;
                                373                 :                : 
 2400 michael@paquier.xyz       374                 :           8826 :             dirsize += st.st_size;
                                375                 :                : 
                                376                 :                :             /*
                                377                 :                :              * No need to work on the file when calculating only the size of
                                378                 :                :              * the items in the data folder.
                                379                 :                :              */
                                380         [ +  - ]:           8826 :             if (!sizeonly)
                                381                 :           8826 :                 scan_file(fn, segmentno);
                                382                 :                :         }
 2762 magnus@hagander.net       383   [ +  +  +  - ]:             49 :         else if (S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode))
                                384                 :                :         {
                                385                 :                :             /*
                                386                 :                :              * If going through the entries of pg_tblspc, we assume to operate
                                387                 :                :              * on tablespace locations where only TABLESPACE_VERSION_DIRECTORY
                                388                 :                :              * is valid, resolving the linked locations and dive into them
                                389                 :                :              * directly.
                                390                 :                :              */
  419 michael@paquier.xyz       391         [ +  + ]:             49 :             if (strncmp(PG_TBLSPC_DIR, subdir, strlen(PG_TBLSPC_DIR)) == 0)
                                392                 :                :             {
                                393                 :                :                 char        tblspc_path[MAXPGPATH];
                                394                 :                :                 struct stat tblspc_st;
                                395                 :                : 
                                396                 :                :                 /*
                                397                 :                :                  * Resolve tablespace location path and check whether
                                398                 :                :                  * TABLESPACE_VERSION_DIRECTORY exists.  Not finding a valid
                                399                 :                :                  * location is unexpected, since there should be no orphaned
                                400                 :                :                  * links and no links pointing to something else than a
                                401                 :                :                  * directory.
                                402                 :                :                  */
 2069                           403                 :              5 :                 snprintf(tblspc_path, sizeof(tblspc_path), "%s/%s/%s",
                                404                 :              5 :                          path, de->d_name, TABLESPACE_VERSION_DIRECTORY);
                                405                 :                : 
                                406         [ -  + ]:              5 :                 if (lstat(tblspc_path, &tblspc_st) < 0)
 1298 tgl@sss.pgh.pa.us         407                 :UBC           0 :                     pg_fatal("could not stat file \"%s\": %m",
                                408                 :                :                              tblspc_path);
                                409                 :                : 
                                410                 :                :                 /*
                                411                 :                :                  * Move backwards once as the scan needs to happen for the
                                412                 :                :                  * contents of TABLESPACE_VERSION_DIRECTORY.
                                413                 :                :                  */
 2069 michael@paquier.xyz       414                 :CBC           5 :                 snprintf(tblspc_path, sizeof(tblspc_path), "%s/%s",
                                415                 :              5 :                          path, de->d_name);
                                416                 :                : 
                                417                 :                :                 /* Looks like a valid tablespace location */
                                418                 :              5 :                 dirsize += scan_directory(tblspc_path,
                                419                 :                :                                           TABLESPACE_VERSION_DIRECTORY,
                                420                 :                :                                           sizeonly);
                                421                 :                :             }
                                422                 :                :             else
                                423                 :                :             {
                                424                 :             44 :                 dirsize += scan_directory(path, de->d_name, sizeonly);
                                425                 :                :             }
                                426                 :                :         }
                                427                 :                :     }
 2762 magnus@hagander.net       428                 :             88 :     closedir(dir);
 2400 michael@paquier.xyz       429                 :             88 :     return dirsize;
                                430                 :                : }
                                431                 :                : 
                                432                 :                : int
 2762 magnus@hagander.net       433                 :             31 : main(int argc, char *argv[])
                                434                 :                : {
                                435                 :                :     static struct option long_options[] = {
                                436                 :                :         {"check", no_argument, NULL, 'c'},
                                437                 :                :         {"pgdata", required_argument, NULL, 'D'},
                                438                 :                :         {"disable", no_argument, NULL, 'd'},
                                439                 :                :         {"enable", no_argument, NULL, 'e'},
                                440                 :                :         {"filenode", required_argument, NULL, 'f'},
                                441                 :                :         {"no-sync", no_argument, NULL, 'N'},
                                442                 :                :         {"progress", no_argument, NULL, 'P'},
                                443                 :                :         {"verbose", no_argument, NULL, 'v'},
                                444                 :                :         {"sync-method", required_argument, NULL, 1},
                                445                 :                :         {NULL, 0, NULL, 0}
                                446                 :                :     };
                                447                 :                : 
                                448                 :             31 :     char       *DataDir = NULL;
                                449                 :                :     int         c;
                                450                 :                :     int         option_index;
                                451                 :                :     bool        crc_ok;
                                452                 :                :     uint32      major_version;
                                453                 :                :     char       *version_str;
                                454                 :                : 
 2401 peter@eisentraut.org      455                 :             31 :     pg_logging_init(argv[0]);
 2420 michael@paquier.xyz       456                 :             31 :     set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_checksums"));
 2762 magnus@hagander.net       457                 :             31 :     progname = get_progname(argv[0]);
                                458                 :                : 
                                459         [ +  - ]:             31 :     if (argc > 1)
                                460                 :                :     {
                                461   [ +  +  -  + ]:             31 :         if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
                                462                 :                :         {
                                463                 :              1 :             usage();
                                464                 :              1 :             exit(0);
                                465                 :                :         }
                                466   [ +  +  -  + ]:             30 :         if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
                                467                 :                :         {
 2420 michael@paquier.xyz       468                 :              1 :             puts("pg_checksums (PostgreSQL) " PG_VERSION);
 2762 magnus@hagander.net       469                 :              1 :             exit(0);
                                470                 :                :         }
                                471                 :                :     }
                                472                 :                : 
 1050 peter@eisentraut.org      473         [ +  + ]:             93 :     while ((c = getopt_long(argc, argv, "cdD:ef:NPv", long_options, &option_index)) != -1)
                                474                 :                :     {
 2762 magnus@hagander.net       475   [ +  +  +  +  :             65 :         switch (c)
                                     +  +  -  -  -  
                                                 + ]
                                476                 :                :         {
 2410 michael@paquier.xyz       477                 :             19 :             case 'c':
                                478                 :             19 :                 mode = PG_MODE_CHECK;
                                479                 :             19 :                 break;
                                480                 :              3 :             case 'd':
                                481                 :              3 :                 mode = PG_MODE_DISABLE;
                                482                 :              3 :                 break;
 1050 peter@eisentraut.org      483                 :             28 :             case 'D':
                                484                 :             28 :                 DataDir = optarg;
                                485                 :             28 :                 break;
 2410 michael@paquier.xyz       486                 :              4 :             case 'e':
                                487                 :              4 :                 mode = PG_MODE_ENABLE;
                                488                 :              4 :                 break;
 2342                           489                 :              6 :             case 'f':
 1125 rhaas@postgresql.org      490         [ -  + ]:              6 :                 if (!option_parse_int(optarg, "-f/--filenode", 0,
                                491                 :                :                                       INT_MAX,
                                492                 :                :                                       NULL))
 2342 michael@paquier.xyz       493                 :UBC           0 :                     exit(1);
 2342 michael@paquier.xyz       494                 :CBC           6 :                 only_filenode = pstrdup(optarg);
                                495                 :              6 :                 break;
 2410                           496                 :              4 :             case 'N':
                                497                 :              4 :                 do_sync = false;
                                498                 :              4 :                 break;
 2400 michael@paquier.xyz       499                 :UBC           0 :             case 'P':
                                500                 :              0 :                 showprogress = true;
                                501                 :              0 :                 break;
 1050 peter@eisentraut.org      502                 :              0 :             case 'v':
                                503                 :              0 :                 verbose = true;
                                504                 :              0 :                 break;
  782 nathan@postgresql.or      505                 :              0 :             case 1:
                                506         [ #  # ]:              0 :                 if (!parse_sync_method(optarg, &sync_method))
                                507                 :              0 :                     exit(1);
                                508                 :              0 :                 break;
 2762 magnus@hagander.net       509                 :CBC           1 :             default:
                                510                 :                :                 /* getopt_long already emitted a complaint */
 1298 tgl@sss.pgh.pa.us         511                 :              1 :                 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
 2762 magnus@hagander.net       512                 :              1 :                 exit(1);
                                513                 :                :         }
                                514                 :                :     }
                                515                 :                : 
                                516         [ -  + ]:             28 :     if (DataDir == NULL)
                                517                 :                :     {
 2762 magnus@hagander.net       518         [ #  # ]:UBC           0 :         if (optind < argc)
                                519                 :              0 :             DataDir = argv[optind++];
                                520                 :                :         else
                                521                 :              0 :             DataDir = getenv("PGDATA");
                                522                 :                : 
                                523                 :                :         /* If no DataDir was specified, and none could be found, error out */
                                524         [ #  # ]:              0 :         if (DataDir == NULL)
                                525                 :                :         {
 2401 peter@eisentraut.org      526                 :              0 :             pg_log_error("no data directory specified");
 1298 tgl@sss.pgh.pa.us         527                 :              0 :             pg_log_error_hint("Try \"%s --help\" for more information.", progname);
 2762 magnus@hagander.net       528                 :              0 :             exit(1);
                                529                 :                :         }
                                530                 :                :     }
                                531                 :                : 
                                532                 :                :     /* Complain if any arguments remain */
 2762 magnus@hagander.net       533         [ -  + ]:CBC          28 :     if (optind < argc)
                                534                 :                :     {
 2401 peter@eisentraut.org      535                 :UBC           0 :         pg_log_error("too many command-line arguments (first is \"%s\")",
                                536                 :                :                      argv[optind]);
 1298 tgl@sss.pgh.pa.us         537                 :              0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
 2762 magnus@hagander.net       538                 :              0 :         exit(1);
                                539                 :                :     }
                                540                 :                : 
                                541                 :                :     /* filenode checking only works in --check mode */
 2342 michael@paquier.xyz       542   [ +  +  +  + ]:CBC          28 :     if (mode != PG_MODE_CHECK && only_filenode)
                                543                 :                :     {
 2302 peter@eisentraut.org      544                 :              2 :         pg_log_error("option -f/--filenode can only be used with --check");
 1298 tgl@sss.pgh.pa.us         545                 :              2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
 2410 michael@paquier.xyz       546                 :              2 :         exit(1);
                                547                 :                :     }
                                548                 :                : 
                                549                 :                :     /*
                                550                 :                :      * Retrieve the contents of this cluster's PG_VERSION.  We require
                                551                 :                :      * compatibility with the same major version as the one this tool is
                                552                 :                :      * compiled with.
                                553                 :                :      */
    7 michael@paquier.xyz       554                 :GNC          26 :     major_version = GET_PG_MAJORVERSION_NUM(get_pg_version(DataDir, &version_str));
                                555         [ -  + ]:             26 :     if (major_version != PG_MAJORVERSION_NUM)
                                556                 :                :     {
    7 michael@paquier.xyz       557                 :UNC           0 :         pg_log_error("data directory is of wrong version");
                                558                 :              0 :         pg_log_error_detail("File \"%s\" contains \"%s\", which is not compatible with this program's version \"%s\".",
                                559                 :                :                             "PG_VERSION", version_str, PG_MAJORVERSION);
                                560                 :              0 :         exit(1);
                                561                 :                :     }
                                562                 :                : 
                                563                 :                :     /* Read the control file and check compatibility */
 2401 peter@eisentraut.org      564                 :CBC          26 :     ControlFile = get_controlfile(DataDir, &crc_ok);
 2762 magnus@hagander.net       565         [ -  + ]:             26 :     if (!crc_ok)
 1298 tgl@sss.pgh.pa.us         566                 :UBC           0 :         pg_fatal("pg_control CRC value is incorrect");
                                567                 :                : 
 2420 michael@paquier.xyz       568         [ -  + ]:CBC          26 :     if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
 1298 tgl@sss.pgh.pa.us         569                 :UBC           0 :         pg_fatal("cluster is not compatible with this version of pg_checksums");
                                570                 :                : 
 2415 michael@paquier.xyz       571         [ -  + ]:CBC          26 :     if (ControlFile->blcksz != BLCKSZ)
                                572                 :                :     {
 2401 peter@eisentraut.org      573                 :UBC           0 :         pg_log_error("database cluster is not compatible");
 1298 tgl@sss.pgh.pa.us         574                 :              0 :         pg_log_error_detail("The database cluster was initialized with block size %u, but pg_checksums was compiled with block size %u.",
                                575                 :                :                             ControlFile->blcksz, BLCKSZ);
 2415 michael@paquier.xyz       576                 :              0 :         exit(1);
                                577                 :                :     }
                                578                 :                : 
                                579                 :                :     /*
                                580                 :                :      * Check if cluster is running.  A clean shutdown is required to avoid
                                581                 :                :      * random checksum failures caused by torn pages.  Note that this doesn't
                                582                 :                :      * guard against someone starting the cluster concurrently.
                                583                 :                :      */
 2762 magnus@hagander.net       584         [ +  + ]:CBC          26 :     if (ControlFile->state != DB_SHUTDOWNED &&
                                585         [ +  - ]:              1 :         ControlFile->state != DB_SHUTDOWNED_IN_RECOVERY)
 1298 tgl@sss.pgh.pa.us         586                 :              1 :         pg_fatal("cluster must be shut down");
                                587                 :                : 
 2410 michael@paquier.xyz       588         [ +  + ]:             25 :     if (ControlFile->data_checksum_version == 0 &&
                                589         [ +  + ]:              4 :         mode == PG_MODE_CHECK)
 1298 tgl@sss.pgh.pa.us         590                 :              1 :         pg_fatal("data checksums are not enabled in cluster");
                                591                 :                : 
 2410 michael@paquier.xyz       592         [ +  + ]:             24 :     if (ControlFile->data_checksum_version == 0 &&
                                593         [ +  + ]:              3 :         mode == PG_MODE_DISABLE)
 1298 tgl@sss.pgh.pa.us         594                 :              1 :         pg_fatal("data checksums are already disabled in cluster");
                                595                 :                : 
 2410 michael@paquier.xyz       596         [ +  + ]:             23 :     if (ControlFile->data_checksum_version > 0 &&
                                597         [ +  + ]:             21 :         mode == PG_MODE_ENABLE)
 1298 tgl@sss.pgh.pa.us         598                 :              1 :         pg_fatal("data checksums are already enabled in cluster");
                                599                 :                : 
                                600                 :                :     /* Operate on all files if checking or enabling checksums */
 2410 michael@paquier.xyz       601   [ +  +  +  + ]:             22 :     if (mode == PG_MODE_CHECK || mode == PG_MODE_ENABLE)
                                602                 :                :     {
                                603                 :                :         /*
                                604                 :                :          * If progress status information is requested, we need to scan the
                                605                 :                :          * directory tree twice: once to know how much total data needs to be
                                606                 :                :          * processed and once to do the real work.
                                607                 :                :          */
 2400                           608         [ -  + ]:             21 :         if (showprogress)
                                609                 :                :         {
 2400 michael@paquier.xyz       610                 :UBC           0 :             total_size = scan_directory(DataDir, "global", true);
                                611                 :              0 :             total_size += scan_directory(DataDir, "base", true);
  419                           612                 :              0 :             total_size += scan_directory(DataDir, PG_TBLSPC_DIR, true);
                                613                 :                :         }
                                614                 :                : 
 2400 michael@paquier.xyz       615                 :CBC          21 :         (void) scan_directory(DataDir, "global", false);
                                616                 :             13 :         (void) scan_directory(DataDir, "base", false);
  419                           617                 :             13 :         (void) scan_directory(DataDir, PG_TBLSPC_DIR, false);
                                618                 :                : 
 2400                           619         [ -  + ]:             13 :         if (showprogress)
 2400 michael@paquier.xyz       620                 :UBC           0 :             progress_report(true);
                                621                 :                : 
 2410 michael@paquier.xyz       622                 :CBC          13 :         printf(_("Checksum operation completed\n"));
  239 peter@eisentraut.org      623                 :             13 :         printf(_("Files scanned:   %" PRId64 "\n"), files_scanned);
                                624                 :             13 :         printf(_("Blocks scanned:  %" PRId64 "\n"), blocks_scanned);
 2410 michael@paquier.xyz       625         [ +  + ]:             13 :         if (mode == PG_MODE_CHECK)
                                626                 :                :         {
  239 peter@eisentraut.org      627                 :             11 :             printf(_("Bad checksums:  %" PRId64 "\n"), badblocks);
 1791 bruce@momjian.us          628                 :             11 :             printf(_("Data checksum version: %u\n"), ControlFile->data_checksum_version);
                                629                 :                : 
 2410 michael@paquier.xyz       630         [ +  + ]:             11 :             if (badblocks > 0)
                                631                 :              4 :                 exit(1);
                                632                 :                :         }
 1580                           633         [ +  - ]:              2 :         else if (mode == PG_MODE_ENABLE)
                                634                 :                :         {
  239 peter@eisentraut.org      635                 :              2 :             printf(_("Files written:  %" PRId64 "\n"), files_written);
                                636                 :              2 :             printf(_("Blocks written: %" PRId64 "\n"), blocks_written);
                                637                 :                :         }
                                638                 :                :     }
                                639                 :                : 
                                640                 :                :     /*
                                641                 :                :      * Finally make the data durable on disk if enabling or disabling
                                642                 :                :      * checksums.  Flush first the data directory for safety, and then update
                                643                 :                :      * the control file to keep the switch consistent.
                                644                 :                :      */
 2410 michael@paquier.xyz       645   [ +  +  +  + ]:             10 :     if (mode == PG_MODE_ENABLE || mode == PG_MODE_DISABLE)
                                646                 :                :     {
                                647                 :              3 :         ControlFile->data_checksum_version =
                                648                 :              3 :             (mode == PG_MODE_ENABLE) ? PG_DATA_CHECKSUM_VERSION : 0;
                                649                 :                : 
                                650         [ +  + ]:              3 :         if (do_sync)
                                651                 :                :         {
 2401 peter@eisentraut.org      652                 :              1 :             pg_log_info("syncing data directory");
  216 nathan@postgresql.or      653                 :              1 :             sync_pgdata(DataDir, PG_VERSION_NUM, sync_method, true);
                                654                 :                :         }
                                655                 :                : 
 2401 peter@eisentraut.org      656                 :              3 :         pg_log_info("updating control file");
                                657                 :              3 :         update_controlfile(DataDir, ControlFile, do_sync);
                                658                 :                : 
 2410 michael@paquier.xyz       659         [ -  + ]:              3 :         if (verbose)
 1791 bruce@momjian.us          660                 :UBC           0 :             printf(_("Data checksum version: %u\n"), ControlFile->data_checksum_version);
 2410 michael@paquier.xyz       661         [ +  + ]:CBC           3 :         if (mode == PG_MODE_ENABLE)
                                662                 :              2 :             printf(_("Checksums enabled in cluster\n"));
                                663                 :                :         else
                                664                 :              1 :             printf(_("Checksums disabled in cluster\n"));
                                665                 :                :     }
                                666                 :                : 
 2762 magnus@hagander.net       667                 :             10 :     return 0;
                                668                 :                : }
        

Generated by: LCOV version 2.4-beta