btrfs-progs: ci: cache built dependencies
[platform/upstream/btrfs-progs.git] / utils-lib.c
1 #include "kerncompat.h"
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <limits.h>
5 #include <sys/ioctl.h>
6 #include <ioctl.h>
7
8 #if BTRFS_FLAT_INCLUDES
9 #include "ctree.h"
10 #else
11 #include <btrfs/ctree.h>
12 #endif /* BTRFS_FLAT_INCLUDES */
13
14 /*
15  * This function should be only used when parsing command arg, it won't return
16  * error to its caller and rather exit directly just like usage().
17  */
18 u64 arg_strtou64(const char *str)
19 {
20         u64 value;
21         char *ptr_parse_end = NULL;
22
23         value = strtoull(str, &ptr_parse_end, 0);
24         if (ptr_parse_end && *ptr_parse_end != '\0') {
25                 fprintf(stderr, "ERROR: %s is not a valid numeric value.\n",
26                         str);
27                 exit(1);
28         }
29
30         /*
31          * if we pass a negative number to strtoull, it will return an
32          * unexpected number to us, so let's do the check ourselves.
33          */
34         if (str[0] == '-') {
35                 fprintf(stderr, "ERROR: %s: negative value is invalid.\n",
36                         str);
37                 exit(1);
38         }
39         if (value == ULLONG_MAX) {
40                 fprintf(stderr, "ERROR: %s is too large.\n", str);
41                 exit(1);
42         }
43         return value;
44 }
45
46 /*
47  * For a given:
48  * - file or directory return the containing tree root id
49  * - subvolume return its own tree id
50  * - BTRFS_EMPTY_SUBVOL_DIR_OBJECTID (directory with ino == 2) the result is
51  *   undefined and function returns -1
52  */
53 int lookup_path_rootid(int fd, u64 *rootid)
54 {
55         struct btrfs_ioctl_ino_lookup_args args;
56         int ret;
57
58         memset(&args, 0, sizeof(args));
59         args.treeid = 0;
60         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
61
62         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
63         if (ret < 0)
64                 return -errno;
65
66         *rootid = args.treeid;
67
68         return 0;
69 }
70