Debian Codegraph @

src/udev/mtd_probe/mtd_probe.c

raw
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3 * Copyright © 2010 - Maxim Levitsky
4 *
5 * mtd_probe is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * mtd_probe is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with mtd_probe; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor,
18 * Boston, MA 02110-1301 USA
19 */
20
21 #include <fcntl.h>
22 #include <mtd/mtd-user.h>
23 #include <sys/ioctl.h>
24
25 #include "build.h"
26 #include "errno-util.h"
27 #include "fd-util.h"
28 #include "format-table.h"
29 #include "help-util.h"
30 #include "log.h"
31 #include "main-func.h"
32 #include "mtd_probe.h"
33 #include "options.h"
34 #include "strv.h"
35
36 static const char *arg_device = NULL;
37
38 static int help(void) {
39 _cleanup_(table_unrefp) Table *options = NULL;
40 int r;
41
42 r = option_parser_get_help_table(&options);
43 if (r < 0)
44 return r;
45
46 help_cmdline("[OPTIONS...] /dev/mtd[n]");
47 help_abstract("Probe MTD devices.");
48 help_section("Options");
49
50 return table_print_or_warn(options);
51 }
52
53 static int parse_argv(int argc, char *argv[]) {
54 assert(argc >= 0);
55 assert(argv);
56
57 OptionParser opts = { argc, argv };
58
59 FOREACH_OPTION_OR_RETURN(c, &opts)
60 switch (c) {
61
62 OPTION_COMMON_HELP:
63 return help();
64
65 OPTION_COMMON_VERSION:
66 return version();
67 }
68
69 char **args = option_parser_get_args(&opts);
70 if (strv_length(args) != 1)
71 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Need exactly one DEVICE argument.");
72
73 arg_device = args[0];
74 return 1;
75 }
76
77 static int run(int argc, char** argv) {
78 _cleanup_close_ int mtd_fd = -EBADF;
79 mtd_info_t mtd_info;
80 int r;
81
82 r = parse_argv(argc, argv);
83 if (r <= 0)
84 return r;
85
86 mtd_fd = open(arg_device, O_RDONLY|O_CLOEXEC|O_NOCTTY);
87 if (mtd_fd < 0) {
88 bool ignore = ERRNO_IS_DEVICE_ABSENT_OR_EMPTY(errno);
89 log_full_errno(ignore ? LOG_DEBUG : LOG_WARNING, errno,
90 "Failed to open device node '%s'%s: %m",
91 arg_device, ignore ? ", ignoring" : "");
92 return ignore ? 0 : -errno;
93 }
94
95 if (ioctl(mtd_fd, MEMGETINFO, &mtd_info) < 0)
96 return log_error_errno(errno, "MEMGETINFO ioctl failed: %m");
97
98 return probe_smart_media(mtd_fd, &mtd_info);
99 }
100
101 DEFINE_MAIN_FUNCTION(run);