btrfs-progs: corrupt-block: Fix -D option
[btrfs-progs-unstable/devel.git] / utils-lib.c
blob044f93fc4446db7fd8918a5909856fd7fbc5391c
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>
8 #if BTRFS_FLAT_INCLUDES
9 #include "ctree.h"
10 #else
11 #include <btrfs/ctree.h>
12 #endif /* BTRFS_FLAT_INCLUDES */
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().
18 u64 arg_strtou64(const char *str)
20 u64 value;
21 char *ptr_parse_end = NULL;
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);
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.
34 if (str[0] == '-') {
35 fprintf(stderr, "ERROR: %s: negative value is invalid.\n",
36 str);
37 exit(1);
39 if (value == ULLONG_MAX) {
40 fprintf(stderr, "ERROR: %s is too large.\n", str);
41 exit(1);
43 return value;
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
53 int lookup_path_rootid(int fd, u64 *rootid)
55 struct btrfs_ioctl_ino_lookup_args args;
56 int ret;
58 memset(&args, 0, sizeof(args));
59 args.treeid = 0;
60 args.objectid = BTRFS_FIRST_FREE_OBJECTID;
62 ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
63 if (ret < 0)
64 return -errno;
66 *rootid = args.treeid;
68 return 0;