LCOV - code coverage report
Current view: top level - cmdline - unix.c (source / functions) Hit Total Coverage
Test: lcov.info Lines: 517 673 76.8 %
Date: 2026-02-28 16:42:47 Functions: 37 42 88.1 %

          Line data    Source code
       1             : /*
       2             :  * Copyright (C) 2013 Andrea Mazzoleni
       3             :  *
       4             :  * This program is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 3 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * This program is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "portable.h"
      19             : 
      20             : #ifndef __MINGW32__ /* Only for Unix */
      21             : 
      22             : #include "support.h"
      23             : 
      24             : /**
      25             :  * Exit codes.
      26             :  */
      27             : int exit_success = 0;
      28             : int exit_failure = 1;
      29             : int exit_sync_needed = 2;
      30             : 
      31     1786051 : int open_noatime(const char* file, int flags)
      32             : {
      33             : #ifdef O_NOATIME
      34     1786051 :         int f = open(file, flags | O_NOATIME);
      35             : 
      36             :         /* only root is allowed to use O_NOATIME, in case retry without it */
      37     1786051 :         if (f == -1 && errno == EPERM)
      38           0 :                 f = open(file, flags);
      39     1786051 :         return f;
      40             : #else
      41             :         return open(file, flags);
      42             : #endif
      43             : }
      44             : 
      45           0 : int dirent_hidden(struct dirent* dd)
      46             : {
      47           0 :         return dd->d_name[0] == '.';
      48             : }
      49             : 
      50           0 : const char* stat_desc(struct stat* st)
      51             : {
      52           0 :         if (S_ISREG(st->st_mode))
      53           0 :                 return "regular";
      54           0 :         if (S_ISDIR(st->st_mode))
      55           0 :                 return "directory";
      56           0 :         if (S_ISCHR(st->st_mode))
      57           0 :                 return "character";
      58           0 :         if (S_ISBLK(st->st_mode))
      59           0 :                 return "block-device";
      60           0 :         if (S_ISFIFO(st->st_mode))
      61           0 :                 return "fifo";
      62           0 :         if (S_ISLNK(st->st_mode))
      63           0 :                 return "link";
      64           0 :         if (S_ISLNK(st->st_mode))
      65           0 :                 return "symbolic-link";
      66           0 :         if (S_ISSOCK(st->st_mode))
      67           0 :                 return "socket";
      68           0 :         return "unknown";
      69             : }
      70             : 
      71             : static const char* smartctl_paths[] = {
      72             :         /* Linux & BSD */
      73             :         "/usr/sbin/smartctl",
      74             :         "/sbin/smartctl",
      75             :         "/usr/local/sbin/smartctl",
      76             :         "/usr/bin/smartctl",
      77             :         "/usr/local/bin/smartctl",
      78             :         /* macOS (Intel & Apple Silicon) */
      79             :         "/opt/homebrew/sbin/smartctl",
      80             :         0
      81             : };
      82             : 
      83          71 : const char* find_smartctl(void)
      84             : {
      85             :         int i;
      86             : 
      87          71 :         for (i = 0; smartctl_paths[i]; ++i) {
      88          71 :                 if (access(smartctl_paths[i], X_OK) == 0)
      89          71 :                         return smartctl_paths[i];
      90             :         }
      91             : 
      92           0 :         return 0;
      93             : }
      94             : 
      95             : /**
      96             :  * Read a file from sys
      97             :  *
      98             :  * Return -1 on error, otherwise the size of data read
      99             :  */
     100             : #if HAVE_LINUX_DEVICE
     101         686 : static int sysread(const char* path, char* buf, size_t buf_size)
     102             : {
     103             :         int f;
     104             :         int ret;
     105             :         int len;
     106             : 
     107         686 :         f = open(path, O_RDONLY);
     108         686 :         if (f == -1) {
     109             :                 /* LCOV_EXCL_START */
     110             :                 return -1;
     111             :                 /* LCOV_EXCL_STOP */
     112             :         }
     113             : 
     114         632 :         len = read(f, buf, buf_size);
     115         632 :         if (len < 0) {
     116             :                 /* LCOV_EXCL_START */
     117             :                 close(f);
     118             :                 return -1;
     119             :                 /* LCOV_EXCL_STOP */
     120             :         }
     121             : 
     122         632 :         ret = close(f);
     123         632 :         if (ret != 0) {
     124             :                 /* LCOV_EXCL_START */
     125             :                 return -1;
     126             :                 /* LCOV_EXCL_STOP */
     127             :         }
     128             : 
     129         632 :         return len;
     130             : }
     131             : #endif
     132             : 
     133             : /**
     134             :  * Read a file from sys.
     135             :  * Trim spaces.
     136             :  * Always put an ending 0.
     137             :  * Do not report error on reading.
     138             :  * Return an error if truncated
     139             :  *
     140             :  * Return -1 on error, 0 on success
     141             :  */
     142             : #if HAVE_LINUX_DEVICE
     143         102 : static int sysattr(const char* path, char* buf, size_t buf_size)
     144             : {
     145             :         int len;
     146             : 
     147         102 :         len = sysread(path, buf, buf_size);
     148         102 :         if (len < 0) {
     149             :                 /* LCOV_EXCL_START */
     150             :                 return -1;
     151             :                 /* LCOV_EXCL_STOP */
     152             :         }
     153             : 
     154          48 :         if ((size_t)len + 1 > buf_size) {
     155             :                 /* LCOV_EXCL_START */
     156             :                 return -1;
     157             :                 /* LCOV_EXCL_STOP */
     158             :         }
     159             : 
     160          48 :         buf[len] = 0;
     161             : 
     162          48 :         strtrim(buf);
     163             : 
     164          48 :         return 0;
     165             : }
     166             : #endif
     167             : 
     168             : /**
     169             :  * Get the device file from the device number.
     170             :  *
     171             :  * It uses /proc/self/mountinfo.
     172             :  *
     173             :  * Null devices (major==0) are resolved to the device indicated in mountinfo.
     174             :  */
     175             : #if HAVE_LINUX_DEVICE
     176           4 : static int devresolve_proc(uint64_t device, char* path, size_t path_size)
     177             : {
     178             :         FILE* f;
     179             :         char match[32];
     180             : 
     181             :         /* generate the matching string */
     182           4 :         snprintf(match, sizeof(match), "%u:%u", major(device), minor(device));
     183             : 
     184           4 :         f = fopen("/proc/self/mountinfo", "r");
     185           4 :         if (!f) {
     186           0 :                 log_tag("resolve:proc:%u:%u: failed to open /proc/self/mountinfo\n", major(device), minor(device));
     187           0 :                 return -1;
     188             :         }
     189             : 
     190             :         /*
     191             :          * mountinfo format
     192             :          * 0 - mount ID
     193             :          * 1 - parent ID
     194             :          * 2 - major:minor
     195             :          * 3 - root
     196             :          * 4 - mount point
     197             :          * 5 - options
     198             :          * 6 - "-" (separator)
     199             :          * 7 - fs
     200             :          * 8 - mount source - /dev/device
     201             :          */
     202             : 
     203         192 :         while (1) {
     204             :                 char buf[256];
     205             :                 char* first_map[8];
     206             :                 unsigned first_mac;
     207             :                 char* second_map[8];
     208             :                 unsigned second_mac;
     209             :                 char* s;
     210             :                 struct stat st;
     211             :                 char* separator;
     212             :                 char* majorminor;
     213             :                 char* mountpoint;
     214             :                 char* fs;
     215             :                 char* mountsource;
     216             : 
     217         196 :                 s = fgets(buf, sizeof(buf), f);
     218         196 :                 if (s == 0)
     219           4 :                         break;
     220             : 
     221             :                 /* find the separator position */
     222         192 :                 separator = strstr(s, " - ");
     223         192 :                 if (!separator)
     224           0 :                         continue;
     225             : 
     226             :                 /* skip the separator */
     227         192 :                 *separator = 0;
     228         192 :                 separator += 3;
     229             : 
     230             :                 /* split the line */
     231         192 :                 first_mac = strsplit(first_map, 8, s, " \t\r\n");
     232         192 :                 second_mac = strsplit(second_map, 8, separator, " \t\r\n");
     233             : 
     234             :                 /* if too short, it's the wrong line */
     235         192 :                 if (first_mac < 5)
     236           0 :                         continue;
     237         192 :                 if (second_mac < 2)
     238           0 :                         continue;
     239             : 
     240         192 :                 majorminor = first_map[2];
     241         192 :                 mountpoint = first_map[4];
     242         192 :                 fs = second_map[0];
     243         192 :                 mountsource = second_map[1];
     244             : 
     245             :                 /* compare major:minor from mountinfo */
     246         192 :                 if (strcmp(majorminor, match) == 0) {
     247             :                         /*
     248             :                          * Accept only /dev/... mountsource
     249             :                          *
     250             :                          * This excludes ZFS that uses a bare label for mountsource, like "tank".
     251             :                          *
     252             :                          * 410 408 0:193 / /XXX rw,relatime shared:217 - zfs tank/system/data/var/lib/docker/XXX rw,xattr,noacl
     253             :                          *
     254             :                          * Also excludes AUTOFS unmounted devices that point to a fake filesystem
     255             :                          * used to remount them at the first use.
     256             :                          *
     257             :                          * 97 25 0:42 / /XXX rw,relatime shared:76 - autofs /etc/auto.seed rw,fd=6,pgrp=952,timeout=30,minproto=5,maxproto=5,indirect
     258             :                          */
     259           0 :                         if (strncmp(mountsource, "/dev/", 5) != 0) {
     260           0 :                                 log_tag("resolve:proc:%u:%u: match skipped for not /dev/ mountsource for %s %s\n", major(device), minor(device), fs, mountsource);
     261           0 :                                 continue;
     262             :                         }
     263             : 
     264           0 :                         pathcpy(path, path_size, mountsource);
     265             : 
     266           0 :                         log_tag("resolve:proc:%u:%u: found device %s matching device %s\n", major(device), minor(device), path, match);
     267             : 
     268           0 :                         fclose(f);
     269           0 :                         return 0;
     270             :                 }
     271             : 
     272             :                 /* get the device of the mount point */
     273             :                 /* in Btrfs it could be different than the one in mountinfo */
     274         192 :                 if (stat(mountpoint, &st) == 0 && st.st_dev == device) {
     275           0 :                         if (strncmp(mountsource, "/dev/", 5) != 0) {
     276           0 :                                 log_tag("resolve:proc:%u:%u: match skipped for not /dev/ mountsource for %s %s\n", major(device), minor(device), fs, mountsource);
     277           0 :                                 continue;
     278             :                         }
     279             : 
     280           0 :                         pathcpy(path, path_size, mountsource);
     281             : 
     282           0 :                         log_tag("resolve:proc:%u:%u: found device %s matching mountpoint %s\n", major(device), minor(device), path, mountpoint);
     283             : 
     284           0 :                         fclose(f);
     285           0 :                         return 0;
     286             :                 }
     287             :         }
     288             : 
     289           4 :         log_tag("resolve:proc:%u:%u: not found\n", major(device), minor(device));
     290             : 
     291           4 :         fclose(f);
     292           4 :         return -1;
     293             : }
     294             : #endif
     295             : 
     296             : /**
     297             :  * Get the device of a virtual superblock.
     298             :  *
     299             :  * This is intended to resolve the case of Btrfs filesystems that
     300             :  * create a virtual superblock (major==0) not backed by any low
     301             :  * level device.
     302             :  *
     303             :  * See:
     304             :  * Bug 711881 - too funny btrfs st_dev numbers
     305             :  * https://bugzilla.redhat.com/show_bug.cgi?id=711881
     306             :  */
     307             : #if HAVE_LINUX_DEVICE
     308           4 : static int devdereference(uint64_t device, uint64_t* new_device)
     309             : {
     310             :         char path[PATH_MAX];
     311             :         struct stat st;
     312             : 
     313             :         /* use the proc interface to get the device containing the filesystem */
     314           4 :         if (devresolve_proc(device, path, sizeof(path)) != 0) {
     315             :                 /* LCOV_EXCL_START */
     316             :                 return -1;
     317             :                 /* LCOV_EXCL_STOP */
     318             :         }
     319             : 
     320             :         /* check the device */
     321           0 :         if (stat(path, &st) != 0) {
     322             :                 /* LCOV_EXCL_START */
     323             :                 log_tag("dereference:%u:%u: failed to stat %s\n", major(device), minor(device), path);
     324             :                 return -1;
     325             :                 /* LCOV_EXCL_STOP */
     326             :         }
     327             : 
     328           0 :         if (major(st.st_rdev) == 0) {
     329             :                 /* LCOV_EXCL_START */
     330             :                 log_tag("dereference:%u:%u: still null device %s -> %u:%u\n", major(device), minor(device), path, major(st.st_rdev), minor(st.st_rdev));
     331             :                 return -1;
     332             :                 /* LCOV_EXCL_STOP */
     333             :         }
     334             : 
     335           0 :         *new_device = st.st_rdev;
     336           0 :         log_tag("dereference:%u:%u: found %u:%u\n", major(device), minor(device), major(st.st_rdev), minor(st.st_rdev));
     337           0 :         return 0;
     338             : }
     339             : #endif
     340             : 
     341             : /**
     342             :  * Read a file extracting the specified tag TAG=VALUE format.
     343             :  * Return !=0 on error.
     344             :  */
     345             : #if HAVE_LINUX_DEVICE
     346         393 : static int tagread(const char* path, const char* tag, char* value, size_t value_size)
     347             : {
     348             :         int ret;
     349             :         char buf[512];
     350             :         size_t tag_len;
     351             :         char* i;
     352             :         char* e;
     353             : 
     354         393 :         ret = sysread(path, buf, sizeof(buf));
     355         393 :         if (ret < 0) {
     356             :                 /* LCOV_EXCL_START */
     357             :                 log_fatal(errno, "Failed to read '%s'.\n", path);
     358             :                 return -1;
     359             :                 /* LCOV_EXCL_STOP */
     360             :         }
     361         393 :         if ((size_t)ret + 1 > sizeof(buf)) {
     362             :                 /* LCOV_EXCL_START */
     363             :                 log_fatal(EEXTERNAL, "Too long read '%s'.\n", path);
     364             :                 return -1;
     365             :                 /* LCOV_EXCL_STOP */
     366             :         }
     367             : 
     368             :         /* ending 0 */
     369         393 :         buf[ret] = 0;
     370             : 
     371         393 :         tag_len = strlen(tag);
     372             : 
     373        6908 :         for (i = buf; *i; ++i) {
     374        6908 :                 char* p = i;
     375             : 
     376             :                 /* start with a space */
     377        6908 :                 if (p != buf) {
     378        6515 :                         if (!isspace(*p))
     379        5729 :                                 continue;
     380         786 :                         ++p;
     381             :                 }
     382             : 
     383        1179 :                 if (strncmp(p, tag, tag_len) != 0)
     384         786 :                         continue;
     385         393 :                 p += tag_len;
     386             : 
     387             :                 /* end with a = */
     388         393 :                 if (*p != '=')
     389           0 :                         continue;
     390         393 :                 ++p;
     391             : 
     392             :                 /* found */
     393         393 :                 i = p;
     394         393 :                 break;
     395             :         }
     396         393 :         if (!*i) {
     397             :                 /* LCOV_EXCL_START */
     398             :                 log_fatal(EEXTERNAL, "Missing tag '%s' for '%s'.\n", tag, path);
     399             :                 return -1;
     400             :                 /* LCOV_EXCL_STOP */
     401             :         }
     402             : 
     403             :         /* terminate at the first space */
     404         393 :         e = i;
     405        1733 :         while (*e != 0 && !isspace(*e))
     406        1340 :                 ++e;
     407         393 :         *e = 0;
     408             : 
     409         393 :         if (!*i) {
     410             :                 /* LCOV_EXCL_START */
     411             :                 log_fatal(EEXTERNAL, "Empty tag '%s' for '%s'.\n", tag, path);
     412             :                 return -1;
     413             :                 /* LCOV_EXCL_STOP */
     414             :         }
     415             : 
     416         393 :         pathprint(value, value_size, "%s", i);
     417             : 
     418         393 :         return 0;
     419             : }
     420             : #endif
     421             : 
     422             : /**
     423             :  * Get the device file from the device number.
     424             :  *
     425             :  * It uses /sys/dev/block/.../uevent.
     426             :  *
     427             :  * For null device (major==0) it fails.
     428             :  */
     429             : #if HAVE_LINUX_DEVICE
     430         393 : static int devresolve_sys(dev_t device, char* path, size_t path_size)
     431             : {
     432             :         struct stat st;
     433             :         char buf[PATH_MAX];
     434             : 
     435             :         /* default device path from device number */
     436         393 :         pathprint(path, path_size, "/sys/dev/block/%u:%u/uevent", major(device), minor(device));
     437             : 
     438         393 :         if (tagread(path, "DEVNAME", buf, sizeof(buf)) != 0) {
     439             :                 /* LCOV_EXCL_START */
     440             :                 log_tag("resolve:sys:%u:%u: failed to read DEVNAME tag '%s'\n", major(device), minor(device), path);
     441             :                 return -1;
     442             :                 /* LCOV_EXCL_STOP */
     443             :         }
     444             : 
     445             :         /* set the real device path */
     446         393 :         pathprint(path, path_size, "/dev/%s", buf);
     447             : 
     448             :         /* check the device */
     449         393 :         if (stat(path, &st) != 0) {
     450             :                 /* LCOV_EXCL_START */
     451             :                 log_tag("resolve:sys:%u:%u: failed to stat '%s'\n", major(device), minor(device), path);
     452             :                 return -1;
     453             :                 /* LCOV_EXCL_STOP */
     454             :         }
     455         393 :         if (st.st_rdev != device) {
     456             :                 /* LCOV_EXCL_START */
     457             :                 log_tag("resolve:sys:%u:%u: unexpected device '%u:%u' for '%s'.\n", major(device), minor(device), major(st.st_rdev), minor(st.st_rdev), path);
     458             :                 return -1;
     459             :                 /* LCOV_EXCL_STOP */
     460             :         }
     461             : 
     462         393 :         log_tag("resolve:sys:%u:%u:%s: found\n", major(device), minor(device), path);
     463             : 
     464         393 :         return 0;
     465             : }
     466             : #endif
     467             : 
     468             : /**
     469             :  * Get the device file from the device number.
     470             :  */
     471             : #if HAVE_LINUX_DEVICE
     472         393 : static int devresolve(uint64_t device, char* path, size_t path_size)
     473             : {
     474         393 :         if (devresolve_sys(device, path, path_size) == 0)
     475         393 :                 return 0;
     476             : 
     477           0 :         return -1;
     478             : }
     479             : #endif
     480             : 
     481             : /**
     482             :  * Cache used by blkid.
     483             :  */
     484             : #if HAVE_BLKID
     485             : static blkid_cache cache = 0;
     486             : #endif
     487             : 
     488             : /**
     489             :  * Get the UUID using the /dev/disk/by-uuid/ links.
     490             :  * It doesn't require root permission, and the uuid are always updated.
     491             :  * It doesn't work with Btrfs file-systems that don't export the main UUID
     492             :  * in /dev/disk/by-uuid/.
     493             :  */
     494             : #if HAVE_LINUX_DEVICE
     495       10896 : static int devuuid_dev(uint64_t device, char* uuid, size_t uuid_size)
     496             : {
     497             :         int ret;
     498             :         DIR* d;
     499             :         struct dirent* dd;
     500             :         struct stat st;
     501             : 
     502             :         /* scan the UUID directory searching for the device */
     503       10896 :         d = opendir("/dev/disk/by-uuid");
     504       10896 :         if (!d) {
     505           0 :                 log_tag("uuid:by-uuid:%u:%u: opendir(/dev/disk/by-uuid) failed, %s\n", major(device), minor(device), strerror(errno));
     506             :                 /* directory missing?, likely we are not in Linux */
     507           0 :                 return -1;
     508             :         }
     509             : 
     510       10896 :         int dir_fd = dirfd(d);
     511       10896 :         if (dir_fd == -1) {
     512           0 :                 log_tag("uuid:by-uuid:%u:%u: dirfd(/dev/disk/by-uuid) failed, %s\n", major(device), minor(device), strerror(errno));
     513           0 :                 return -1;
     514             :         }
     515             : 
     516      173796 :         while ((dd = readdir(d)) != 0) {
     517             :                 /* skip "." and ".." files, UUIDs never start with '.' */
     518      173796 :                 if (dd->d_name[0] == '.')
     519       21792 :                         continue;
     520             : 
     521      152004 :                 ret = fstatat(dir_fd, dd->d_name, &st, 0);
     522      152004 :                 if (ret != 0) {
     523           0 :                         log_tag("uuid:by-uuid:%u:%u: fstatat(%s) failed, %s\n", major(device), minor(device), dd->d_name, strerror(errno));
     524             :                         /* generic error, ignore and continue the search */
     525           0 :                         continue;
     526             :                 }
     527             : 
     528             :                 /* if it matches, we have the uuid */
     529      152004 :                 if (S_ISBLK(st.st_mode) && st.st_rdev == (dev_t)device) {
     530             :                         char buf[PATH_MAX];
     531             :                         char path[PATH_MAX];
     532             : 
     533             :                         /* resolve the link */
     534       10896 :                         pathprint(path, sizeof(path), "/dev/disk/by-uuid/%s", dd->d_name);
     535       10896 :                         ret = readlink(path, buf, sizeof(buf));
     536       10896 :                         if (ret < 0 || ret >= PATH_MAX) {
     537           0 :                                 log_tag("uuid:by-uuid:%u:%u: readlink(/dev/disk/by-uuid/%s) failed, %s\n", major(device), minor(device), dd->d_name, strerror(errno));
     538             :                                 /* generic error, ignore and continue the search */
     539           0 :                                 continue;
     540             :                         }
     541       10896 :                         buf[ret] = 0;
     542             : 
     543             :                         /* found */
     544       10896 :                         pathcpy(uuid, uuid_size, dd->d_name);
     545             : 
     546       10896 :                         log_tag("uuid:by-uuid:%u:%u:%s: found %s\n", major(device), minor(device), uuid, buf);
     547             : 
     548       10896 :                         closedir(d);
     549       10896 :                         return 0;
     550             :                 }
     551             :         }
     552             : 
     553           0 :         log_tag("uuid:by-uuid:%u:%u: /dev/disk/by-uuid doesn't contain a matching block device\n", major(device), minor(device));
     554             : 
     555             :         /* not found */
     556           0 :         closedir(d);
     557           0 :         return -1;
     558             : }
     559             : #endif
     560             : 
     561             : /**
     562             :  * Get the UUID using libblkid.
     563             :  * It uses a cache to work without root permission, resulting in UUID
     564             :  * not necessarily recent.
     565             :  * We could call blkid_probe_all() to refresh the UUID, but it would
     566             :  * require root permission to read the superblocks, and resulting in
     567             :  * all the disks spinning.
     568             :  */
     569             : #if HAVE_BLKID
     570           0 : static int devuuid_blkid(uint64_t device, char* uuid, size_t uuid_size)
     571             : {
     572             :         char* devname;
     573             :         char* uuidname;
     574             : 
     575           0 :         devname = blkid_devno_to_devname(device);
     576           0 :         if (!devname) {
     577           0 :                 log_tag("uuid:blkid:%u:%u: blkid_devno_to_devname() failed, %s\n", major(device), minor(device), strerror(errno));
     578             :                 /* device mapping failed */
     579           0 :                 return -1;
     580             :         }
     581             : 
     582           0 :         uuidname = blkid_get_tag_value(cache, "UUID", devname);
     583           0 :         if (!uuidname) {
     584           0 :                 log_tag("uuid:blkid:%u:%u: blkid_get_tag_value(UUID,%s) failed, %s\n", major(device), minor(device), devname, strerror(errno));
     585             :                 /* uuid mapping failed */
     586           0 :                 free(devname);
     587           0 :                 return -1;
     588             :         }
     589             : 
     590           0 :         pathcpy(uuid, uuid_size, uuidname);
     591             : 
     592           0 :         log_tag("uuid:blkid:%u:%u:%s: found %s\n", major(device), minor(device), uuid, devname);
     593             : 
     594           0 :         free(devname);
     595           0 :         free(uuidname);
     596           0 :         return 0;
     597             : }
     598             : #endif
     599             : 
     600             : 
     601             : /**
     602             :  * Get the LABEL using libblkid.
     603             :  * It uses a cache to work without root permission, resulting in LABEL
     604             :  * not necessarily recent.
     605             :  */
     606             : #if HAVE_BLKID
     607        5919 : static int devuuid_label(uint64_t device, char* label, size_t label_size)
     608             : {
     609             :         char* devname;
     610             :         char* labelname;
     611             : 
     612        5919 :         devname = blkid_devno_to_devname(device);
     613        5919 :         if (!devname) {
     614           0 :                 log_tag("label:blkid:%u:%u: blkid_devno_to_devname() failed, %s\n", major(device), minor(device), strerror(errno));
     615             :                 /* device mapping failed */
     616           0 :                 return -1;
     617             :         }
     618             : 
     619        5919 :         labelname = blkid_get_tag_value(cache, "LABEL", devname);
     620        5919 :         if (!labelname) {
     621        5919 :                 log_tag("label:blkid:%u:%u: blkid_get_tag_value(LABEL,%s) failed, %s\n", major(device), minor(device), devname, strerror(errno));
     622        5919 :                 free(devname);
     623             :                 /* label mapping failed */
     624        5919 :                 return -1;
     625             :         }
     626             : 
     627           0 :         pathcpy(label, label_size, labelname);
     628             : 
     629           0 :         log_tag("label:blkid:%u:%u:%s: found %s\n", major(device), minor(device), label, devname);
     630             : 
     631           0 :         free(devname);
     632           0 :         free(labelname);
     633           0 :         return 0;
     634             : }
     635             : #endif
     636             : 
     637             : 
     638             : #ifdef __APPLE__
     639             : static int devuuid_darwin(const char* path, char* uuid, size_t uuid_size)
     640             : {
     641             :         CFStringRef path_apple = 0;
     642             :         DASessionRef session = 0;
     643             :         CFURLRef path_appler = 0;
     644             :         int result = -1;
     645             : 
     646             :         *uuid = 0;
     647             : 
     648             :         path_apple = CFStringCreateWithCString(kCFAllocatorDefault, path, kCFStringEncodingUTF8);
     649             :         if (!path_apple)
     650             :                 goto bail;
     651             : 
     652             :         session = DASessionCreate(kCFAllocatorDefault);
     653             :         if (!session)
     654             :                 goto bail;
     655             : 
     656             :         path_appler = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, path_apple, kCFURLPOSIXPathStyle, false);
     657             :         if (!path_appler)
     658             :                 goto bail;
     659             : 
     660             :         /* find the mount point */
     661             :         DADiskRef disk = NULL;
     662             :         while (path_appler) {
     663             :                 disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, path_appler);
     664             :                 if (disk)
     665             :                         break;
     666             : 
     667             :                 CFURLRef parent = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, path_appler);
     668             :                 if (!parent)
     669             :                         break;
     670             : 
     671             :                 /* check if we hit the root (parent == child) */
     672             :                 if (CFEqual(parent, path_appler)) {
     673             :                         CFRelease(parent);
     674             :                         break;
     675             :                 }
     676             : 
     677             :                 CFRelease(path_appler);
     678             :                 path_appler = parent;
     679             :         }
     680             : 
     681             :         /* safely extract the UUID */
     682             :         if (disk) {
     683             :                 CFDictionaryRef description = DADiskCopyDescription(disk);
     684             :                 if (description) {
     685             :                         /* key might not exist for NTFS/ExFAT on some drivers */
     686             :                         const void* value = (CFUUIDRef)CFDictionaryGetValue(description, kDADiskDescriptionVolumeUUIDKey);
     687             :                         CFStringRef uuid_string = NULL;
     688             : 
     689             :                         if (value) {
     690             :                                 if (CFGetTypeID(value) == CFUUIDGetTypeID()) {
     691             :                                         uuid_string = CFUUIDCreateString(kCFAllocatorDefault, (CFUUIDRef)value);
     692             :                                 } else if (CFGetTypeID(value) == CFStringGetTypeID()) {
     693             :                                         /* if it's already a string, retain it so we can release it later consistently */
     694             :                                         uuid_string = (CFStringRef)CFRetain(value);
     695             :                                 }
     696             :                         }
     697             : 
     698             :                         if (uuid_string) {
     699             :                                 if (CFStringGetCString(uuid_string, uuid, uuid_size, kCFStringEncodingUTF8)) {
     700             :                                         result = 0; /* success */
     701             :                                 }
     702             :                                 CFRelease(uuid_string);
     703             :                         }
     704             : 
     705             :                         CFRelease(description);
     706             :                 }
     707             :                 CFRelease(disk);
     708             :         }
     709             : 
     710             : bail:
     711             :         /* clean up */
     712             :         if (path_appler) CFRelease(path_appler);
     713             :         if (session) CFRelease(session);
     714             :         if (path_apple) CFRelease(path_apple);
     715             : 
     716             :         return result;
     717             : }
     718             : #endif
     719             : 
     720       10900 : int devuuid(uint64_t device, const char* path, char* uuid, size_t uuid_size)
     721             : {
     722             :         (void)path;
     723             :         (void)device;
     724             : 
     725             : #ifdef __APPLE__
     726             :         if (devuuid_darwin(path, uuid, uuid_size) == 0)
     727             :                 return 0;
     728             : #endif
     729             : 
     730             : #if HAVE_LINUX_DEVICE
     731             :         /* if the major is the null device */
     732       10900 :         if (major(device) == 0) {
     733             :                 /* obtain the real device */
     734           4 :                 if (devdereference(device, &device) != 0) {
     735             :                         /* LCOV_EXCL_START */
     736             :                         return -1;
     737             :                         /* LCOV_EXCL_STOP */
     738             :                 }
     739             :         }
     740             : #endif
     741             : 
     742             :         /* first try with the /dev/disk/by-uuid version */
     743             : #if HAVE_LINUX_DEVICE
     744       10896 :         if (devuuid_dev(device, uuid, uuid_size) == 0)
     745       10896 :                 return 0;
     746             : #else
     747             :         log_tag("uuid:by-uuid:%u:%u: by-uuid not supported\n", major(device), minor(device));
     748             : #endif
     749             : 
     750             :         /* fall back to blkid for other cases */
     751             : #if HAVE_BLKID
     752           0 :         if (devuuid_blkid(device, uuid, uuid_size) == 0)
     753           0 :                 return 0;
     754             : #else
     755             :         log_tag("uuid:blkid:%u:%u: blkid support not compiled in\n", major(device), minor(device));
     756             : #endif
     757             : 
     758           0 :         log_tag("uuid:notfound:%u:%u:\n", major(device), minor(device));
     759             : 
     760             :         /* not supported */
     761             :         (void)uuid;
     762             :         (void)uuid_size;
     763           0 :         return -1;
     764             : }
     765             : 
     766       11432 : int filephy(const char* path, uint64_t size, uint64_t* physical)
     767             : {
     768             : #if HAVE_LINUX_FIEMAP_H
     769             :         /* In Linux get the real physical address of the file */
     770             :         /* Note that FIEMAP doesn't require root permission */
     771             :         int f;
     772             :         struct fiemap* fiemap;
     773             :         size_t fiemap_size;
     774             :         unsigned int blknum;
     775             : 
     776       11432 :         f = open(path, O_RDONLY);
     777       11432 :         if (f == -1) {
     778           0 :                 return -1;
     779             :         }
     780             : 
     781             :         /* first try with FIEMAP */
     782             :         /* if works for ext2, ext3, ext4, xfs, btrfs */
     783       11432 :         fiemap_size = sizeof(struct fiemap) + sizeof(struct fiemap_extent);
     784       11432 :         fiemap = malloc_nofail(fiemap_size);
     785       11432 :         memset(fiemap, 0, fiemap_size);
     786       11432 :         fiemap->fm_start = 0;
     787       11432 :         fiemap->fm_length = ~0ULL;
     788       11432 :         fiemap->fm_flags = FIEMAP_FLAG_SYNC; /* required to ensure that just created files report a valid address and not 0 */
     789       11432 :         fiemap->fm_extent_count = 1; /* we are interested only at the first block */
     790             : 
     791       11432 :         if (ioctl(f, FS_IOC_FIEMAP, fiemap) != -1) {
     792       11432 :                 uint32_t flags = fiemap->fm_extents[0].fe_flags;
     793       11432 :                 uint64_t offset = fiemap->fm_extents[0].fe_physical;
     794             : 
     795             :                 /* check some condition for validating the offset */
     796       11432 :                 if (flags & FIEMAP_EXTENT_DATA_INLINE) {
     797             :                         /* if the data is inline, we don't have an offset to report */
     798           0 :                         *physical = FILEPHY_WITHOUT_OFFSET;
     799       11432 :                 } else if (flags & FIEMAP_EXTENT_UNKNOWN) {
     800             :                         /* if the offset is unknown, we don't have an offset to report */
     801           0 :                         *physical = FILEPHY_WITHOUT_OFFSET;
     802       11432 :                 } else if (offset == 0) {
     803             :                         /* 0 is the general fallback for file-systems when */
     804             :                         /* they don't have an offset to report */
     805          14 :                         *physical = FILEPHY_WITHOUT_OFFSET;
     806             :                 } else {
     807             :                         /* finally report the real offset */
     808       11418 :                         *physical = offset + FILEPHY_REAL_OFFSET;
     809             :                 }
     810             : 
     811       11432 :                 if (close(f) == -1)
     812           0 :                         return -1;
     813       11432 :                 return 0;
     814             :         }
     815             : 
     816           0 :         free(fiemap);
     817             : 
     818             :         /* if the file is empty, FIBMAP doesn't work, and we don't even try to use it */
     819           0 :         if (size == 0) {
     820           0 :                 *physical = FILEPHY_WITHOUT_OFFSET;
     821           0 :                 if (close(f) == -1)
     822           0 :                         return -1;
     823           0 :                 return 0;
     824             :         }
     825             : 
     826             :         /* then try with FIBMAP */
     827             :         /* it works for jfs, reiserfs, ntfs-3g */
     828             :         /* in exfat it always returns 0, that it's anyway better than the fake inodes */
     829           0 :         blknum = 0; /* first block */
     830           0 :         if (ioctl(f, FIBMAP, &blknum) != -1) {
     831           0 :                 *physical = blknum + FILEPHY_REAL_OFFSET;
     832           0 :                 if (close(f) == -1)
     833           0 :                         return -1;
     834           0 :                 return 0;
     835             :         }
     836             : 
     837             :         /* otherwise don't use anything, and keep the directory traversal order */
     838             :         /* at now this should happen only for vfat */
     839             :         /* and it's surely better than using fake inodes */
     840           0 :         *physical = FILEPHY_UNREPORTED_OFFSET;
     841           0 :         if (close(f) == -1)
     842           0 :                 return -1;
     843             : #else
     844             :         /* In a generic Unix use a dummy value for all the files */
     845             :         /* We don't want to risk to use the inode without knowing */
     846             :         /* if it really improves performance. */
     847             :         /* In this way we keep them in the directory traversal order */
     848             :         /* that at least keeps files in the same directory together. */
     849             :         /* Note also that in newer file-system with snapshot, like ZFS, */
     850             :         /* the inode doesn't represent even more the disk position, because files */
     851             :         /* are not overwritten in place, but rewritten in another location */
     852             :         /* of the disk. */
     853             :         *physical = FILEPHY_UNREPORTED_OFFSET;
     854             : 
     855             :         (void)path; /* not used here */
     856             :         (void)size;
     857             : #endif
     858             : 
     859           0 :         return 0;
     860             : }
     861             : 
     862             : /* from man statfs */
     863             : #define ADFS_SUPER_MAGIC 0xadf5
     864             : #define AFFS_SUPER_MAGIC 0xADFF
     865             : #define BDEVFS_MAGIC 0x62646576
     866             : #define BEFS_SUPER_MAGIC 0x42465331
     867             : #define BFS_MAGIC 0x1BADFACE
     868             : #define BINFMTFS_MAGIC 0x42494e4d
     869             : #define BTRFS_SUPER_MAGIC 0x9123683E
     870             : #define CGROUP_SUPER_MAGIC 0x27e0eb
     871             : #define CIFS_MAGIC_NUMBER 0xFF534D42
     872             : #define CODA_SUPER_MAGIC 0x73757245
     873             : #define COH_SUPER_MAGIC 0x012FF7B7
     874             : #define CRAMFS_MAGIC 0x28cd3d45
     875             : #define DEBUGFS_MAGIC 0x64626720
     876             : #define DEVFS_SUPER_MAGIC 0x1373
     877             : #define DEVPTS_SUPER_MAGIC 0x1cd1
     878             : #define EFIVARFS_MAGIC 0xde5e81e4
     879             : #define EFS_SUPER_MAGIC 0x00414A53
     880             : #define EXT_SUPER_MAGIC 0x137D
     881             : #define EXT2_OLD_SUPER_MAGIC 0xEF51
     882             : #define EXT4_SUPER_MAGIC 0xEF53 /* also ext2/ext3 */
     883             : #define FUSE_SUPER_MAGIC 0x65735546
     884             : #define FUTEXFS_SUPER_MAGIC 0xBAD1DEA
     885             : #define HFS_SUPER_MAGIC 0x4244
     886             : #define HFSPLUS_SUPER_MAGIC 0x482b
     887             : #define HOSTFS_SUPER_MAGIC 0x00c0ffee
     888             : #define HPFS_SUPER_MAGIC 0xF995E849
     889             : #define HUGETLBFS_MAGIC 0x958458f6
     890             : #define ISOFS_SUPER_MAGIC 0x9660
     891             : #define JFFS2_SUPER_MAGIC 0x72b6
     892             : #define JFS_SUPER_MAGIC 0x3153464a
     893             : #define MINIX_SUPER_MAGIC 0x137F
     894             : #define MINIX_SUPER_MAGIC2 0x138F
     895             : #define MINIX2_SUPER_MAGIC 0x2468
     896             : #define MINIX2_SUPER_MAGIC2 0x2478
     897             : #define MINIX3_SUPER_MAGIC 0x4d5a
     898             : #define MQUEUE_MAGIC 0x19800202
     899             : #define MSDOS_SUPER_MAGIC 0x4d44
     900             : #define NCP_SUPER_MAGIC 0x564c
     901             : #define NFS_SUPER_MAGIC 0x6969
     902             : #define NILFS_SUPER_MAGIC 0x3434
     903             : #define NTFS_SB_MAGIC 0x5346544e
     904             : #define OCFS2_SUPER_MAGIC 0x7461636f
     905             : #define OPENPROM_SUPER_MAGIC 0x9fa1
     906             : #define PIPEFS_MAGIC 0x50495045
     907             : #define PROC_SUPER_MAGIC 0x9fa0
     908             : #define PSTOREFS_MAGIC 0x6165676C
     909             : #define QNX4_SUPER_MAGIC 0x002f
     910             : #define QNX6_SUPER_MAGIC 0x68191122
     911             : #define RAMFS_MAGIC 0x858458f6
     912             : #define REISERFS_SUPER_MAGIC 0x52654973
     913             : #define ROMFS_MAGIC 0x7275
     914             : #define SELINUX_MAGIC 0xf97cff8c
     915             : #define SMACK_MAGIC 0x43415d53
     916             : #define SMB_SUPER_MAGIC 0x517B
     917             : #define SOCKFS_MAGIC 0x534F434B
     918             : #define SQUASHFS_MAGIC 0x73717368
     919             : #define SYSFS_MAGIC 0x62656572
     920             : #define SYSV2_SUPER_MAGIC 0x012FF7B6
     921             : #define SYSV4_SUPER_MAGIC 0x012FF7B5
     922             : #define TMPFS_MAGIC 0x01021994
     923             : #define UDF_SUPER_MAGIC 0x15013346
     924             : #define UFS_MAGIC 0x00011954
     925             : #define USBDEVICE_SUPER_MAGIC 0x9fa2
     926             : #define V9FS_MAGIC 0x01021997
     927             : #define VXFS_SUPER_MAGIC 0xa501FCF5
     928             : #define XENFS_SUPER_MAGIC 0xabba1974
     929             : #define XENIX_SUPER_MAGIC 0x012FF7B4
     930             : #define XFS_SUPER_MAGIC 0x58465342
     931             : #define _XIAFS_SUPER_MAGIC 0x012FD16D
     932             : #define AFS_SUPER_MAGIC 0x5346414F
     933             : #define AUFS_SUPER_MAGIC 0x61756673
     934             : #define ANON_INODE_FS_SUPER_MAGIC 0x09041934
     935             : #define CEPH_SUPER_MAGIC 0x00C36400
     936             : #define ECRYPTFS_SUPER_MAGIC 0xF15F
     937             : #define FAT_SUPER_MAGIC 0x4006
     938             : #define FHGFS_SUPER_MAGIC 0x19830326
     939             : #define FUSEBLK_SUPER_MAGIC 0x65735546
     940             : #define FUSECTL_SUPER_MAGIC 0x65735543
     941             : #define GFS_SUPER_MAGIC 0x1161970
     942             : #define GPFS_SUPER_MAGIC 0x47504653
     943             : #define MTD_INODE_FS_SUPER_MAGIC 0x11307854
     944             : #define INOTIFYFS_SUPER_MAGIC 0x2BAD1DEA
     945             : #define ISOFS_R_WIN_SUPER_MAGIC 0x4004
     946             : #define ISOFS_WIN_SUPER_MAGIC 0x4000
     947             : #define JFFS_SUPER_MAGIC 0x07C0
     948             : #define KAFS_SUPER_MAGIC 0x6B414653
     949             : #define LUSTRE_SUPER_MAGIC 0x0BD00BD0
     950             : #define NFSD_SUPER_MAGIC 0x6E667364
     951             : #define PANFS_SUPER_MAGIC 0xAAD7AAEA
     952             : #define RPC_PIPEFS_SUPER_MAGIC 0x67596969
     953             : #define SECURITYFS_SUPER_MAGIC 0x73636673
     954             : #define UFS_BYTESWAPPED_SUPER_MAGIC 0x54190100
     955             : #define VMHGFS_SUPER_MAGIC 0xBACBACBC
     956             : #define VZFS_SUPER_MAGIC 0x565A4653
     957             : #define ZFS_SUPER_MAGIC 0x2FC12FC1
     958             : 
     959             : struct filesystem_entry {
     960             :         unsigned id;
     961             :         const char* name;
     962             :         int remote;
     963             : } FILESYSTEMS[] = {
     964             :         { ADFS_SUPER_MAGIC, "adfs", 0 },
     965             :         { AFFS_SUPER_MAGIC, "affs", 0 },
     966             :         { AFS_SUPER_MAGIC, "afs", 1 },
     967             :         { AUFS_SUPER_MAGIC, "aufs", 1 },
     968             :         { BEFS_SUPER_MAGIC, "befs", 0 },
     969             :         { BDEVFS_MAGIC, "bdevfs", 0 },
     970             :         { BFS_MAGIC, "bfs", 0 },
     971             :         { BINFMTFS_MAGIC, "binfmt_misc", 0 },
     972             :         { BTRFS_SUPER_MAGIC, "btrfs", 0 },
     973             :         { CEPH_SUPER_MAGIC, "ceph", 1 },
     974             :         { CGROUP_SUPER_MAGIC, "cgroupfs", 0 },
     975             :         { CIFS_MAGIC_NUMBER, "cifs", 1 },
     976             :         { CODA_SUPER_MAGIC, "coda", 1 },
     977             :         { COH_SUPER_MAGIC, "coh", 0 },
     978             :         { CRAMFS_MAGIC, "cramfs", 0 },
     979             :         { DEBUGFS_MAGIC, "debugfs", 0 },
     980             :         { DEVFS_SUPER_MAGIC, "devfs", 0 },
     981             :         { DEVPTS_SUPER_MAGIC, "devpts", 0 },
     982             :         { ECRYPTFS_SUPER_MAGIC, "ecryptfs", 0 },
     983             :         { EFS_SUPER_MAGIC, "efs", 0 },
     984             :         { EXT_SUPER_MAGIC, "ext", 0 },
     985             :         { EXT4_SUPER_MAGIC, "ext4", 0 },
     986             :         { EXT2_OLD_SUPER_MAGIC, "ext2", 0 },
     987             :         { FAT_SUPER_MAGIC, "fat", 0 },
     988             :         { FHGFS_SUPER_MAGIC, "fhgfs", 1 },
     989             :         { FUSEBLK_SUPER_MAGIC, "fuseblk", 1 },
     990             :         { FUSECTL_SUPER_MAGIC, "fusectl", 1 },
     991             :         { FUTEXFS_SUPER_MAGIC, "futexfs", 0 },
     992             :         { GFS_SUPER_MAGIC, "gfs/gfs2", 1 },
     993             :         { GPFS_SUPER_MAGIC, "gpfs", 1 },
     994             :         { HFS_SUPER_MAGIC, "hfs", 0 },
     995             :         { HFSPLUS_SUPER_MAGIC, "hfsplus", 0 },
     996             :         { HPFS_SUPER_MAGIC, "hpfs", 0 },
     997             :         { HUGETLBFS_MAGIC, "hugetlbfs", 0 },
     998             :         { MTD_INODE_FS_SUPER_MAGIC, "inodefs", 0 },
     999             :         { INOTIFYFS_SUPER_MAGIC, "inotifyfs", 0 },
    1000             :         { ISOFS_SUPER_MAGIC, "isofs", 0 },
    1001             :         { ISOFS_R_WIN_SUPER_MAGIC, "isofs", 0 },
    1002             :         { ISOFS_WIN_SUPER_MAGIC, "isofs", 0 },
    1003             :         { JFFS_SUPER_MAGIC, "jffs", 0 },
    1004             :         { JFFS2_SUPER_MAGIC, "jffs2", 0 },
    1005             :         { JFS_SUPER_MAGIC, "jfs", 0 },
    1006             :         { KAFS_SUPER_MAGIC, "k-afs", 1 },
    1007             :         { LUSTRE_SUPER_MAGIC, "lustre", 1 },
    1008             :         { MINIX_SUPER_MAGIC, "minix", 0 },
    1009             :         { MINIX_SUPER_MAGIC2, "minix", 0 },
    1010             :         { MINIX2_SUPER_MAGIC, "minix2", 0 },
    1011             :         { MINIX2_SUPER_MAGIC2, "minix2", 0 },
    1012             :         { MINIX3_SUPER_MAGIC, "minix3", 0 },
    1013             :         { MQUEUE_MAGIC, "mqueue", 0 },
    1014             :         { MSDOS_SUPER_MAGIC, "msdos", 0 },
    1015             :         { NCP_SUPER_MAGIC, "novell", 1 },
    1016             :         { NFS_SUPER_MAGIC, "nfs", 1 },
    1017             :         { NFSD_SUPER_MAGIC, "nfsd", 1 },
    1018             :         { NILFS_SUPER_MAGIC, "nilfs", 0 },
    1019             :         { NTFS_SB_MAGIC, "ntfs", 0 },
    1020             :         { OPENPROM_SUPER_MAGIC, "openprom", 0 },
    1021             :         { OCFS2_SUPER_MAGIC, "ocfs2", 1 },
    1022             :         { PANFS_SUPER_MAGIC, "panfs", 1 },
    1023             :         { PIPEFS_MAGIC, "pipefs", 1 },
    1024             :         { PROC_SUPER_MAGIC, "proc", 0 },
    1025             :         { PSTOREFS_MAGIC, "pstorefs", 0 },
    1026             :         { QNX4_SUPER_MAGIC, "qnx4", 0 },
    1027             :         { QNX6_SUPER_MAGIC, "qnx6", 0 },
    1028             :         { RAMFS_MAGIC, "ramfs", 0 },
    1029             :         { REISERFS_SUPER_MAGIC, "reiserfs", 0 },
    1030             :         { ROMFS_MAGIC, "romfs", 0 },
    1031             :         { RPC_PIPEFS_SUPER_MAGIC, "rpc_pipefs", 0 },
    1032             :         { SECURITYFS_SUPER_MAGIC, "securityfs", 0 },
    1033             :         { SELINUX_MAGIC, "selinux", 0 },
    1034             :         { SMB_SUPER_MAGIC, "smb", 1 },
    1035             :         { SOCKFS_MAGIC, "sockfs", 0 },
    1036             :         { SQUASHFS_MAGIC, "squashfs", 0 },
    1037             :         { SYSFS_MAGIC, "sysfs", 0 },
    1038             :         { SYSV2_SUPER_MAGIC, "sysv2", 0 },
    1039             :         { SYSV4_SUPER_MAGIC, "sysv4", 0 },
    1040             :         { TMPFS_MAGIC, "tmpfs", 0 },
    1041             :         { UDF_SUPER_MAGIC, "udf", 0 },
    1042             :         { UFS_MAGIC, "ufs", 0 },
    1043             :         { UFS_BYTESWAPPED_SUPER_MAGIC, "ufs", 0 },
    1044             :         { USBDEVICE_SUPER_MAGIC, "usbdevfs", 0 },
    1045             :         { V9FS_MAGIC, "v9fs", 0 },
    1046             :         { VMHGFS_SUPER_MAGIC, "vmhgfs", 1 },
    1047             :         { VXFS_SUPER_MAGIC, "vxfs", 0 },
    1048             :         { VZFS_SUPER_MAGIC, "vzfs", 0 },
    1049             :         { XENFS_SUPER_MAGIC, "xenfs", 0 },
    1050             :         { XENIX_SUPER_MAGIC, "xenix", 0 },
    1051             :         { XFS_SUPER_MAGIC, "xfs", 0 },
    1052             :         { _XIAFS_SUPER_MAGIC, "xia", 0 },
    1053             :         { ZFS_SUPER_MAGIC, "zfs", 0 },
    1054             :         { 0 }
    1055             : };
    1056             : 
    1057        6596 : int fsinfo(const char* path, int* has_persistent_inode, int* has_syncronized_hardlinks, uint64_t* total_space, uint64_t* free_space, char* fstype, size_t fstype_size, char* fslabel, size_t fslabel_size)
    1058             : {
    1059             : #if HAVE_STATFS
    1060             :         struct statfs st;
    1061             : 
    1062        6596 :         if (statfs(path, &st) != 0) {
    1063             :                 char dir[PATH_MAX];
    1064             :                 char* slash;
    1065             : 
    1066          48 :                 if (errno != ENOENT) {
    1067           0 :                         return -1;
    1068             :                 }
    1069             : 
    1070             :                 /* if it doesn't exist, we assume a file */
    1071             :                 /* and we check for the containing dir */
    1072          48 :                 if (strlen(path) + 1 > sizeof(dir)) {
    1073           0 :                         errno = ENAMETOOLONG;
    1074           0 :                         return -1;
    1075             :                 }
    1076             : 
    1077          48 :                 strcpy(dir, path);
    1078             : 
    1079          48 :                 slash = strrchr(dir, '/');
    1080          48 :                 if (!slash)
    1081           0 :                         return -1;
    1082             : 
    1083          48 :                 *slash = 0;
    1084          48 :                 if (statfs(dir, &st) != 0)
    1085           0 :                         return -1;
    1086             :         }
    1087             : #endif
    1088             : 
    1089             :         /* to get the fs type check "man stat" or "stat -f -t FILE" */
    1090        6596 :         if (has_persistent_inode) {
    1091             : #if HAVE_STATFS && HAVE_STRUCT_STATFS_F_TYPE
    1092         629 :                 switch (st.f_type) {
    1093           0 :                 case FUSEBLK_SUPER_MAGIC : /* FUSE, "fuseblk" in the stat command */
    1094             :                 case MSDOS_SUPER_MAGIC : /* VFAT, "msdos" in the stat command */
    1095           0 :                         *has_persistent_inode = 0;
    1096           0 :                         break;
    1097         629 :                 default :
    1098             :                         /* by default assume yes */
    1099         629 :                         *has_persistent_inode = 1;
    1100         629 :                         break;
    1101             :                 }
    1102             : #else
    1103             :                 /* in Unix inodes are persistent by default */
    1104             :                 *has_persistent_inode = 1;
    1105             : #endif
    1106             :         }
    1107             : 
    1108        6596 :         if (has_syncronized_hardlinks) {
    1109             : #if HAVE_STATFS && HAVE_STRUCT_STATFS_F_TYPE
    1110         629 :                 switch (st.f_type) {
    1111           0 :                 case NTFS_SB_MAGIC : /* NTFS */
    1112             :                 case MSDOS_SUPER_MAGIC : /* VFAT, "msdos" in the stat command */
    1113           0 :                         *has_syncronized_hardlinks = 0;
    1114           0 :                         break;
    1115         629 :                 default :
    1116             :                         /* by default assume yes */
    1117         629 :                         *has_syncronized_hardlinks = 1;
    1118         629 :                         break;
    1119             :                 }
    1120             : #else
    1121             :                 /* in Unix hardlinks share the same metadata by default */
    1122             :                 *has_syncronized_hardlinks = 1;
    1123             : #endif
    1124             :         }
    1125             : 
    1126        6596 :         if (total_space) {
    1127             : #if HAVE_STATFS
    1128        5967 :                 *total_space = st.f_bsize * (uint64_t)st.f_blocks;
    1129             : #else
    1130             :                 *total_space = 0;
    1131             : #endif
    1132             :         }
    1133             : 
    1134        6596 :         if (free_space) {
    1135             : #if HAVE_STATFS
    1136        5967 :                 *free_space = st.f_bsize * (uint64_t)st.f_bfree;
    1137             : #else
    1138             :                 *free_space = 0;
    1139             : #endif
    1140             :         }
    1141             : 
    1142        6596 :         const char* ptype = 0;
    1143             : 
    1144             : #if HAVE_STATFS && HAVE_STRUCT_STATFS_F_FSTYPENAME
    1145             :         /* get the filesystem type directly from the struct (Mac OS X) */
    1146             :         ptype = st.f_fstypename;
    1147             : #elif HAVE_STATFS && HAVE_STRUCT_STATFS_F_TYPE
    1148             :         /* get the filesystem type from f_type (Linux) */
    1149             :         /* from: https://github.com/influxdata/gopsutil/blob/master/disk/disk_linux.go */
    1150      145112 :         for (int i = 0; FILESYSTEMS[i].id != 0; ++i) {
    1151      145112 :                 if (st.f_type == FILESYSTEMS[i].id) {
    1152        6596 :                         ptype = FILESYSTEMS[i].name;
    1153        6596 :                         break;
    1154             :                 }
    1155             :         }
    1156             : #endif
    1157             : 
    1158        6596 :         if (fstype) {
    1159        5967 :                 fstype[0] = 0;
    1160        5967 :                 if (ptype)
    1161        5967 :                         snprintf(fstype, fstype_size, "%s", ptype);
    1162             :         }
    1163             : 
    1164        6596 :         if (fslabel) {
    1165        5967 :                 fslabel[0] = 0;
    1166             : #if HAVE_BLKID
    1167             :                 struct stat fst;
    1168        5967 :                 if (stat(path, &fst) == 0)
    1169        5919 :                         devuuid_label(fst.st_dev, fslabel, fslabel_size);
    1170             : #else
    1171             :                 (void)fslabel_size;
    1172             : #endif
    1173             :         }
    1174             : 
    1175        6596 :         return 0;
    1176             : }
    1177             : 
    1178     4047960 : uint64_t tick(void)
    1179             : {
    1180             : #if HAVE_MACH_ABSOLUTE_TIME
    1181             :         /* for Mac OS X */
    1182             :         return mach_absolute_time();
    1183             : #elif HAVE_CLOCK_GETTIME && (defined(CLOCK_MONOTONIC) || defined(CLOCK_MONOTONIC_RAW))
    1184             :         /* for Linux */
    1185             :         struct timespec tv;
    1186             : 
    1187             :         /* nanosecond precision with clock_gettime() */
    1188             : #if defined(CLOCK_MONOTONIC_RAW)
    1189     4047960 :         if (clock_gettime(CLOCK_MONOTONIC_RAW, &tv) != 0) {
    1190             : #else
    1191             :         if (clock_gettime(CLOCK_MONOTONIC, &tv) != 0) {
    1192             : #endif
    1193           0 :                 return 0;
    1194             :         }
    1195             : 
    1196     4047960 :         return tv.tv_sec * 1000000000ULL + tv.tv_nsec;
    1197             : #else
    1198             :         /* other platforms */
    1199             :         struct timeval tv;
    1200             : 
    1201             :         /* microsecond precision with gettimeofday() */
    1202             :         if (gettimeofday(&tv, 0) != 0) {
    1203             :                 return 0;
    1204             :         }
    1205             : 
    1206             :         return tv.tv_sec * 1000000ULL + tv.tv_usec;
    1207             : #endif
    1208             : }
    1209             : 
    1210        3721 : uint64_t tick_ms(void)
    1211             : {
    1212             :         struct timeval tv;
    1213             : 
    1214        3721 :         if (gettimeofday(&tv, 0) != 0)
    1215           0 :                 return 0;
    1216             : 
    1217        3721 :         return tv.tv_sec * 1000ULL + tv.tv_usec / 1000;
    1218             : }
    1219             : 
    1220         308 : int randomize(void* ptr, size_t size)
    1221             : {
    1222             :         int f;
    1223             :         ssize_t ret;
    1224             : 
    1225         308 :         f = open("/dev/urandom", O_RDONLY);
    1226         308 :         if (f == -1)
    1227           0 :                 return -1;
    1228             : 
    1229         308 :         ret = read(f, ptr, size);
    1230         308 :         if (ret < 0 || (size_t)ret != size) {
    1231           0 :                 close(f);
    1232           0 :                 return -1;
    1233             :         }
    1234             : 
    1235         308 :         if (close(f) != 0)
    1236           0 :                 return -1;
    1237             : 
    1238         308 :         return 0;
    1239             : }
    1240             : 
    1241             : /**
    1242             :  * Read a file extracting the contained device number in %u:%u format.
    1243             :  * Return 0 on error.
    1244             :  */
    1245             : #if HAVE_LINUX_DEVICE
    1246         316 : static dev_t devread(const char* path)
    1247             : {
    1248             :         int f;
    1249             :         int ret;
    1250             :         int len;
    1251             :         char buf[64];
    1252             :         char* e;
    1253             :         unsigned ma;
    1254             :         unsigned mi;
    1255             : 
    1256         316 :         f = open(path, O_RDONLY);
    1257         316 :         if (f == -1) {
    1258             :                 /* LCOV_EXCL_START */
    1259             :                 log_fatal(errno, "Failed to open '%s'.\n", path);
    1260             :                 return 0;
    1261             :                 /* LCOV_EXCL_STOP */
    1262             :         }
    1263             : 
    1264         316 :         len = read(f, buf, sizeof(buf));
    1265         316 :         if (len < 0) {
    1266             :                 /* LCOV_EXCL_START */
    1267             :                 close(f);
    1268             :                 log_fatal(errno, "Failed to read '%s'.\n", path);
    1269             :                 return 0;
    1270             :                 /* LCOV_EXCL_STOP */
    1271             :         }
    1272         316 :         if (len == sizeof(buf)) {
    1273             :                 /* LCOV_EXCL_START */
    1274             :                 close(f);
    1275             :                 log_fatal(EEXTERNAL, "Too long read '%s'.\n", path);
    1276             :                 return 0;
    1277             :                 /* LCOV_EXCL_STOP */
    1278             :         }
    1279             : 
    1280         316 :         ret = close(f);
    1281         316 :         if (ret != 0) {
    1282             :                 /* LCOV_EXCL_START */
    1283             :                 log_fatal(errno, "Failed to close '%s'.\n", path);
    1284             :                 return 0;
    1285             :                 /* LCOV_EXCL_STOP */
    1286             :         }
    1287             : 
    1288         316 :         buf[len] = 0;
    1289             : 
    1290         316 :         ma = strtoul(buf, &e, 10);
    1291         316 :         if (*e != ':') {
    1292             :                 /* LCOV_EXCL_START */
    1293             :                 log_fatal(EEXTERNAL, "Invalid format in '%s' for '%s'.\n", path, buf);
    1294             :                 return 0;
    1295             :                 /* LCOV_EXCL_STOP */
    1296             :         }
    1297             : 
    1298         316 :         mi = strtoul(e + 1, &e, 10);
    1299         316 :         if (*e != 0 && !isspace(*e)) {
    1300             :                 /* LCOV_EXCL_START */
    1301             :                 log_fatal(EEXTERNAL, "Invalid format in '%s' for '%s'.\n", path, buf);
    1302             :                 return 0;
    1303             :                 /* LCOV_EXCL_STOP */
    1304             :         }
    1305             : 
    1306         316 :         return makedev(ma, mi);
    1307             : }
    1308             : #endif
    1309             : 
    1310             : /**
    1311             :  * Read a device tree filling the specified list of disk_t entries.
    1312             :  */
    1313             : #if HAVE_LINUX_DEVICE
    1314         274 : static int devtree(devinfo_t* parent, dev_t device, tommy_list* list)
    1315             : {
    1316             :         char path[PATH_MAX];
    1317             :         DIR* d;
    1318         274 :         int slaves = 0;
    1319             : 
    1320         274 :         pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/slaves", major(device), minor(device));
    1321             : 
    1322             :         /* check if there is a slaves list */
    1323         274 :         d = opendir(path);
    1324         274 :         if (d != 0) {
    1325             :                 struct dirent* dd;
    1326             : 
    1327         548 :                 while ((dd = readdir(d)) != 0) {
    1328         411 :                         if (dd->d_name[0] != '.') {
    1329             :                                 dev_t subdev;
    1330             : 
    1331             :                                 /* for each slave, expand the full potential tree */
    1332         137 :                                 pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/slaves/%s/dev", major(device), minor(device), dd->d_name);
    1333             : 
    1334         137 :                                 subdev = devread(path);
    1335         137 :                                 if (!subdev) {
    1336             :                                         /* LCOV_EXCL_START */
    1337             :                                         closedir(d);
    1338             :                                         return -1;
    1339             :                                         /* LCOV_EXCL_STOP */
    1340             :                                 }
    1341             : 
    1342         137 :                                 if (devtree(parent, subdev, list) != 0) {
    1343             :                                         /* LCOV_EXCL_START */
    1344             :                                         closedir(d);
    1345             :                                         return -1;
    1346             :                                         /* LCOV_EXCL_STOP */
    1347             :                                 }
    1348             : 
    1349         137 :                                 ++slaves;
    1350             :                         }
    1351             :                 }
    1352             : 
    1353         137 :                 closedir(d);
    1354             :         }
    1355             : 
    1356             :         /* if no slaves found */
    1357         274 :         if (!slaves) {
    1358             :                 /* this is a raw device */
    1359             :                 devinfo_t* devinfo;
    1360             : 
    1361             :                 /* check if it's a real device */
    1362         137 :                 pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/device", major(device), minor(device));
    1363         137 :                 if (access(path, F_OK) != 0) {
    1364             :                         /* get the parent device */
    1365         137 :                         pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/../dev", major(device), minor(device));
    1366             : 
    1367         137 :                         device = devread(path);
    1368         137 :                         if (!device) {
    1369             :                                 /* LCOV_EXCL_START */
    1370             :                                 return -1;
    1371             :                                 /* LCOV_EXCL_STOP */
    1372             :                         }
    1373             :                 }
    1374             : 
    1375             :                 /* get the device file */
    1376         137 :                 if (devresolve(device, path, sizeof(path)) != 0) {
    1377             :                         /* LCOV_EXCL_START */
    1378             :                         log_fatal(EEXTERNAL, "Failed to resolve device '%u:%u'.\n", major(device), minor(device));
    1379             :                         return -1;
    1380             :                         /* LCOV_EXCL_STOP */
    1381             :                 }
    1382             : 
    1383         137 :                 devinfo = calloc_nofail(1, sizeof(devinfo_t));
    1384             : 
    1385         137 :                 devinfo->device = device;
    1386         137 :                 pathcpy(devinfo->name, sizeof(devinfo->name), parent->name);
    1387         137 :                 pathcpy(devinfo->smartctl, sizeof(devinfo->smartctl), parent->smartctl);
    1388         137 :                 memcpy(devinfo->smartignore, parent->smartignore, sizeof(devinfo->smartignore));
    1389         137 :                 pathcpy(devinfo->file, sizeof(devinfo->file), path);
    1390         137 :                 devinfo->parent = parent;
    1391             : 
    1392             :                 /* insert in the list */
    1393         137 :                 tommy_list_insert_tail(list, &devinfo->node, devinfo);
    1394             :         }
    1395             : 
    1396         274 :         return 0;
    1397             : }
    1398             : #endif
    1399             : 
    1400             : /**
    1401             :  * Scan all the devices.
    1402             :  *
    1403             :  * If a device is already in, it's not added again.
    1404             :  */
    1405             : #if HAVE_LINUX_DEVICE
    1406           3 : static int devscan(tommy_list* list)
    1407             : {
    1408             :         char dir[PATH_MAX];
    1409             :         DIR* d;
    1410             :         struct dirent* dd;
    1411             : 
    1412           3 :         pathprint(dir, sizeof(dir), "/sys/dev/block/");
    1413             : 
    1414             :         /* check if there is a slaves list */
    1415           3 :         d = opendir(dir);
    1416           3 :         if (d == 0) {
    1417             :                 /* LCOV_EXCL_START */
    1418             :                 log_fatal(errno, "Failed to open dir '%s'.\n", dir);
    1419             :                 return -1;
    1420             :                 /* LCOV_EXCL_STOP */
    1421             :         }
    1422             : 
    1423         225 :         while ((dd = readdir(d)) != 0) {
    1424             :                 char path[PATH_MAX];
    1425             :                 tommy_node* i;
    1426             :                 dev_t device;
    1427             :                 devinfo_t* devinfo;
    1428             : 
    1429         222 :                 if (dd->d_name[0] == '.')
    1430         216 :                         continue;
    1431             : 
    1432         216 :                 pathprint(path, sizeof(path), "/sys/dev/block/%s/device", dd->d_name);
    1433             : 
    1434             :                 /* check if it's a real device */
    1435         216 :                 if (access(path, F_OK) != 0)
    1436         174 :                         continue;
    1437             : 
    1438          42 :                 pathprint(path, sizeof(path), "/sys/dev/block/%s/dev", dd->d_name);
    1439             : 
    1440          42 :                 device = devread(path);
    1441          42 :                 if (!device) {
    1442             :                         /* LCOV_EXCL_START */
    1443             :                         log_tag("scan:skip: Skipping device %s because failed to read its device number.\n", dd->d_name);
    1444             :                         continue;
    1445             :                         /* LCOV_EXCL_STOP */
    1446             :                 }
    1447             : 
    1448             :                 /* check if already present */
    1449         315 :                 for (i = tommy_list_head(list); i != 0; i = i->next) {
    1450         309 :                         devinfo = i->data;
    1451         309 :                         if (devinfo->device == device)
    1452          36 :                                 break;
    1453             :                 }
    1454             : 
    1455             :                 /* if already present */
    1456          42 :                 if (i != 0)
    1457          36 :                         continue;
    1458             : 
    1459             :                 /* get the device file */
    1460           6 :                 if (devresolve(device, path, sizeof(path)) != 0) {
    1461             :                         /* LCOV_EXCL_START */
    1462             :                         log_tag("scan:skip: Skipping device %u:%u because failed to resolve.\n", major(device), minor(device));
    1463             :                         continue;
    1464             :                         /* LCOV_EXCL_STOP */
    1465             :                 }
    1466             : 
    1467           6 :                 devinfo = calloc_nofail(1, sizeof(devinfo_t));
    1468             : 
    1469           6 :                 devinfo->device = device;
    1470           6 :                 pathcpy(devinfo->file, sizeof(devinfo->file), path);
    1471             : 
    1472             :                 /* insert in the list */
    1473           6 :                 tommy_list_insert_tail(list, &devinfo->node, devinfo);
    1474             :         }
    1475             : 
    1476           3 :         closedir(d);
    1477           3 :         return 0;
    1478             : }
    1479             : #endif
    1480             : 
    1481             : /**
    1482             :  * Get SMART attributes.
    1483             :  */
    1484             : #if HAVE_LINUX_DEVICE
    1485          26 : static int devsmart(dev_t device, const char* name, const char* smartctl, struct smart_attr* smart, uint64_t* info, char* serial, char* family, char* model, char* interface)
    1486             : {
    1487             :         char cmd[PATH_MAX + 64];
    1488             :         char file[PATH_MAX];
    1489             :         FILE* f;
    1490             :         int ret;
    1491             :         const char* x;
    1492             : 
    1493          26 :         x = find_smartctl();
    1494          26 :         if (!x) {
    1495             :                 /* LCOV_EXCL_START */
    1496             :                 log_fatal(EEXTERNAL, "Cannot find smartctl.\n");
    1497             :                 return -1;
    1498             :                 /* LCOV_EXCL_STOP */
    1499             :         }
    1500             : 
    1501          26 :         if (devresolve(device, file, sizeof(file)) != 0) {
    1502             :                 /* LCOV_EXCL_START */
    1503             :                 log_fatal(EEXTERNAL, "Failed to resolve device '%u:%u'.\n", major(device), minor(device));
    1504             :                 return -1;
    1505             :                 /* LCOV_EXCL_STOP */
    1506             :         }
    1507             : 
    1508             :         /* if there is a custom smartctl command */
    1509          26 :         if (smartctl[0]) {
    1510             :                 char option[PATH_MAX];
    1511           0 :                 snprintf(option, sizeof(option), smartctl, file);
    1512           0 :                 snprintf(cmd, sizeof(cmd), "%s -a %s", x, option);
    1513             :         } else {
    1514          26 :                 snprintf(cmd, sizeof(cmd), "%s -a %s", x, file);
    1515             :         }
    1516             : 
    1517          26 :         log_tag("smartctl:%s:%s:run: %s\n", file, name, cmd);
    1518             : 
    1519          26 :         f = popen(cmd, "r");
    1520          26 :         if (!f) {
    1521             :                 /* LCOV_EXCL_START */
    1522             :                 log_tag("device:%s:%s:shell\n", file, name);
    1523             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (from popen).\n", cmd);
    1524             :                 return -1;
    1525             :                 /* LCOV_EXCL_STOP */
    1526             :         }
    1527             : 
    1528          26 :         if (smartctl_attribute(f, file, name, smart, info, serial, family, model, interface) != 0) {
    1529             :                 /* LCOV_EXCL_START */
    1530             :                 pclose(f);
    1531             :                 log_tag("device:%s:%s:shell\n", file, name);
    1532             :                 return -1;
    1533             :                 /* LCOV_EXCL_STOP */
    1534             :         }
    1535             : 
    1536          26 :         ret = pclose(f);
    1537             : 
    1538          26 :         log_tag("smartctl:%s:%s:ret: %x\n", file, name, ret);
    1539             : 
    1540          26 :         if (!WIFEXITED(ret)) {
    1541             :                 /* LCOV_EXCL_START */
    1542             :                 log_tag("device:%s:%s:abort\n", file, name);
    1543             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (not exited).\n", cmd);
    1544             :                 return -1;
    1545             :                 /* LCOV_EXCL_STOP */
    1546             :         }
    1547          26 :         if (WEXITSTATUS(ret) == 127) {
    1548             :                 /* LCOV_EXCL_START */
    1549             :                 log_tag("device:%s:%s:shell\n", file, name);
    1550             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (from sh).\n", cmd);
    1551             :                 return -1;
    1552             :                 /* LCOV_EXCL_STOP */
    1553             :         }
    1554             : 
    1555             :         /* store the return smartctl return value */
    1556          26 :         smart[SMART_FLAGS].raw = WEXITSTATUS(ret);
    1557             : 
    1558          26 :         return 0;
    1559             : }
    1560             : #endif
    1561             : 
    1562             : /**
    1563             :  * Compute disk usage by aggregating access statistics.
    1564             :  */
    1565             : #if HAVE_LINUX_DEVICE
    1566         137 : static int devstat(dev_t device, uint64_t* count)
    1567             : {
    1568             :         char path[PATH_MAX];
    1569             :         char buf[512];
    1570             :         int token;
    1571             :         int ret;
    1572             :         char* i;
    1573             : 
    1574         137 :         *count = 0;
    1575             : 
    1576         137 :         pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/stat", major(device), minor(device));
    1577             : 
    1578         137 :         ret = sysread(path, buf, sizeof(buf));
    1579         137 :         if (ret < 0) {
    1580             :                 /* LCOV_EXCL_START */
    1581             :                 log_fatal(errno, "Failed to read '%s'.\n", path);
    1582             :                 return -1;
    1583             :                 /* LCOV_EXCL_STOP */
    1584             :         }
    1585         137 :         if ((size_t)ret + 1 > sizeof(buf)) {
    1586             :                 /* LCOV_EXCL_START */
    1587             :                 log_fatal(EEXTERNAL, "Too long read '%s'.\n", path);
    1588             :                 return -1;
    1589             :                 /* LCOV_EXCL_STOP */
    1590             :         }
    1591             : 
    1592             :         /* ending 0 */
    1593         137 :         buf[ret] = 0;
    1594             : 
    1595         137 :         i = buf;
    1596         137 :         token = 1; /* token number */
    1597         685 :         while (*i) {
    1598             :                 char* n;
    1599             :                 char* e;
    1600             :                 unsigned long long v;
    1601             : 
    1602             :                 /* skip spaces */
    1603        2164 :                 while (*i && isspace(*i))
    1604        1479 :                         ++i;
    1605             : 
    1606             :                 /* read digits */
    1607         685 :                 n = i;
    1608        4895 :                 while (*i && isdigit(*i))
    1609        4210 :                         ++i;
    1610             : 
    1611         685 :                 if (i == n) /* if no digit, abort */
    1612         137 :                         break;
    1613         685 :                 if (*i == 0 || !isspace(*i)) /* if no space, abort */
    1614             :                         break;
    1615         685 :                 *i++ = 0; /* put a terminator */
    1616             : 
    1617         685 :                 v = strtoull(n, &e, 10);
    1618         685 :                 if (*e != 0)
    1619           0 :                         break;
    1620             : 
    1621             :                 /* sum reads and writes completed */
    1622         685 :                 if (token == 1 || token == 5) {
    1623         274 :                         *count += v;
    1624         274 :                         if (token == 5)
    1625         137 :                                 break; /* stop here */
    1626             :                 }
    1627             : 
    1628         548 :                 ++token;
    1629             :         }
    1630             : 
    1631         137 :         return 0;
    1632             : }
    1633             : #endif
    1634             : 
    1635             : /**
    1636             :  * Get device attributes.
    1637             :  */
    1638             : #if HAVE_LINUX_DEVICE
    1639          54 : static void devattr(dev_t device, uint64_t* info, char* serial, char* family, char* model, char* interface)
    1640             : {
    1641             :         char path[PATH_MAX];
    1642             :         char buf[512];
    1643             :         int ret;
    1644             : 
    1645             :         (void)family; /* not available, smartctl uses an internal database to get it */
    1646             : 
    1647          54 :         if (info[INFO_SIZE] == SMART_UNASSIGNED) {
    1648          12 :                 pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/size", major(device), minor(device));
    1649          12 :                 if (sysattr(path, buf, sizeof(buf)) == 0) {
    1650             :                         char* e;
    1651             :                         uint64_t v;
    1652          12 :                         v = strtoul(buf, &e, 10);
    1653          12 :                         if (*e == 0)
    1654          12 :                                 info[INFO_SIZE] = v * 512;
    1655             :                 }
    1656             :         }
    1657             : 
    1658          54 :         if (info[INFO_ROTATION_RATE] == SMART_UNASSIGNED) {
    1659          12 :                 pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/queue/rotational", major(device), minor(device));
    1660          12 :                 if (sysattr(path, buf, sizeof(buf)) == 0) {
    1661             :                         char* e;
    1662             :                         uint64_t v;
    1663          12 :                         v = strtoul(buf, &e, 10);
    1664          12 :                         if (*e == 0)
    1665          12 :                                 info[INFO_ROTATION_RATE] = v;
    1666             :                 }
    1667             :         }
    1668             : 
    1669          54 :         if (*model == 0) {
    1670          12 :                 pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/device/model", major(device), minor(device));
    1671          12 :                 if (sysattr(path, buf, sizeof(buf)) == 0) {
    1672          12 :                         if (buf[0] != 0)
    1673          12 :                                 pathcpy(model, SMART_MAX, buf);
    1674             :                 }
    1675             :         }
    1676             : 
    1677          54 :         if (*serial == 0) {
    1678          54 :                 pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/device/serial", major(device), minor(device));
    1679          54 :                 if (sysattr(path, buf, sizeof(buf)) == 0) {
    1680           0 :                         if (buf[0] != 0)
    1681           0 :                                 pathcpy(serial, SMART_MAX, buf);
    1682             :                 }
    1683             :         }
    1684             : 
    1685          54 :         if (*serial == 0) {
    1686             :                 // --- Page 0x80: Unit Serial Number ---
    1687          54 :                 pathprint(path, sizeof(path), "/sys/dev/block/%u:%u/device/vpd_pg80", major(device), minor(device));
    1688          54 :                 ret = sysread(path, buf, sizeof(buf));
    1689          54 :                 if (ret > 4) {
    1690          54 :                         unsigned len = (unsigned char)buf[3];
    1691          54 :                         if (4 + len <= (size_t)ret && 4 + len + 1 <= sizeof(buf)) {
    1692          54 :                                 char* attr = buf + 4;
    1693          54 :                                 attr[len] = 0;
    1694          54 :                                 strtrim(attr);
    1695          54 :                                 if (*attr)
    1696          54 :                                         pathcpy(serial, SMART_MAX, attr);
    1697             :                         }
    1698             :                 }
    1699             :         }
    1700             : 
    1701             :         /* always override interface if it's usb */
    1702          54 :         pathprint(path, sizeof(path), "/sys/dev/block/%u:%u", major(device), minor(device));
    1703          54 :         ret = readlink(path, buf, sizeof(buf));
    1704          54 :         if (ret > 0 && (unsigned)ret < sizeof(buf)) {
    1705          54 :                 buf[ret] = 0;
    1706          54 :                 if (strstr(buf, "usb") != 0)
    1707           0 :                         strcpy(interface, "USB");
    1708             :         }
    1709          54 : }
    1710             : #endif
    1711             : 
    1712             : /**
    1713             :  * Get POWER state.
    1714             :  */
    1715             : #if HAVE_LINUX_DEVICE
    1716          28 : static int devprobe(dev_t device, const char* name, const char* smartctl, int* power, struct smart_attr* smart, uint64_t* info, char* serial, char* family, char* model, char* interface)
    1717             : {
    1718             :         char cmd[PATH_MAX + 64];
    1719             :         char file[PATH_MAX];
    1720             :         FILE* f;
    1721             :         int ret;
    1722             :         const char* x;
    1723             : 
    1724          28 :         x = find_smartctl();
    1725          28 :         if (!x) {
    1726             :                 /* LCOV_EXCL_START */
    1727             :                 log_fatal(EEXTERNAL, "Cannot find smartctl.\n");
    1728             :                 return -1;
    1729             :                 /* LCOV_EXCL_STOP */
    1730             :         }
    1731             : 
    1732          28 :         if (devresolve(device, file, sizeof(file)) != 0) {
    1733             :                 /* LCOV_EXCL_START */
    1734             :                 log_fatal(EEXTERNAL, "Failed to resolve device '%u:%u'.\n", major(device), minor(device));
    1735             :                 return -1;
    1736             :                 /* LCOV_EXCL_STOP */
    1737             :         }
    1738             : 
    1739             :         /* if there is a custom smartctl command */
    1740          28 :         if (smartctl[0]) {
    1741             :                 char option[PATH_MAX];
    1742           0 :                 snprintf(option, sizeof(option), smartctl, file);
    1743           0 :                 snprintf(cmd, sizeof(cmd), "%s -n standby,3 -a %s", x, option);
    1744             :         } else {
    1745          28 :                 snprintf(cmd, sizeof(cmd), "%s -n standby,3 -a %s", x, file);
    1746             :         }
    1747             : 
    1748          28 :         log_tag("smartctl:%s:%s:run: %s\n", file, name, cmd);
    1749             : 
    1750          28 :         f = popen(cmd, "r");
    1751          28 :         if (!f) {
    1752             :                 /* LCOV_EXCL_START */
    1753             :                 log_tag("device:%s:%s:shell\n", file, name);
    1754             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (from popen).\n", cmd);
    1755             :                 return -1;
    1756             :                 /* LCOV_EXCL_STOP */
    1757             :         }
    1758             : 
    1759          28 :         if (smartctl_attribute(f, file, name, smart, info, serial, family, model, interface) != 0) {
    1760             :                 /* LCOV_EXCL_START */
    1761             :                 pclose(f);
    1762             :                 log_tag("device:%s:%s:shell\n", file, name);
    1763             :                 return -1;
    1764             :                 /* LCOV_EXCL_STOP */
    1765             :         }
    1766             : 
    1767          28 :         ret = pclose(f);
    1768             : 
    1769          28 :         log_tag("smartctl:%s:%s:ret: %x\n", file, name, ret);
    1770             : 
    1771          28 :         if (!WIFEXITED(ret)) {
    1772             :                 /* LCOV_EXCL_START */
    1773             :                 log_tag("device:%s:%s:abort\n", file, name);
    1774             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (not exited).\n", cmd);
    1775             :                 return -1;
    1776             :                 /* LCOV_EXCL_STOP */
    1777             :         }
    1778          28 :         if (WEXITSTATUS(ret) == 127) {
    1779             :                 /* LCOV_EXCL_START */
    1780             :                 log_tag("device:%s:%s:shell\n", file, name);
    1781             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (from sh).\n", cmd);
    1782             :                 return -1;
    1783             :                 /* LCOV_EXCL_STOP */
    1784             :         }
    1785             : 
    1786          28 :         if (WEXITSTATUS(ret) == 3) {
    1787          12 :                 log_tag("attr:%s:%s:power:standby\n", file, name);
    1788          12 :                 *power = POWER_STANDBY;
    1789             :         } else {
    1790          16 :                 log_tag("attr:%s:%s:power:active\n", file, name);
    1791          16 :                 *power = POWER_ACTIVE;
    1792             : 
    1793             :                 /* store the smartctl return value */
    1794          16 :                 if (smart)
    1795          16 :                         smart[SMART_FLAGS].raw = WEXITSTATUS(ret);
    1796             :         }
    1797             : 
    1798          28 :         return 0;
    1799             : }
    1800             : #endif
    1801             : 
    1802             : /**
    1803             :  * Spin down a specific device.
    1804             :  */
    1805             : #if HAVE_LINUX_DEVICE
    1806          17 : static int devdown(dev_t device, const char* name, const char* smartctl)
    1807             : {
    1808             :         char cmd[PATH_MAX + 64];
    1809             :         char file[PATH_MAX];
    1810             :         FILE* f;
    1811             :         int ret;
    1812             :         const char* x;
    1813             : 
    1814          17 :         x = find_smartctl();
    1815          17 :         if (!x) {
    1816             :                 /* LCOV_EXCL_START */
    1817             :                 log_fatal(EEXTERNAL, "Cannot find smartctl.\n");
    1818             :                 return -1;
    1819             :                 /* LCOV_EXCL_STOP */
    1820             :         }
    1821             : 
    1822          17 :         if (devresolve(device, file, sizeof(file)) != 0) {
    1823             :                 /* LCOV_EXCL_START */
    1824             :                 log_fatal(EEXTERNAL, "Failed to resolve device '%u:%u'.\n", major(device), minor(device));
    1825             :                 return -1;
    1826             :                 /* LCOV_EXCL_STOP */
    1827             :         }
    1828             : 
    1829             :         /* if there is a custom smartctl command */
    1830          17 :         if (smartctl[0]) {
    1831             :                 char option[PATH_MAX];
    1832           5 :                 snprintf(option, sizeof(option), smartctl, file);
    1833           5 :                 snprintf(cmd, sizeof(cmd), "%s -s standby,now %s", x, option);
    1834             :         } else {
    1835          12 :                 snprintf(cmd, sizeof(cmd), "%s -s standby,now %s", x, file);
    1836             :         }
    1837             : 
    1838          17 :         log_tag("smartctl:%s:%s:run: %s\n", file, name, cmd);
    1839             : 
    1840          17 :         f = popen(cmd, "r");
    1841          17 :         if (!f) {
    1842             :                 /* LCOV_EXCL_START */
    1843             :                 log_tag("device:%s:%s:shell\n", file, name);
    1844             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (from popen).\n", cmd);
    1845             :                 return -1;
    1846             :                 /* LCOV_EXCL_STOP */
    1847             :         }
    1848             : 
    1849          17 :         if (smartctl_flush(f, file, name) != 0) {
    1850             :                 /* LCOV_EXCL_START */
    1851             :                 pclose(f);
    1852             :                 log_tag("device:%s:%s:shell\n", file, name);
    1853             :                 return -1;
    1854             :                 /* LCOV_EXCL_STOP */
    1855             :         }
    1856             : 
    1857          17 :         ret = pclose(f);
    1858             : 
    1859          17 :         log_tag("smartctl:%s:%s:ret: %x\n", file, name, ret);
    1860             : 
    1861          17 :         if (!WIFEXITED(ret)) {
    1862             :                 /* LCOV_EXCL_START */
    1863             :                 log_tag("device:%s:%s:abort\n", file, name);
    1864             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (not exited).\n", cmd);
    1865             :                 return -1;
    1866             :                 /* LCOV_EXCL_STOP */
    1867             :         }
    1868          17 :         if (WEXITSTATUS(ret) == 127) {
    1869             :                 /* LCOV_EXCL_START */
    1870             :                 log_tag("device:%s:%s:shell\n", file, name);
    1871             :                 log_fatal(EEXTERNAL, "Failed to run '%s' (from sh).\n", cmd);
    1872             :                 return -1;
    1873             :                 /* LCOV_EXCL_STOP */
    1874             :         }
    1875          17 :         if (WEXITSTATUS(ret) != 0) {
    1876             :                 /* LCOV_EXCL_START */
    1877             :                 log_tag("device:%s:%s:exit:%d\n", file, name, WEXITSTATUS(ret));
    1878             :                 log_fatal(EEXTERNAL, "Failed to run '%s' with return code %xh.\n", cmd, WEXITSTATUS(ret));
    1879             :                 return -1;
    1880             :                 /* LCOV_EXCL_STOP */
    1881             :         }
    1882             : 
    1883          12 :         log_tag("attr:%s:%s:power:down\n", file, name);
    1884             : 
    1885          12 :         return 0;
    1886             : }
    1887             : #endif
    1888             : 
    1889             : /**
    1890             :  * Spin down a specific device if it's up.
    1891             :  */
    1892             : #if HAVE_LINUX_DEVICE
    1893           0 : static int devdownifup(dev_t device, const char* name, const char* smartctl, int* power)
    1894             : {
    1895           0 :         *power = POWER_UNKNOWN;
    1896             : 
    1897           0 :         if (devprobe(device, name, smartctl, power, 0, 0, 0, 0, 0, 0) != 0)
    1898           0 :                 return -1;
    1899             : 
    1900           0 :         if (*power == POWER_ACTIVE)
    1901           0 :                 return devdown(device, name, smartctl);
    1902             : 
    1903           0 :         return 0;
    1904             : }
    1905             : #endif
    1906             : 
    1907             : /**
    1908             :  * Spin up a specific device.
    1909             :  */
    1910             : #if HAVE_LINUX_DEVICE
    1911          42 : static int devup(dev_t device, const char* name)
    1912             : {
    1913             :         char file[PATH_MAX];
    1914             :         int ret;
    1915             :         int f;
    1916             :         void* buf;
    1917             :         uint64_t size;
    1918             :         uint64_t offset;
    1919             : 
    1920          42 :         if (devresolve(device, file, sizeof(file)) != 0) {
    1921             :                 /* LCOV_EXCL_START */
    1922             :                 log_fatal(EEXTERNAL, "Failed to resolve device '%u:%u'.\n", major(device), minor(device));
    1923             :                 return -1;
    1924             :                 /* LCOV_EXCL_STOP */
    1925             :         }
    1926             : 
    1927             :         /* O_DIRECT requires memory aligned to the block size */
    1928          42 :         if (posix_memalign(&buf, 4096, 4096) != 0) {
    1929             :                 /* LCOV_EXCL_START */
    1930             :                 log_fatal(errno, "Failed to allocate aligned memory for device '%u:%u'.\n", major(device), minor(device));
    1931             :                 return -1;
    1932             :                 /* LCOV_EXCL_STOP */
    1933             :         }
    1934             : 
    1935          42 :         f = open(file, O_RDONLY | O_DIRECT);
    1936          42 :         if (f < 0) {
    1937             :                 /* LCOV_EXCL_START */
    1938             :                 free(buf);
    1939             :                 log_tag("device:%s:%s:error:%d\n", file, name, errno);
    1940             :                 log_fatal(errno, "Failed to open device '%u:%u'.\n", major(device), minor(device));
    1941             :                 return -1;
    1942             :                 /* LCOV_EXCL_STOP */
    1943             :         }
    1944             : 
    1945          12 :         if (ioctl(f, BLKGETSIZE64, &size) < 0) {
    1946             :                 /* LCOV_EXCL_START */
    1947             :                 close(f);
    1948             :                 free(buf);
    1949             :                 log_tag("device:%s:%s:error:%d\n", file, name, errno);
    1950             :                 log_fatal(errno, "Failed to get device size '%u:%u'.\n", major(device), minor(device));
    1951             :                 return -1;
    1952             :                 /* LCOV_EXCL_STOP */
    1953             :         }
    1954             : 
    1955             :         /* select a random offset */
    1956          12 :         offset = (random_u64() % (size / 4096)) * 4096;
    1957             : 
    1958             : #if HAVE_POSIX_FADVISE
    1959             :         /* clear cache */
    1960          12 :         ret = posix_fadvise(f, offset, 4096, POSIX_FADV_DONTNEED);
    1961          12 :         if (ret != 0) {
    1962             :                 /* LCOV_EXCL_START */
    1963             :                 close(f);
    1964             :                 free(buf);
    1965             :                 log_tag("device:%s:%s:error:%d\n", file, name, errno);
    1966             :                 log_fatal(errno, "Failed to advise device '%u:%u'.\n", major(device), minor(device));
    1967             :                 return -1;
    1968             :                 /* LCOV_EXCL_STOP */
    1969             :         }
    1970             : #endif
    1971             : 
    1972          12 :         ret = pread(f, buf, 4096, offset);
    1973          12 :         if (ret < 0) {
    1974             :                 /* LCOV_EXCL_START */
    1975             :                 close(f);
    1976             :                 free(buf);
    1977             :                 log_tag("device:%s:%s:error:%d\n", file, name, errno);
    1978             :                 log_fatal(errno, "Failed to read device '%u:%u'.\n", major(device), minor(device));
    1979             :                 return -1;
    1980             :                 /* LCOV_EXCL_STOP */
    1981             :         }
    1982             : 
    1983          12 :         ret = close(f);
    1984          12 :         if (ret < 0) {
    1985             :                 /* LCOV_EXCL_START */
    1986             :                 free(buf);
    1987             :                 log_tag("device:%s:%s:error:%d\n", file, name, errno);
    1988             :                 log_fatal(errno, "Failed to close device '%u:%u'.\n", major(device), minor(device));
    1989             :                 return -1;
    1990             :                 /* LCOV_EXCL_STOP */
    1991             :         }
    1992             : 
    1993          12 :         log_tag("attr:%s:%s:power:up\n", file, name);
    1994             : 
    1995          12 :         free(buf);
    1996          12 :         return 0;
    1997             : }
    1998             : #endif
    1999             : 
    2000             : /**
    2001             :  * Thread for spinning up.
    2002             :  *
    2003             :  * Note that filling up the devinfo object is done inside this thread,
    2004             :  * to avoid to block the main thread if the device need to be spin up
    2005             :  * to handle stat/resolve requests.
    2006             :  */
    2007          42 : static void* thread_spinup(void* arg)
    2008             : {
    2009             : #if HAVE_LINUX_DEVICE
    2010          42 :         devinfo_t* devinfo = arg;
    2011             :         uint64_t start;
    2012             : 
    2013          42 :         start = tick_ms();
    2014             : 
    2015          42 :         if (devup(devinfo->device, devinfo->name) != 0) {
    2016             :                 /* LCOV_EXCL_START */
    2017             :                 return (void*)-1;
    2018             :                 /* LCOV_EXCL_STOP */
    2019             :         }
    2020             : 
    2021          12 :         msg_status("Spunup device '%s' for disk '%s' in %" PRIu64 " ms.\n", devinfo->file, devinfo->name, tick_ms() - start);
    2022             : 
    2023             :         /* after the spin up, get SMART info */
    2024          12 :         if (devsmart(devinfo->device, devinfo->name, devinfo->smartctl, devinfo->smart, devinfo->info, devinfo->serial, devinfo->family, devinfo->model, devinfo->interf) != 0) {
    2025             :                 /* LCOV_EXCL_START */
    2026             :                 return (void*)-1;
    2027             :                 /* LCOV_EXCL_STOP */
    2028             :         }
    2029             : 
    2030             :         /*
    2031             :          * Retrieve some attributes directly from the system.
    2032             :          *
    2033             :          * smartctl intentionally skips queries on devices in standby mode
    2034             :          * to prevent accidentally spinning them up.
    2035             :          */
    2036          12 :         devattr(devinfo->device, devinfo->info, devinfo->serial, devinfo->family, devinfo->model, devinfo->interf);
    2037             : 
    2038          12 :         return 0;
    2039             : #else
    2040             :         (void)arg;
    2041             :         return (void*)-1;
    2042             : #endif
    2043             : }
    2044             : 
    2045             : /**
    2046             :  * Thread for spinning down.
    2047             :  */
    2048          17 : static void* thread_spindown(void* arg)
    2049             : {
    2050             : #if HAVE_LINUX_DEVICE
    2051          17 :         devinfo_t* devinfo = arg;
    2052             :         uint64_t start;
    2053             : 
    2054          17 :         start = tick_ms();
    2055             : 
    2056          17 :         if (devdown(devinfo->device, devinfo->name, devinfo->smartctl) != 0) {
    2057             :                 /* LCOV_EXCL_START */
    2058             :                 return (void*)-1;
    2059             :                 /* LCOV_EXCL_STOP */
    2060             :         }
    2061             : 
    2062          12 :         msg_status("Spundown device '%s' for disk '%s' in %" PRIu64 " ms.\n", devinfo->file, devinfo->name, tick_ms() - start);
    2063             : 
    2064          12 :         return 0;
    2065             : #else
    2066             :         (void)arg;
    2067             :         return (void*)-1;
    2068             : #endif
    2069             : }
    2070             : 
    2071             : /**
    2072             :  * Thread for spinning down.
    2073             :  */
    2074           0 : static void* thread_spindownifup(void* arg)
    2075             : {
    2076             : #if HAVE_LINUX_DEVICE
    2077           0 :         devinfo_t* devinfo = arg;
    2078             :         uint64_t start;
    2079             :         int power;
    2080             : 
    2081           0 :         start = tick_ms();
    2082             : 
    2083           0 :         if (devdownifup(devinfo->device, devinfo->name, devinfo->smartctl, &power) != 0) {
    2084             :                 /* LCOV_EXCL_START */
    2085             :                 return (void*)-1;
    2086             :                 /* LCOV_EXCL_STOP */
    2087             :         }
    2088             : 
    2089           0 :         if (power == POWER_ACTIVE)
    2090           0 :                 msg_status("Spundown device '%s' for disk '%s' in %" PRIu64 " ms.\n", devinfo->file, devinfo->name, tick_ms() - start);
    2091             : 
    2092           0 :         return 0;
    2093             : #else
    2094             :         (void)arg;
    2095             :         return (void*)-1;
    2096             : #endif
    2097             : }
    2098             : 
    2099             : /**
    2100             :  * Thread for getting smart info.
    2101             :  */
    2102          14 : static void* thread_smart(void* arg)
    2103             : {
    2104             : #if HAVE_LINUX_DEVICE
    2105          14 :         devinfo_t* devinfo = arg;
    2106             : 
    2107          14 :         if (devsmart(devinfo->device, devinfo->name, devinfo->smartctl, devinfo->smart, devinfo->info, devinfo->serial, devinfo->family, devinfo->model, devinfo->interf) != 0) {
    2108             :                 /* LCOV_EXCL_START */
    2109             :                 return (void*)-1;
    2110             :                 /* LCOV_EXCL_STOP */
    2111             :         }
    2112             : 
    2113             :         /*
    2114             :          * Retrieve some attributes directly from the system.
    2115             :          *
    2116             :          * smartctl intentionally skips queries on devices in standby mode
    2117             :          * to prevent accidentally spinning them up.
    2118             :          */
    2119          14 :         devattr(devinfo->device, devinfo->info, devinfo->serial, devinfo->family, devinfo->model, devinfo->interf);
    2120             : 
    2121          14 :         return 0;
    2122             : #else
    2123             :         (void)arg;
    2124             :         return (void*)-1;
    2125             : #endif
    2126             : }
    2127             : 
    2128             : /**
    2129             :  * Thread for getting power info.
    2130             :  */
    2131          28 : static void* thread_probe(void* arg)
    2132             : {
    2133             : #if HAVE_LINUX_DEVICE
    2134          28 :         devinfo_t* devinfo = arg;
    2135             : 
    2136          28 :         if (devprobe(devinfo->device, devinfo->name, devinfo->smartctl, &devinfo->power, devinfo->smart, devinfo->info, devinfo->serial, devinfo->family, devinfo->model, devinfo->interf) != 0) {
    2137             :                 /* LCOV_EXCL_START */
    2138             :                 return (void*)-1;
    2139             :                 /* LCOV_EXCL_STOP */
    2140             :         }
    2141             : 
    2142             :         /*
    2143             :          * Retrieve some attributes directly from the system.
    2144             :          *
    2145             :          * smartctl intentionally skips queries on devices in standby mode
    2146             :          * to prevent accidentally spinning them up.
    2147             :          */
    2148          28 :         devattr(devinfo->device, devinfo->info, devinfo->serial, devinfo->family, devinfo->model, devinfo->interf);
    2149             : 
    2150          28 :         return 0;
    2151             : #else
    2152             :         (void)arg;
    2153             :         return (void*)-1;
    2154             : #endif
    2155             : }
    2156             : 
    2157           7 : static int device_thread(tommy_list* list, void* (*func)(void* arg))
    2158             : {
    2159           7 :         int fail = 0;
    2160             :         tommy_node* i;
    2161             : 
    2162             : #if HAVE_THREAD
    2163             :         /* start all threads */
    2164         108 :         for (i = tommy_list_head(list); i != 0; i = i->next) {
    2165         101 :                 devinfo_t* devinfo = i->data;
    2166             : 
    2167         101 :                 thread_create(&devinfo->thread, func, devinfo);
    2168             :         }
    2169             : 
    2170             :         /* join all threads */
    2171         108 :         for (i = tommy_list_head(list); i != 0; i = i->next) {
    2172         101 :                 devinfo_t* devinfo = i->data;
    2173             :                 void* retval;
    2174             : 
    2175         101 :                 thread_join(devinfo->thread, &retval);
    2176             : 
    2177         101 :                 if (retval != 0)
    2178          35 :                         ++fail;
    2179             :         }
    2180             : #else
    2181             :         for (i = tommy_list_head(list); i != 0; i = i->next) {
    2182             :                 devinfo_t* devinfo = i->data;
    2183             : 
    2184             :                 if (func(devinfo) != 0)
    2185             :                         ++fail;
    2186             :         }
    2187             : #endif
    2188           7 :         if (fail != 0) {
    2189             :                 /* LCOV_EXCL_START */
    2190             :                 return -1;
    2191             :                 /* LCOV_EXCL_STOP */
    2192             :         }
    2193             : 
    2194           5 :         return 0;
    2195             : }
    2196             : 
    2197           9 : int devquery(tommy_list* high, tommy_list* low, int operation, int others)
    2198             : {
    2199           9 :         void* (*func)(void* arg) = 0;
    2200             : 
    2201             : #if HAVE_LINUX_DEVICE
    2202             :         tommy_node* i;
    2203             :         struct stat st;
    2204             : 
    2205             :         /* sysfs interface is required */
    2206           9 :         if (stat("/sys/dev/block", &st) != 0) {
    2207             :                 /* LCOV_EXCL_START */
    2208             :                 log_fatal(EEXTERNAL, "Missing interface /sys/dev/block.\n");
    2209             :                 return -1;
    2210             :                 /* LCOV_EXCL_STOP */
    2211             :         }
    2212             : 
    2213             :         /* for each device */
    2214         146 :         for (i = tommy_list_head(high); i != 0; i = i->next) {
    2215         137 :                 devinfo_t* devinfo = i->data;
    2216         137 :                 uint64_t device = devinfo->device;
    2217             :                 uint64_t access_stat;
    2218             : 
    2219             : #if HAVE_SYNCFS
    2220         137 :                 if (operation == DEVICE_DOWN) {
    2221             :                         /* flush the high level filesystem before spinning down */
    2222          17 :                         int f = open(devinfo->mount, O_RDONLY);
    2223          17 :                         if (f >= 0) {
    2224          17 :                                 syncfs(f);
    2225          17 :                                 close(f);
    2226             :                         }
    2227             :                 }
    2228             : #endif
    2229             : 
    2230             :                 /* if the major is the null device, find the real one */
    2231         137 :                 if (major(device) == 0) {
    2232             :                         /* obtain the real device */
    2233           0 :                         if (devdereference(device, &device) != 0) {
    2234             :                                 /* LCOV_EXCL_START */
    2235             :                                 log_fatal(EEXTERNAL, "Failed to dereference device '%u:%u'.\n", major(device), minor(device));
    2236             :                                 return -1;
    2237             :                                 /* LCOV_EXCL_STOP */
    2238             :                         }
    2239             :                 }
    2240             : 
    2241             :                 /* retrieve access stat for the high level device */
    2242         137 :                 if (devstat(device, &access_stat) == 0) {
    2243             :                         /* cumulate access stat in the first split */
    2244         137 :                         if (devinfo->split)
    2245          39 :                                 devinfo->split->access_stat += access_stat;
    2246             :                         else
    2247          98 :                                 devinfo->access_stat += access_stat;
    2248             :                 }
    2249             : 
    2250             :                 /* get the device file */
    2251         137 :                 if (devresolve(device, devinfo->file, sizeof(devinfo->file)) != 0) {
    2252             :                         /* LCOV_EXCL_START */
    2253             :                         log_fatal(EEXTERNAL, "Failed to resolve device '%u:%u'.\n", major(device), minor(device));
    2254             :                         return -1;
    2255             :                         /* LCOV_EXCL_STOP */
    2256             :                 }
    2257             : 
    2258             :                 /* expand the tree of devices */
    2259         137 :                 if (devtree(devinfo, device, low) != 0) {
    2260             :                         /* LCOV_EXCL_START */
    2261             :                         log_fatal(EEXTERNAL, "Failed to expand device '%u:%u'.\n", major(device), minor(device));
    2262             :                         return -1;
    2263             :                         /* LCOV_EXCL_STOP */
    2264             :                 }
    2265             :         }
    2266             : 
    2267             :         /* add other devices */
    2268           9 :         if (others) {
    2269           3 :                 if (devscan(low) != 0) {
    2270             :                         /* LCOV_EXCL_START */
    2271             :                         log_fatal(EEXTERNAL, "Failed to list other devices.\n");
    2272             :                         return -1;
    2273             :                         /* LCOV_EXCL_STOP */
    2274             :                 }
    2275             :         }
    2276             : #else
    2277             :         (void)high;
    2278             :         (void)others;
    2279             : #endif
    2280             : 
    2281           9 :         switch (operation) {
    2282           2 :         case DEVICE_UP : func = thread_spinup; break;
    2283           2 :         case DEVICE_DOWN : func = thread_spindown; break;
    2284           1 :         case DEVICE_SMART : func = thread_smart; break;
    2285           2 :         case DEVICE_PROBE : func = thread_probe; break;
    2286           0 :         case DEVICE_DOWNIFUP : func = thread_spindownifup; break;
    2287             :         }
    2288             : 
    2289           9 :         if (!func)
    2290           2 :                 return 0;
    2291             : 
    2292           7 :         return device_thread(low, func);
    2293             : }
    2294             : 
    2295         297 : void os_init(int opt)
    2296             : {
    2297             : #if HAVE_BLKID
    2298             :         int ret;
    2299         297 :         ret = blkid_get_cache(&cache, NULL);
    2300         297 :         if (ret != 0) {
    2301             :                 /* LCOV_EXCL_START */
    2302             :                 log_fatal(EEXTERNAL, "WARNING Failed to get blkid cache\n");
    2303             :                 /* LCOV_EXCL_STOP */
    2304             :         }
    2305             : #endif
    2306             : 
    2307             :         (void)opt;
    2308         297 : }
    2309             : 
    2310         286 : void os_done(void)
    2311             : {
    2312             : #if HAVE_BLKID
    2313         286 :         if (cache != 0)
    2314         286 :                 blkid_put_cache(cache);
    2315             : #endif
    2316         286 : }
    2317             : 
    2318             : /* LCOV_EXCL_START */
    2319             : void os_abort(void)
    2320             : {
    2321             : #if HAVE_BACKTRACE && HAVE_BACKTRACE_SYMBOLS
    2322             :         void* stack[32];
    2323             :         char** messages;
    2324             :         size_t size;
    2325             :         unsigned i;
    2326             : #endif
    2327             : 
    2328             :         printf("Stacktrace of " PACKAGE " v" VERSION);
    2329             : #ifdef _linux
    2330             :         printf(", linux");
    2331             : #endif
    2332             : #ifdef __GNUC__
    2333             :         printf(", gcc " __VERSION__);
    2334             : #endif
    2335             :         printf(", %d-bit", (int)sizeof(void*) * 8);
    2336             :         printf(", PATH_MAX=%d", PATH_MAX);
    2337             :         printf("\n");
    2338             : 
    2339             : #if HAVE_BACKTRACE && HAVE_BACKTRACE_SYMBOLS
    2340             :         size = backtrace(stack, 32);
    2341             : 
    2342             :         messages = backtrace_symbols(stack, size);
    2343             : 
    2344             :         for (i = 1; i < size; ++i) {
    2345             :                 const char* msg;
    2346             : 
    2347             :                 if (messages)
    2348             :                         msg = messages[i];
    2349             :                 else
    2350             :                         msg = "<unknown>";
    2351             : 
    2352             :                 printf("[bt] %02u: %s\n", i, msg);
    2353             : 
    2354             :                 if (messages) {
    2355             :                         int ret;
    2356             :                         char addr2line[1024];
    2357             :                         size_t j = 0;
    2358             :                         while (msg[j] != '(' && msg[j] != ' ' && msg[j] != 0)
    2359             :                                 ++j;
    2360             : 
    2361             :                         snprintf(addr2line, sizeof(addr2line), "addr2line %p -e %.*s", stack[i], (unsigned)j, msg);
    2362             : 
    2363             :                         ret = system(addr2line);
    2364             :                         if (WIFEXITED(ret) && WEXITSTATUS(ret) != 0)
    2365             :                                 printf("exit:%d\n", WEXITSTATUS(ret));
    2366             :                         if (WIFSIGNALED(ret))
    2367             :                                 printf("signal:%d\n", WTERMSIG(ret));
    2368             :                 }
    2369             :         }
    2370             : #endif
    2371             : 
    2372             :         printf("Please report this error to the SnapRAID Forum:\n");
    2373             :         printf("https://sourceforge.net/p/snapraid/discussion/1677233/\n");
    2374             : 
    2375             :         abort();
    2376             : }
    2377             : /* LCOV_EXCL_STOP */
    2378             : 
    2379           1 : void os_clear(void)
    2380             : {
    2381             :         /* ANSI codes */
    2382           1 :         printf("\033[H"); /* cursor at topleft */
    2383           1 :         printf("\033[2J"); /* clear screen */
    2384           1 : }
    2385             : 
    2386         135 : size_t direct_size(void)
    2387             : {
    2388             :         long size;
    2389             : 
    2390         135 :         size = sysconf(_SC_PAGESIZE);
    2391             : 
    2392         135 :         if (size == -1) {
    2393             :                 /* LCOV_EXCL_START */
    2394             :                 log_fatal(EEXTERNAL, "No page size\n");
    2395             :                 exit(EXIT_FAILURE);
    2396             :                 /* LCOV_EXCL_STOP */
    2397             :         }
    2398             : 
    2399         135 :         return size;
    2400             : }
    2401             : 
    2402             : #if HAVE_LINUX_DEVICE
    2403             : 
    2404             : /* List of possible ambient temperature labels */
    2405             : const char* AMBIENT_LABEL[] = {
    2406             :         "systin",
    2407             :         "auxtin",
    2408             :         "mb",
    2409             :         "m/b",
    2410             :         "board",
    2411             :         "motherboard",
    2412             :         "system",
    2413             :         "chassis",
    2414             :         "case",
    2415             :         "room",
    2416             :         "ambient",
    2417             :         0
    2418             : };
    2419             : 
    2420           1 : int ambient_temperature(void)
    2421             : {
    2422             :         DIR* dir;
    2423             :         struct dirent* entry;
    2424           1 :         int lowest_temp = 0;
    2425             : 
    2426           1 :         dir = opendir("/sys/class/hwmon");
    2427           1 :         if (!dir)
    2428           0 :                 return 0;
    2429             : 
    2430             :         /* iterate through hwmon devices */
    2431           5 :         while ((entry = readdir(dir)) != NULL) {
    2432             :                 char path[PATH_MAX];
    2433             :                 DIR* hwmon_dir;
    2434             :                 struct dirent* hwmon_entry;
    2435             : 
    2436           4 :                 if (strncmp(entry->d_name, "hwmon", 5) != 0)
    2437           2 :                         continue;
    2438             : 
    2439           2 :                 pathprint(path, sizeof(path), "/sys/class/hwmon/%s", entry->d_name);
    2440             : 
    2441             :                 /* iterate through temp*_input files */
    2442           2 :                 hwmon_dir = opendir(path);
    2443           2 :                 if (!hwmon_dir)
    2444           0 :                         continue;
    2445             : 
    2446          66 :                 while ((hwmon_entry = readdir(hwmon_dir)) != NULL) {
    2447             :                         char value[128];
    2448             :                         char name[128];
    2449             :                         char label[128];
    2450             :                         char* dash;
    2451             :                         char* e;
    2452             :                         int temp;
    2453             : 
    2454          64 :                         if (strncmp(hwmon_entry->d_name, "temp", 4) != 0)
    2455          63 :                                 continue;
    2456             : 
    2457          18 :                         dash = strrchr(hwmon_entry->d_name, '_');
    2458          18 :                         if (dash == 0)
    2459           0 :                                 continue;
    2460             : 
    2461          18 :                         if (strcmp(dash, "_input") != 0)
    2462          14 :                                 continue;
    2463             : 
    2464             :                         /* read the temperature */
    2465           4 :                         pathprint(path, sizeof(path), "/sys/class/hwmon/%s/%s", entry->d_name, hwmon_entry->d_name);
    2466             : 
    2467           4 :                         if (sysattr(path, value, sizeof(value)) != 0)
    2468           0 :                                 continue;
    2469             : 
    2470           4 :                         temp = strtol(value, &e, 10) / 1000;
    2471           4 :                         if (*e != 0 && !isspace(*e))
    2472           0 :                                 continue;
    2473             : 
    2474             :                         /* cut the file name at "_input" */
    2475           4 :                         *dash = 0;
    2476             : 
    2477             :                         /* read the corresponding name */
    2478           4 :                         pathprint(path, sizeof(path), "/sys/class/hwmon/%s/name", entry->d_name);
    2479           4 :                         if (sysattr(path, name, sizeof(name)) != 0) {
    2480             :                                 /* fallback to using the hwmon name */
    2481           0 :                                 pathcpy(name, sizeof(name), entry->d_name);
    2482             :                         }
    2483             : 
    2484             :                         /* read the corresponding label file */
    2485           4 :                         pathprint(path, sizeof(path), "/sys/class/hwmon/%s/%s_label", entry->d_name, hwmon_entry->d_name);
    2486           4 :                         if (sysattr(path, label, sizeof(label)) != 0) {
    2487             :                                 /* fallback to using the temp* name (e.g., temp1, temp2) */
    2488           0 :                                 pathcpy(label, sizeof(label), hwmon_entry->d_name);
    2489             :                         }
    2490             : 
    2491           4 :                         log_tag("thermal:ambient:device:%s:%s:%s:%s:%d\n", entry->d_name, name, hwmon_entry->d_name, label, temp);
    2492             : 
    2493             :                         /* check if temperature is in reasonable range */
    2494           4 :                         if (temp < 15 || temp > 40)
    2495           3 :                                 continue;
    2496             : 
    2497             :                         /* lower case */
    2498           1 :                         strlwr(label);
    2499             : 
    2500             :                         /* check if label matches possible ambient labels */
    2501           3 :                         for (int i = 0; AMBIENT_LABEL[i]; ++i) {
    2502           3 :                                 if (worddigitstr(label, AMBIENT_LABEL[i]) != 0) {
    2503           1 :                                         log_tag("thermal:ambient:candidate:%d\n", temp);
    2504           1 :                                         if (lowest_temp == 0 || lowest_temp > temp)
    2505           1 :                                                 lowest_temp = temp;
    2506           1 :                                         break;
    2507             :                                 }
    2508             :                         }
    2509             : 
    2510             :                         /* accept also generic "temp1" */
    2511           1 :                         if (strcmp(label, "temp1") == 0) {
    2512           0 :                                 log_tag("thermal:ambient:candidate:%d\n", temp);
    2513           0 :                                 if (lowest_temp == 0 || lowest_temp > temp)
    2514           0 :                                         lowest_temp = temp;
    2515             :                         }
    2516             :                 }
    2517             : 
    2518           2 :                 closedir(hwmon_dir);
    2519             :         }
    2520             : 
    2521           1 :         closedir(dir);
    2522             : 
    2523           1 :         return lowest_temp;
    2524             : }
    2525             : #else
    2526             : int ambient_temperature(void)
    2527             : {
    2528             :         return 0;
    2529             : }
    2530             : #endif
    2531             : 
    2532             : #endif
    2533             : 

Generated by: LCOV version 1.0