]> git.proxmox.com Git - mirror_smartmontools-debian.git/blob - smartctl.cpp
import smartmontools 7.0
[mirror_smartmontools-debian.git] / smartctl.cpp
1 /*
2 * smartctl.cpp
3 *
4 * Home page of code is: http://www.smartmontools.org
5 *
6 * Copyright (C) 2002-11 Bruce Allen
7 * Copyright (C) 2008-16 Christian Franke
8 * Copyright (C) 2000 Michael Cornwell <cornwell@acm.org>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2, or (at your option)
13 * any later version.
14 *
15 * You should have received a copy of the GNU General Public License
16 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
17 *
18 * This code was originally developed as a Senior Thesis by Michael Cornwell
19 * at the Concurrent Systems Laboratory (now part of the Storage Systems
20 * Research Center), Jack Baskin School of Engineering, University of
21 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
22 *
23 */
24
25 #include <errno.h>
26 #include <stdio.h>
27 #include <sys/types.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdexcept>
32 #include <getopt.h>
33
34 #include "config.h"
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39
40 #if defined(__FreeBSD__)
41 #include <sys/param.h>
42 #endif
43
44 #include "int64.h"
45 #include "atacmds.h"
46 #include "dev_interface.h"
47 #include "ataprint.h"
48 #include "knowndrives.h"
49 #include "scsicmds.h"
50 #include "scsiprint.h"
51 #include "nvmeprint.h"
52 #include "smartctl.h"
53 #include "utility.h"
54
55 const char * smartctl_cpp_cvsid = "$Id: smartctl.cpp 4311 2016-04-27 21:03:01Z chrfranke $"
56 CONFIG_H_CVSID SMARTCTL_H_CVSID;
57
58 // Globals to control printing
59 bool printing_is_switchable = false;
60 bool printing_is_off = false;
61
62 static void printslogan()
63 {
64 pout("%s\n", format_version_info("smartctl").c_str());
65 }
66
67 static void UsageSummary()
68 {
69 pout("\nUse smartctl -h to get a usage summary\n\n");
70 return;
71 }
72
73 static std::string getvalidarglist(int opt);
74
75 /* void prints help information for command syntax */
76 static void Usage()
77 {
78 printf("Usage: smartctl [options] device\n\n");
79 printf(
80 "============================================ SHOW INFORMATION OPTIONS =====\n\n"
81 " -h, --help, --usage\n"
82 " Display this help and exit\n\n"
83 " -V, --version, --copyright, --license\n"
84 " Print license, copyright, and version information and exit\n\n"
85 " -i, --info\n"
86 " Show identity information for device\n\n"
87 " --identify[=[w][nvb]]\n"
88 " Show words and bits from IDENTIFY DEVICE data (ATA)\n\n"
89 " -g NAME, --get=NAME\n"
90 " Get device setting: all, aam, apm, lookahead, security, wcache, rcache, wcreorder\n\n"
91 " -a, --all\n"
92 " Show all SMART information for device\n\n"
93 " -x, --xall\n"
94 " Show all information for device\n\n"
95 " --scan\n"
96 " Scan for devices\n\n"
97 " --scan-open\n"
98 " Scan for devices and try to open each device\n\n"
99 );
100 printf(
101 "================================== SMARTCTL RUN-TIME BEHAVIOR OPTIONS =====\n\n"
102 " -q TYPE, --quietmode=TYPE (ATA)\n"
103 " Set smartctl quiet mode to one of: errorsonly, silent, noserial\n\n"
104 " -d TYPE, --device=TYPE\n"
105 " Specify device type to one of: %s\n\n"
106 " -T TYPE, --tolerance=TYPE (ATA)\n"
107 " Tolerance: normal, conservative, permissive, verypermissive\n\n"
108 " -b TYPE, --badsum=TYPE (ATA)\n"
109 " Set action on bad checksum to one of: warn, exit, ignore\n\n"
110 " -r TYPE, --report=TYPE\n"
111 " Report transactions (see man page)\n\n"
112 " -n MODE, --nocheck=MODE (ATA)\n"
113 " No check if: never, sleep, standby, idle (see man page)\n\n",
114 getvalidarglist('d').c_str()); // TODO: Use this function also for other options ?
115 printf(
116 "============================== DEVICE FEATURE ENABLE/DISABLE COMMANDS =====\n\n"
117 " -s VALUE, --smart=VALUE\n"
118 " Enable/disable SMART on device (on/off)\n\n"
119 " -o VALUE, --offlineauto=VALUE (ATA)\n"
120 " Enable/disable automatic offline testing on device (on/off)\n\n"
121 " -S VALUE, --saveauto=VALUE (ATA)\n"
122 " Enable/disable Attribute autosave on device (on/off)\n\n"
123 " -s NAME[,VALUE], --set=NAME[,VALUE]\n"
124 " Enable/disable/change device setting: aam,[N|off], apm,[N|off],\n"
125 " lookahead,[on|off], security-freeze, standby,[N|off|now],\n"
126 " wcache,[on|off], rcache,[on|off], wcreorder,[on|off]\n\n"
127 );
128 printf(
129 "======================================= READ AND DISPLAY DATA OPTIONS =====\n\n"
130 " -H, --health\n"
131 " Show device SMART health status\n\n"
132 " -c, --capabilities (ATA, NVMe)\n"
133 " Show device SMART capabilities\n\n"
134 " -A, --attributes\n"
135 " Show device SMART vendor-specific Attributes and values\n\n"
136 " -f FORMAT, --format=FORMAT (ATA)\n"
137 " Set output format for attributes: old, brief, hex[,id|val]\n\n"
138 " -l TYPE, --log=TYPE\n"
139 " Show device log. TYPE: error, selftest, selective, directory[,g|s],\n"
140 " xerror[,N][,error], xselftest[,N][,selftest],\n"
141 " background, sasphy[,reset], sataphy[,reset],\n"
142 " scttemp[sts,hist], scttempint,N[,p],\n"
143 " scterc[,N,M], devstat[,N], ssd,\n"
144 " gplog,N[,RANGE], smartlog,N[,RANGE],\n"
145 " nvmelog,N,SIZE\n\n"
146 " -v N,OPTION , --vendorattribute=N,OPTION (ATA)\n"
147 " Set display OPTION for vendor Attribute N (see man page)\n\n"
148 " -F TYPE, --firmwarebug=TYPE (ATA)\n"
149 " Use firmware bug workaround:\n"
150 " %s, swapid\n\n"
151 " -P TYPE, --presets=TYPE (ATA)\n"
152 " Drive-specific presets: use, ignore, show, showall\n\n"
153 " -B [+]FILE, --drivedb=[+]FILE (ATA)\n"
154 " Read and replace [add] drive database from FILE\n"
155 " [default is +%s",
156 get_valid_firmwarebug_args(),
157 get_drivedb_path_add()
158 );
159 #ifdef SMARTMONTOOLS_DRIVEDBDIR
160 printf(
161 "\n"
162 " and then %s",
163 get_drivedb_path_default()
164 );
165 #endif
166 printf(
167 "]\n\n"
168 "============================================ DEVICE SELF-TEST OPTIONS =====\n\n"
169 " -t TEST, --test=TEST\n"
170 " Run test. TEST: offline, short, long, conveyance, force, vendor,N,\n"
171 " select,M-N, pending,N, afterselect,[on|off]\n\n"
172 " -C, --captive\n"
173 " Do test in captive mode (along with -t)\n\n"
174 " -X, --abort\n"
175 " Abort any non-captive test on device\n\n"
176 );
177 std::string examples = smi()->get_app_examples("smartctl");
178 if (!examples.empty())
179 printf("%s\n", examples.c_str());
180 }
181
182 // Values for --long only options, see parse_options()
183 enum { opt_identify = 1000, opt_scan, opt_scan_open, opt_set, opt_smart };
184
185 /* Returns a string containing a formatted list of the valid arguments
186 to the option opt or empty on failure. Note 'v' case different */
187 static std::string getvalidarglist(int opt)
188 {
189 switch (opt) {
190 case 'q':
191 return "errorsonly, silent, noserial";
192 case 'd':
193 return smi()->get_valid_dev_types_str() + ", auto, test";
194 case 'T':
195 return "normal, conservative, permissive, verypermissive";
196 case 'b':
197 return "warn, exit, ignore";
198 case 'r':
199 return "ioctl[,N], ataioctl[,N], scsiioctl[,N], nvmeioctl[,N]";
200 case opt_smart:
201 case 'o':
202 case 'S':
203 return "on, off";
204 case 'l':
205 return "error, selftest, selective, directory[,g|s], "
206 "xerror[,N][,error], xselftest[,N][,selftest], "
207 "background, sasphy[,reset], sataphy[,reset], "
208 "scttemp[sts,hist], scttempint,N[,p], "
209 "scterc[,N,M], devstat[,N], ssd, "
210 "gplog,N[,RANGE], smartlog,N[,RANGE], "
211 "nvmelog,N,SIZE";
212 case 'P':
213 return "use, ignore, show, showall";
214 case 't':
215 return "offline, short, long, conveyance, force, vendor,N, select,M-N, "
216 "pending,N, afterselect,[on|off]";
217 case 'F':
218 return std::string(get_valid_firmwarebug_args()) + ", swapid";
219 case 'n':
220 return "never, sleep, standby, idle";
221 case 'f':
222 return "old, brief, hex[,id|val]";
223 case 'g':
224 return "aam, apm, lookahead, security, wcache, rcache, wcreorder";
225 case opt_set:
226 return "aam,[N|off], apm,[N|off], lookahead,[on|off], security-freeze, "
227 "standby,[N|off|now], wcache,[on|off], rcache,[on|off], wcreorder,[on|off]";
228 case 's':
229 return getvalidarglist(opt_smart)+", "+getvalidarglist(opt_set);
230 case opt_identify:
231 return "n, wn, w, v, wv, wb";
232 case 'v':
233 default:
234 return "";
235 }
236 }
237
238 /* Prints the message "=======> VALID ARGUMENTS ARE: <LIST> \n", where
239 <LIST> is the list of valid arguments for option opt. */
240 static void printvalidarglistmessage(int opt)
241 {
242 if (opt=='v'){
243 pout("=======> VALID ARGUMENTS ARE:\n\thelp\n%s\n<=======\n",
244 create_vendor_attribute_arg_list().c_str());
245 }
246 else {
247 // getvalidarglist() might produce a multiline or single line string. We
248 // need to figure out which to get the formatting right.
249 std::string s = getvalidarglist(opt);
250 char separator = strchr(s.c_str(), '\n') ? '\n' : ' ';
251 pout("=======> VALID ARGUMENTS ARE:%c%s%c<=======\n", separator, s.c_str(), separator);
252 }
253
254 return;
255 }
256
257 // Checksum error mode
258 enum checksum_err_mode_t {
259 CHECKSUM_ERR_WARN, CHECKSUM_ERR_EXIT, CHECKSUM_ERR_IGNORE
260 };
261
262 static checksum_err_mode_t checksum_err_mode = CHECKSUM_ERR_WARN;
263
264 static void scan_devices(const smart_devtype_list & types, bool with_open, char ** argv);
265
266
267 /* Takes command options and sets features to be run */
268 static const char * parse_options(int argc, char** argv,
269 ata_print_options & ataopts, scsi_print_options & scsiopts,
270 nvme_print_options & nvmeopts, bool & print_type_only)
271 {
272 // Please update getvalidarglist() if you edit shortopts
273 const char *shortopts = "h?Vq:d:T:b:r:s:o:S:HcAl:iaxv:P:t:CXF:n:B:f:g:";
274 // Please update getvalidarglist() if you edit longopts
275 struct option longopts[] = {
276 { "help", no_argument, 0, 'h' },
277 { "usage", no_argument, 0, 'h' },
278 { "version", no_argument, 0, 'V' },
279 { "copyright", no_argument, 0, 'V' },
280 { "license", no_argument, 0, 'V' },
281 { "quietmode", required_argument, 0, 'q' },
282 { "device", required_argument, 0, 'd' },
283 { "tolerance", required_argument, 0, 'T' },
284 { "badsum", required_argument, 0, 'b' },
285 { "report", required_argument, 0, 'r' },
286 { "smart", required_argument, 0, opt_smart },
287 { "offlineauto", required_argument, 0, 'o' },
288 { "saveauto", required_argument, 0, 'S' },
289 { "health", no_argument, 0, 'H' },
290 { "capabilities", no_argument, 0, 'c' },
291 { "attributes", no_argument, 0, 'A' },
292 { "log", required_argument, 0, 'l' },
293 { "info", no_argument, 0, 'i' },
294 { "all", no_argument, 0, 'a' },
295 { "xall", no_argument, 0, 'x' },
296 { "vendorattribute", required_argument, 0, 'v' },
297 { "presets", required_argument, 0, 'P' },
298 { "test", required_argument, 0, 't' },
299 { "captive", no_argument, 0, 'C' },
300 { "abort", no_argument, 0, 'X' },
301 { "firmwarebug", required_argument, 0, 'F' },
302 { "nocheck", required_argument, 0, 'n' },
303 { "drivedb", required_argument, 0, 'B' },
304 { "format", required_argument, 0, 'f' },
305 { "get", required_argument, 0, 'g' },
306 { "identify", optional_argument, 0, opt_identify },
307 { "set", required_argument, 0, opt_set },
308 { "scan", no_argument, 0, opt_scan },
309 { "scan-open", no_argument, 0, opt_scan_open },
310 { 0, 0, 0, 0 }
311 };
312
313 char extraerror[256];
314 memset(extraerror, 0, sizeof(extraerror));
315 opterr=optopt=0;
316
317 const char * type = 0; // set to -d optarg
318 smart_devtype_list scan_types; // multiple -d TYPE options for --scan
319 bool use_default_db = true; // set false on '-B FILE'
320 bool output_format_set = false; // set true on '-f FORMAT'
321 int scan = 0; // set by --scan, --scan-open
322 bool badarg = false, captive = false;
323 int testcnt = 0; // number of self-tests requested
324
325 int optchar;
326 char *arg;
327
328 while ((optchar = getopt_long(argc, argv, shortopts, longopts, 0)) != -1) {
329 switch (optchar){
330 case 'V':
331 printing_is_off = false;
332 pout("%s", format_version_info("smartctl", true /*full*/).c_str());
333 EXIT(0);
334 break;
335 case 'q':
336 if (!strcmp(optarg,"errorsonly")) {
337 printing_is_switchable = true;
338 printing_is_off = false;
339 } else if (!strcmp(optarg,"silent")) {
340 printing_is_switchable = false;
341 printing_is_off = true;
342 } else if (!strcmp(optarg,"noserial")) {
343 dont_print_serial_number = true;
344 } else {
345 badarg = true;
346 }
347 break;
348 case 'd':
349 if (!strcmp(optarg, "test"))
350 print_type_only = true;
351 else if (!strcmp(optarg, "auto")) {
352 type = 0;
353 scan_types.clear();
354 }
355 else {
356 type = optarg;
357 scan_types.push_back(optarg);
358 }
359 break;
360 case 'T':
361 if (!strcmp(optarg,"normal")) {
362 failuretest_conservative = false;
363 failuretest_permissive = 0;
364 } else if (!strcmp(optarg,"conservative")) {
365 failuretest_conservative = true;
366 } else if (!strcmp(optarg,"permissive")) {
367 if (failuretest_permissive < 0xff)
368 failuretest_permissive++;
369 } else if (!strcmp(optarg,"verypermissive")) {
370 failuretest_permissive = 0xff;
371 } else {
372 badarg = true;
373 }
374 break;
375 case 'b':
376 if (!strcmp(optarg,"warn")) {
377 checksum_err_mode = CHECKSUM_ERR_WARN;
378 } else if (!strcmp(optarg,"exit")) {
379 checksum_err_mode = CHECKSUM_ERR_EXIT;
380 } else if (!strcmp(optarg,"ignore")) {
381 checksum_err_mode = CHECKSUM_ERR_IGNORE;
382 } else {
383 badarg = true;
384 }
385 break;
386 case 'r':
387 {
388 int n1 = -1, n2 = -1, len = strlen(optarg);
389 char s[9+1]; unsigned i = 1;
390 sscanf(optarg, "%9[a-z]%n,%u%n", s, &n1, &i, &n2);
391 if (!((n1 == len || n2 == len) && 1 <= i && i <= 4)) {
392 badarg = true;
393 } else if (!strcmp(s,"ioctl")) {
394 ata_debugmode = scsi_debugmode = nvme_debugmode = i;
395 } else if (!strcmp(s,"ataioctl")) {
396 ata_debugmode = i;
397 } else if (!strcmp(s,"scsiioctl")) {
398 scsi_debugmode = i;
399 } else if (!strcmp(s,"nvmeioctl")) {
400 nvme_debugmode = i;
401 } else {
402 badarg = true;
403 }
404 }
405 break;
406
407 case 's':
408 case opt_smart: // --smart
409 if (!strcmp(optarg,"on")) {
410 ataopts.smart_enable = scsiopts.smart_enable = true;
411 ataopts.smart_disable = scsiopts.smart_disable = false;
412 } else if (!strcmp(optarg,"off")) {
413 ataopts.smart_disable = scsiopts.smart_disable = true;
414 ataopts.smart_enable = scsiopts.smart_enable = false;
415 } else if (optchar == 's') {
416 goto case_s_continued; // --set, see below
417 } else {
418 badarg = true;
419 }
420 break;
421
422 case 'o':
423 if (!strcmp(optarg,"on")) {
424 ataopts.smart_auto_offl_enable = true;
425 ataopts.smart_auto_offl_disable = false;
426 } else if (!strcmp(optarg,"off")) {
427 ataopts.smart_auto_offl_disable = true;
428 ataopts.smart_auto_offl_enable = false;
429 } else {
430 badarg = true;
431 }
432 break;
433 case 'S':
434 if (!strcmp(optarg,"on")) {
435 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = true;
436 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = false;
437 } else if (!strcmp(optarg,"off")) {
438 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = true;
439 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = false;
440 } else {
441 badarg = true;
442 }
443 break;
444 case 'H':
445 ataopts.smart_check_status = scsiopts.smart_check_status = nvmeopts.smart_check_status = true;
446 scsiopts.smart_ss_media_log = true;
447 break;
448 case 'F':
449 if (!strcmp(optarg, "swapid"))
450 ataopts.fix_swapped_id = true;
451 else if (!parse_firmwarebug_def(optarg, ataopts.firmwarebugs))
452 badarg = true;
453 break;
454 case 'c':
455 ataopts.smart_general_values = nvmeopts.drive_capabilities = true;
456 break;
457 case 'A':
458 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = nvmeopts.smart_vendor_attrib = true;
459 break;
460 case 'l':
461 if (str_starts_with(optarg, "error")) {
462 int n1 = -1, n2 = -1, len = strlen(optarg);
463 unsigned val = ~0;
464 sscanf(optarg, "error%n,%u%n", &n1, &val, &n2);
465 ataopts.smart_error_log = scsiopts.smart_error_log = true;
466 if (n1 == len)
467 nvmeopts.error_log_entries = 16;
468 else if (n2 == len && val > 0)
469 nvmeopts.error_log_entries = val;
470 else
471 badarg = true;
472 } else if (!strcmp(optarg,"selftest")) {
473 ataopts.smart_selftest_log = scsiopts.smart_selftest_log = true;
474 } else if (!strcmp(optarg, "selective")) {
475 ataopts.smart_selective_selftest_log = true;
476 } else if (!strcmp(optarg,"directory")) {
477 ataopts.smart_logdir = ataopts.gp_logdir = true; // SMART+GPL
478 } else if (!strcmp(optarg,"directory,s")) {
479 ataopts.smart_logdir = true; // SMART
480 } else if (!strcmp(optarg,"directory,g")) {
481 ataopts.gp_logdir = true; // GPL
482 } else if (!strcmp(optarg,"sasphy")) {
483 scsiopts.sasphy = true;
484 } else if (!strcmp(optarg,"sasphy,reset")) {
485 scsiopts.sasphy = scsiopts.sasphy_reset = true;
486 } else if (!strcmp(optarg,"sataphy")) {
487 ataopts.sataphy = true;
488 } else if (!strcmp(optarg,"sataphy,reset")) {
489 ataopts.sataphy = ataopts.sataphy_reset = true;
490 } else if (!strcmp(optarg,"background")) {
491 scsiopts.smart_background_log = true;
492 } else if (!strcmp(optarg,"ssd")) {
493 ataopts.devstat_ssd_page = true;
494 scsiopts.smart_ss_media_log = true;
495 } else if (!strcmp(optarg,"scterc")) {
496 ataopts.sct_erc_get = true;
497 } else if (!strcmp(optarg,"scttemp")) {
498 ataopts.sct_temp_sts = ataopts.sct_temp_hist = true;
499 } else if (!strcmp(optarg,"scttempsts")) {
500 ataopts.sct_temp_sts = true;
501 } else if (!strcmp(optarg,"scttemphist")) {
502 ataopts.sct_temp_hist = true;
503
504 } else if (!strncmp(optarg, "scttempint,", sizeof("scstempint,")-1)) {
505 unsigned interval = 0; int n1 = -1, n2 = -1, len = strlen(optarg);
506 if (!( sscanf(optarg,"scttempint,%u%n,p%n", &interval, &n1, &n2) == 1
507 && 0 < interval && interval <= 0xffff && (n1 == len || n2 == len))) {
508 snprintf(extraerror, sizeof(extraerror), "Option -l scttempint,N[,p] must have positive integer N\n");
509 badarg = true;
510 }
511 ataopts.sct_temp_int = interval;
512 ataopts.sct_temp_int_pers = (n2 == len);
513
514 } else if (!strncmp(optarg, "devstat", sizeof("devstat")-1)) {
515 int n1 = -1, n2 = -1, len = strlen(optarg);
516 unsigned val = ~0;
517 sscanf(optarg, "devstat%n,%u%n", &n1, &val, &n2);
518 if (n1 == len)
519 ataopts.devstat_all_pages = true;
520 else {
521 if (n2 != len) // retry with hex
522 sscanf(optarg, "devstat,0x%x%n", &val, &n2);
523 if (n2 == len && val <= 0xff)
524 ataopts.devstat_pages.push_back(val);
525 else
526 badarg = true;
527 }
528
529 } else if (!strncmp(optarg, "xerror", sizeof("xerror")-1)) {
530 int n1 = -1, n2 = -1, len = strlen(optarg);
531 unsigned val = 8;
532 sscanf(optarg, "xerror%n,error%n", &n1, &n2);
533 if (!(n1 == len || n2 == len)) {
534 n1 = n2 = -1;
535 sscanf(optarg, "xerror,%u%n,error%n", &val, &n1, &n2);
536 }
537 if ((n1 == len || n2 == len) && val > 0) {
538 ataopts.smart_ext_error_log = val;
539 ataopts.retry_error_log = (n2 == len);
540 }
541 else
542 badarg = true;
543
544 } else if (!strncmp(optarg, "xselftest", sizeof("xselftest")-1)) {
545 int n1 = -1, n2 = -1, len = strlen(optarg);
546 unsigned val = 25;
547 sscanf(optarg, "xselftest%n,selftest%n", &n1, &n2);
548 if (!(n1 == len || n2 == len)) {
549 n1 = n2 = -1;
550 sscanf(optarg, "xselftest,%u%n,selftest%n", &val, &n1, &n2);
551 }
552 if ((n1 == len || n2 == len) && val > 0) {
553 ataopts.smart_ext_selftest_log = val;
554 ataopts.retry_selftest_log = (n2 == len);
555 }
556 else
557 badarg = true;
558
559 } else if (!strncmp(optarg, "scterc,", sizeof("scterc,")-1)) {
560 unsigned rt = ~0, wt = ~0; int n = -1;
561 sscanf(optarg,"scterc,%u,%u%n", &rt, &wt, &n);
562 if (n == (int)strlen(optarg) && rt <= 999 && wt <= 999) {
563 ataopts.sct_erc_set = true;
564 ataopts.sct_erc_readtime = rt;
565 ataopts.sct_erc_writetime = wt;
566 }
567 else {
568 snprintf(extraerror, sizeof(extraerror), "Option -l scterc,[READTIME,WRITETIME] syntax error\n");
569 badarg = true;
570 }
571 } else if ( !strncmp(optarg, "gplog," , sizeof("gplog," )-1)
572 || !strncmp(optarg, "smartlog,", sizeof("smartlog,")-1)) {
573 unsigned logaddr = ~0U; unsigned page = 0, nsectors = 1; char sign = 0;
574 int n1 = -1, n2 = -1, n3 = -1, len = strlen(optarg);
575 sscanf(optarg, "%*[a-z],0x%x%n,%u%n%c%u%n",
576 &logaddr, &n1, &page, &n2, &sign, &nsectors, &n3);
577 if (len > n2 && n3 == -1 && !strcmp(optarg+n2, "-max")) {
578 nsectors = ~0U; sign = '+'; n3 = len;
579 }
580 bool gpl = (optarg[0] == 'g');
581 const char * erropt = (gpl ? "gplog" : "smartlog");
582 if (!( n1 == len || n2 == len
583 || (n3 == len && (sign == '+' || sign == '-')))) {
584 snprintf(extraerror, sizeof(extraerror), "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] syntax error\n", erropt);
585 badarg = true;
586 }
587 else if (!( logaddr <= 0xff && page <= (gpl ? 0xffffU : 0x00ffU)
588 && 0 < nsectors
589 && (nsectors <= (gpl ? 0xffffU : 0xffU) || nsectors == ~0U)
590 && (sign != '-' || page <= nsectors) )) {
591 snprintf(extraerror, sizeof(extraerror), "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] parameter out of range\n", erropt);
592 badarg = true;
593 }
594 else {
595 ata_log_request req;
596 req.gpl = gpl; req.logaddr = logaddr; req.page = page;
597 req.nsectors = (sign == '-' ? nsectors-page+1 : nsectors);
598 ataopts.log_requests.push_back(req);
599 }
600 }
601
602 else if (str_starts_with(optarg, "nvmelog,")) {
603 int n = -1, len = strlen(optarg);
604 unsigned page = 0, size = 0;
605 sscanf(optarg, "nvmelog,0x%x,0x%x%n", &page, &size, &n);
606 if (n == len && page <= 0xff && 0 < size && size <= 0x4000) {
607 nvmeopts.log_page = page; nvmeopts.log_page_size = size;
608 }
609 else
610 badarg = true;
611 }
612
613 else {
614 badarg = true;
615 }
616 break;
617 case 'i':
618 ataopts.drive_info = scsiopts.drive_info = nvmeopts.drive_info = true;
619 break;
620
621 case opt_identify:
622 ataopts.identify_word_level = ataopts.identify_bit_level = 0;
623 if (optarg) {
624 for (int i = 0; optarg[i]; i++) {
625 switch (optarg[i]) {
626 case 'w': ataopts.identify_word_level = 1; break;
627 case 'n': ataopts.identify_bit_level = -1; break;
628 case 'v': ataopts.identify_bit_level = 1; break;
629 case 'b': ataopts.identify_bit_level = 2; break;
630 default: badarg = true;
631 }
632 }
633 }
634 break;
635
636 case 'a':
637 ataopts.drive_info = scsiopts.drive_info = nvmeopts.drive_info = true;
638 ataopts.smart_check_status = scsiopts.smart_check_status = nvmeopts.smart_check_status = true;
639 ataopts.smart_general_values = nvmeopts.drive_capabilities = true;
640 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = nvmeopts.smart_vendor_attrib = true;
641 ataopts.smart_error_log = scsiopts.smart_error_log = true;
642 nvmeopts.error_log_entries = 16;
643 ataopts.smart_selftest_log = scsiopts.smart_selftest_log = true;
644 ataopts.smart_selective_selftest_log = true;
645 /* scsiopts.smart_background_log = true; */
646 scsiopts.smart_ss_media_log = true;
647 break;
648 case 'x':
649 ataopts.drive_info = scsiopts.drive_info = nvmeopts.drive_info = true;
650 ataopts.smart_check_status = scsiopts.smart_check_status = nvmeopts.smart_check_status = true;
651 ataopts.smart_general_values = nvmeopts.drive_capabilities = true;
652 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = nvmeopts.smart_vendor_attrib = true;
653 ataopts.smart_ext_error_log = 8;
654 ataopts.retry_error_log = true;
655 nvmeopts.error_log_entries = 16;
656 ataopts.smart_ext_selftest_log = 25;
657 ataopts.retry_selftest_log = true;
658 scsiopts.smart_error_log = scsiopts.smart_selftest_log = true;
659 ataopts.smart_selective_selftest_log = true;
660 ataopts.smart_logdir = ataopts.gp_logdir = true;
661 ataopts.sct_temp_sts = ataopts.sct_temp_hist = true;
662 ataopts.sct_erc_get = true;
663 ataopts.sct_wcache_reorder_get = true;
664 ataopts.devstat_all_pages = true;
665 ataopts.sataphy = true;
666 ataopts.get_set_used = true;
667 ataopts.get_aam = ataopts.get_apm = true;
668 ataopts.get_security = true;
669 ataopts.get_lookahead = ataopts.get_wcache = true;
670 scsiopts.get_rcd = scsiopts.get_wce = true;
671 scsiopts.smart_background_log = true;
672 scsiopts.smart_ss_media_log = true;
673 scsiopts.sasphy = true;
674 if (!output_format_set)
675 ataopts.output_format |= ata_print_options::FMT_BRIEF;
676 break;
677 case 'v':
678 // parse vendor-specific definitions of attributes
679 if (!strcmp(optarg,"help")) {
680 printing_is_off = false;
681 printslogan();
682 pout("The valid arguments to -v are:\n\thelp\n%s\n",
683 create_vendor_attribute_arg_list().c_str());
684 EXIT(0);
685 }
686 if (!parse_attribute_def(optarg, ataopts.attribute_defs, PRIOR_USER))
687 badarg = true;
688 break;
689 case 'P':
690 if (!strcmp(optarg, "use")) {
691 ataopts.ignore_presets = false;
692 } else if (!strcmp(optarg, "ignore")) {
693 ataopts.ignore_presets = true;
694 } else if (!strcmp(optarg, "show")) {
695 ataopts.show_presets = true;
696 } else if (!strcmp(optarg, "showall")) {
697 if (!init_drive_database(use_default_db))
698 EXIT(FAILCMD);
699 if (optind < argc) { // -P showall MODEL [FIRMWARE]
700 int cnt = showmatchingpresets(argv[optind], (optind+1<argc ? argv[optind+1] : NULL));
701 EXIT(cnt); // report #matches
702 }
703 if (showallpresets())
704 EXIT(FAILCMD); // report regexp syntax error
705 EXIT(0);
706 } else {
707 badarg = true;
708 }
709 break;
710 case 't':
711 if (!strcmp(optarg,"offline")) {
712 testcnt++;
713 ataopts.smart_selftest_type = OFFLINE_FULL_SCAN;
714 scsiopts.smart_default_selftest = true;
715 } else if (!strcmp(optarg,"short")) {
716 testcnt++;
717 ataopts.smart_selftest_type = SHORT_SELF_TEST;
718 scsiopts.smart_short_selftest = true;
719 } else if (!strcmp(optarg,"long")) {
720 testcnt++;
721 ataopts.smart_selftest_type = EXTEND_SELF_TEST;
722 scsiopts.smart_extend_selftest = true;
723 } else if (!strcmp(optarg,"conveyance")) {
724 testcnt++;
725 ataopts.smart_selftest_type = CONVEYANCE_SELF_TEST;
726 } else if (!strcmp(optarg,"force")) {
727 ataopts.smart_selftest_force = true;
728 scsiopts.smart_selftest_force = true;
729 } else if (!strcmp(optarg,"afterselect,on")) {
730 // scan remainder of disk after doing selected segment
731 ataopts.smart_selective_args.scan_after_select = 2;
732 } else if (!strcmp(optarg,"afterselect,off")) {
733 // don't scan remainder of disk after doing selected segments
734 ataopts.smart_selective_args.scan_after_select = 1;
735 } else if (!strncmp(optarg,"pending,",strlen("pending,"))) {
736 // parse number of minutes that test should be pending
737 int i;
738 char *tailptr=NULL;
739 errno=0;
740 i=(int)strtol(optarg+strlen("pending,"), &tailptr, 10);
741 if (errno || *tailptr != '\0') {
742 snprintf(extraerror, sizeof(extraerror), "Option -t pending,N requires N to be a non-negative integer\n");
743 badarg = true;
744 } else if (i<0 || i>65535) {
745 snprintf(extraerror, sizeof(extraerror), "Option -t pending,N (N=%d) must have 0 <= N <= 65535\n", i);
746 badarg = true;
747 } else {
748 ataopts.smart_selective_args.pending_time = i+1;
749 }
750 } else if (!strncmp(optarg,"select",strlen("select"))) {
751 if (ataopts.smart_selective_args.num_spans == 0)
752 testcnt++;
753 // parse range of LBAs to test
754 uint64_t start, stop; int mode;
755 if (split_selective_arg(optarg, &start, &stop, &mode)) {
756 snprintf(extraerror, sizeof(extraerror), "Option -t select,M-N must have non-negative integer M and N\n");
757 badarg = true;
758 } else {
759 if (ataopts.smart_selective_args.num_spans >= 5 || start > stop) {
760 if (start > stop) {
761 snprintf(extraerror, sizeof(extraerror), "ERROR: Start LBA (%" PRIu64 ") > ending LBA (%" PRId64 ") in argument \"%s\"\n",
762 start, stop, optarg);
763 } else {
764 snprintf(extraerror, sizeof(extraerror),"ERROR: No more than five selective self-test spans may be"
765 " defined\n");
766 }
767 badarg = true;
768 }
769 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].start = start;
770 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].end = stop;
771 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].mode = mode;
772 ataopts.smart_selective_args.num_spans++;
773 ataopts.smart_selftest_type = SELECTIVE_SELF_TEST;
774 }
775 } else if (!strncmp(optarg, "scttempint", sizeof("scstempint")-1)) {
776 snprintf(extraerror, sizeof(extraerror), "-t scttempint is no longer supported, use -l scttempint instead\n");
777 badarg = true;
778 } else if (!strncmp(optarg, "vendor,", sizeof("vendor,")-1)) {
779 unsigned subcmd = ~0U; int n = -1;
780 if (!( sscanf(optarg, "%*[a-z],0x%x%n", &subcmd, &n) == 1
781 && subcmd <= 0xff && n == (int)strlen(optarg))) {
782 snprintf(extraerror, sizeof(extraerror), "Option -t vendor,0xNN syntax error\n");
783 badarg = true;
784 }
785 else
786 ataopts.smart_selftest_type = subcmd;
787 } else {
788 badarg = true;
789 }
790 break;
791 case 'C':
792 captive = true;
793 break;
794 case 'X':
795 testcnt++;
796 scsiopts.smart_selftest_abort = true;
797 ataopts.smart_selftest_type = ABORT_SELF_TEST;
798 break;
799 case 'n':
800 // skip disk check if in low-power mode
801 if (!strcmp(optarg, "never"))
802 ataopts.powermode = 1; // do not skip, but print mode
803 else if (!strcmp(optarg, "sleep"))
804 ataopts.powermode = 2;
805 else if (!strcmp(optarg, "standby"))
806 ataopts.powermode = 3;
807 else if (!strcmp(optarg, "idle"))
808 ataopts.powermode = 4;
809 else
810 badarg = true;
811 break;
812 case 'f':
813 if (!strcmp(optarg, "old")) {
814 ataopts.output_format &= ~ata_print_options::FMT_BRIEF;
815 output_format_set = true;
816 }
817 else if (!strcmp(optarg, "brief")) {
818 ataopts.output_format |= ata_print_options::FMT_BRIEF;
819 output_format_set = true;
820 }
821 else if (!strcmp(optarg, "hex"))
822 ataopts.output_format |= ata_print_options::FMT_HEX_ID
823 | ata_print_options::FMT_HEX_VAL;
824 else if (!strcmp(optarg, "hex,id"))
825 ataopts.output_format |= ata_print_options::FMT_HEX_ID;
826 else if (!strcmp(optarg, "hex,val"))
827 ataopts.output_format |= ata_print_options::FMT_HEX_VAL;
828 else
829 badarg = true;
830 break;
831 case 'B':
832 {
833 const char * path = optarg;
834 if (*path == '+' && path[1])
835 path++;
836 else
837 use_default_db = false;
838 if (!read_drive_database(path))
839 EXIT(FAILCMD);
840 }
841 break;
842 case 'h':
843 printing_is_off = false;
844 printslogan();
845 Usage();
846 EXIT(0);
847 break;
848
849 case 'g':
850 case_s_continued: // -s, see above
851 case opt_set: // --set
852 {
853 ataopts.get_set_used = true;
854 bool get = (optchar == 'g');
855 char name[16+1]; unsigned val;
856 int n1 = -1, n2 = -1, n3 = -1, len = strlen(optarg);
857 if (sscanf(optarg, "%16[^,=]%n%*[,=]%n%u%n", name, &n1, &n2, &val, &n3) >= 1
858 && (n1 == len || (!get && n2 > 0))) {
859 bool on = (n2 > 0 && !strcmp(optarg+n2, "on"));
860 bool off = (n2 > 0 && !strcmp(optarg+n2, "off"));
861 if (n3 != len)
862 val = ~0U;
863
864 if (get && !strcmp(name, "all")) {
865 ataopts.get_aam = ataopts.get_apm = true;
866 ataopts.get_security = true;
867 ataopts.get_lookahead = ataopts.get_wcache = true;
868 scsiopts.get_rcd = scsiopts.get_wce = true;
869 }
870 else if (!strcmp(name, "aam")) {
871 if (get)
872 ataopts.get_aam = true;
873 else if (off)
874 ataopts.set_aam = -1;
875 else if (val <= 254)
876 ataopts.set_aam = val + 1;
877 else {
878 snprintf(extraerror, sizeof(extraerror), "Option -s aam,N must have 0 <= N <= 254\n");
879 badarg = true;
880 }
881 }
882 else if (!strcmp(name, "apm")) {
883 if (get)
884 ataopts.get_apm = true;
885 else if (off)
886 ataopts.set_apm = -1;
887 else if (1 <= val && val <= 254)
888 ataopts.set_apm = val + 1;
889 else {
890 snprintf(extraerror, sizeof(extraerror), "Option -s apm,N must have 1 <= N <= 254\n");
891 badarg = true;
892 }
893 }
894 else if (!strcmp(name, "lookahead")) {
895 if (get) {
896 ataopts.get_lookahead = true;
897 }
898 else if (off)
899 ataopts.set_lookahead = -1;
900 else if (on)
901 ataopts.set_lookahead = 1;
902 else
903 badarg = true;
904 }
905 else if (!strcmp(name, "wcreorder")) {
906 if (get) {
907 ataopts.sct_wcache_reorder_get = true;
908 }
909 else if (off)
910 ataopts.sct_wcache_reorder_set = -1;
911 else if (on)
912 ataopts.sct_wcache_reorder_set = 1;
913 else
914 badarg = true;
915 }
916 else if (!strcmp(name, "rcache")) {
917 if (get)
918 scsiopts.get_rcd = true;
919 else if (off)
920 scsiopts.set_rcd = -1;
921 else if (on)
922 scsiopts.set_rcd = 1;
923 else
924 badarg = true;
925 }
926 else if (get && !strcmp(name, "security")) {
927 ataopts.get_security = true;
928 }
929 else if (!get && !strcmp(optarg, "security-freeze")) {
930 ataopts.set_security_freeze = true;
931 }
932 else if (!get && !strcmp(optarg, "standby,now")) {
933 ataopts.set_standby_now = true;
934 }
935 else if (!get && !strcmp(name, "standby")) {
936 if (off)
937 ataopts.set_standby = 0 + 1;
938 else if (val <= 255)
939 ataopts.set_standby = val + 1;
940 else {
941 snprintf(extraerror, sizeof(extraerror), "Option -s standby,N must have 0 <= N <= 255\n");
942 badarg = true;
943 }
944 }
945 else if (!strcmp(name, "wcache")) {
946 if (get) {
947 ataopts.get_wcache = true;
948 scsiopts.get_wce = true;
949 }
950 else if (off) {
951 ataopts.set_wcache = -1;
952 scsiopts.set_wce = -1;
953 }
954 else if (on) {
955 ataopts.set_wcache = 1;
956 scsiopts.set_wce = 1;
957 }
958 else
959 badarg = true;
960 }
961 else
962 badarg = true;
963 }
964 else
965 badarg = true;
966 }
967 break;
968
969 case opt_scan:
970 case opt_scan_open:
971 scan = optchar;
972 break;
973
974 case '?':
975 default:
976 printing_is_off = false;
977 printslogan();
978 // Point arg to the argument in which this option was found.
979 arg = argv[optind-1];
980 // Check whether the option is a long option that doesn't map to -h.
981 if (arg[1] == '-' && optchar != 'h') {
982 // Iff optopt holds a valid option then argument must be missing.
983 if (optopt && (optopt >= opt_scan || strchr(shortopts, optopt))) {
984 pout("=======> ARGUMENT REQUIRED FOR OPTION: %s\n", arg+2);
985 printvalidarglistmessage(optopt);
986 } else
987 pout("=======> UNRECOGNIZED OPTION: %s\n",arg+2);
988 if (extraerror[0])
989 pout("=======> %s", extraerror);
990 UsageSummary();
991 EXIT(FAILCMD);
992 }
993 if (0 < optopt && optopt < '~') {
994 // Iff optopt holds a valid option then argument must be
995 // missing. Note (BA) this logic seems to fail using Solaris
996 // getopt!
997 if (strchr(shortopts, optopt) != NULL) {
998 pout("=======> ARGUMENT REQUIRED FOR OPTION: %c\n", optopt);
999 printvalidarglistmessage(optopt);
1000 } else
1001 pout("=======> UNRECOGNIZED OPTION: %c\n",optopt);
1002 if (extraerror[0])
1003 pout("=======> %s", extraerror);
1004 UsageSummary();
1005 EXIT(FAILCMD);
1006 }
1007 Usage();
1008 EXIT(0);
1009 } // closes switch statement to process command-line options
1010
1011 // Check to see if option had an unrecognized or incorrect argument.
1012 if (badarg) {
1013 printslogan();
1014 // It would be nice to print the actual option name given by the user
1015 // here, but we just print the short form. Please fix this if you know
1016 // a clean way to do it.
1017 char optstr[] = { (char)optchar, 0 };
1018 pout("=======> INVALID ARGUMENT TO -%s: %s\n",
1019 (optchar == opt_identify ? "-identify" :
1020 optchar == opt_set ? "-set" :
1021 optchar == opt_smart ? "-smart" : optstr), optarg);
1022 printvalidarglistmessage(optchar);
1023 if (extraerror[0])
1024 pout("=======> %s", extraerror);
1025 UsageSummary();
1026 EXIT(FAILCMD);
1027 }
1028 }
1029
1030 // Special handling of --scan, --scanopen
1031 if (scan) {
1032 // Read or init drive database to allow USB ID check.
1033 if (!init_drive_database(use_default_db))
1034 EXIT(FAILCMD);
1035 scan_devices(scan_types, (scan == opt_scan_open), argv + optind);
1036 EXIT(0);
1037 }
1038
1039 // At this point we have processed all command-line options. If the
1040 // print output is switchable, then start with the print output
1041 // turned off
1042 if (printing_is_switchable)
1043 printing_is_off = true;
1044
1045 // Check for multiple -d TYPE options
1046 if (scan_types.size() > 1) {
1047 printing_is_off = false;
1048 printslogan();
1049 pout("ERROR: multiple -d TYPE options are only allowed with --scan\n");
1050 UsageSummary();
1051 EXIT(FAILCMD);
1052 }
1053
1054 // error message if user has asked for more than one test
1055 if (testcnt > 1) {
1056 printing_is_off = false;
1057 printslogan();
1058 pout("\nERROR: smartctl can only run a single test type (or abort) at a time.\n");
1059 UsageSummary();
1060 EXIT(FAILCMD);
1061 }
1062
1063 // error message if user has set selective self-test options without
1064 // asking for a selective self-test
1065 if ( (ataopts.smart_selective_args.pending_time || ataopts.smart_selective_args.scan_after_select)
1066 && !ataopts.smart_selective_args.num_spans) {
1067 printing_is_off = false;
1068 printslogan();
1069 if (ataopts.smart_selective_args.pending_time)
1070 pout("\nERROR: smartctl -t pending,N must be used with -t select,N-M.\n");
1071 else
1072 pout("\nERROR: smartctl -t afterselect,(on|off) must be used with -t select,N-M.\n");
1073 UsageSummary();
1074 EXIT(FAILCMD);
1075 }
1076
1077 // If captive option was used, change test type if appropriate.
1078 if (captive)
1079 switch (ataopts.smart_selftest_type) {
1080 case SHORT_SELF_TEST:
1081 ataopts.smart_selftest_type = SHORT_CAPTIVE_SELF_TEST;
1082 scsiopts.smart_short_selftest = false;
1083 scsiopts.smart_short_cap_selftest = true;
1084 break;
1085 case EXTEND_SELF_TEST:
1086 ataopts.smart_selftest_type = EXTEND_CAPTIVE_SELF_TEST;
1087 scsiopts.smart_extend_selftest = false;
1088 scsiopts.smart_extend_cap_selftest = true;
1089 break;
1090 case CONVEYANCE_SELF_TEST:
1091 ataopts.smart_selftest_type = CONVEYANCE_CAPTIVE_SELF_TEST;
1092 break;
1093 case SELECTIVE_SELF_TEST:
1094 ataopts.smart_selftest_type = SELECTIVE_CAPTIVE_SELF_TEST;
1095 break;
1096 }
1097
1098 // From here on, normal operations...
1099 printslogan();
1100
1101 // Warn if the user has provided no device name
1102 if (argc-optind<1){
1103 pout("ERROR: smartctl requires a device name as the final command-line argument.\n\n");
1104 UsageSummary();
1105 EXIT(FAILCMD);
1106 }
1107
1108 // Warn if the user has provided more than one device name
1109 if (argc-optind>1){
1110 int i;
1111 pout("ERROR: smartctl takes ONE device name as the final command-line argument.\n");
1112 pout("You have provided %d device names:\n",argc-optind);
1113 for (i=0; i<argc-optind; i++)
1114 pout("%s\n",argv[optind+i]);
1115 UsageSummary();
1116 EXIT(FAILCMD);
1117 }
1118
1119 // Read or init drive database
1120 if (!init_drive_database(use_default_db))
1121 EXIT(FAILCMD);
1122
1123 return type;
1124 }
1125
1126 // Printing function (controlled by global printing_is_off)
1127 // [From GLIBC Manual: Since the prototype doesn't specify types for
1128 // optional arguments, in a call to a variadic function the default
1129 // argument promotions are performed on the optional argument
1130 // values. This means the objects of type char or short int (whether
1131 // signed or not) are promoted to either int or unsigned int, as
1132 // appropriate.]
1133 void pout(const char *fmt, ...){
1134 va_list ap;
1135
1136 // initialize variable argument list
1137 va_start(ap,fmt);
1138 if (printing_is_off) {
1139 va_end(ap);
1140 return;
1141 }
1142
1143 // print out
1144 vprintf(fmt,ap);
1145 va_end(ap);
1146 fflush(stdout);
1147 return;
1148 }
1149
1150 // Globals to set failuretest() policy
1151 bool failuretest_conservative = false;
1152 unsigned char failuretest_permissive = 0;
1153
1154 // Compares failure type to policy in effect, and either exits or
1155 // simply returns to the calling routine.
1156 // Used in ataprint.cpp and scsiprint.cpp.
1157 void failuretest(failure_type type, int returnvalue)
1158 {
1159 // If this is an error in an "optional" SMART command
1160 if (type == OPTIONAL_CMD) {
1161 if (!failuretest_conservative)
1162 return;
1163 pout("An optional SMART command failed: exiting. Remove '-T conservative' option to continue.\n");
1164 EXIT(returnvalue);
1165 }
1166
1167 // If this is an error in a "mandatory" SMART command
1168 if (type == MANDATORY_CMD) {
1169 if (failuretest_permissive--)
1170 return;
1171 pout("A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.\n");
1172 EXIT(returnvalue);
1173 }
1174
1175 throw std::logic_error("failuretest: Unknown type");
1176 }
1177
1178 // Used to warn users about invalid checksums. Called from atacmds.cpp.
1179 // Action to be taken may be altered by the user.
1180 void checksumwarning(const char * string)
1181 {
1182 // user has asked us to ignore checksum errors
1183 if (checksum_err_mode == CHECKSUM_ERR_IGNORE)
1184 return;
1185
1186 pout("Warning! %s error: invalid SMART checksum.\n", string);
1187
1188 // user has asked us to fail on checksum errors
1189 if (checksum_err_mode == CHECKSUM_ERR_EXIT)
1190 EXIT(FAILSMART);
1191 }
1192
1193 // Return info string about device protocol
1194 static const char * get_protocol_info(const smart_device * dev)
1195 {
1196 switch ( (int)dev->is_ata()
1197 | ((int)dev->is_scsi() << 1)
1198 | ((int)dev->is_nvme() << 2)) {
1199 case 0x1: return "ATA";
1200 case 0x2: return "SCSI";
1201 case 0x3: return "ATA+SCSI";
1202 case 0x4: return "NVMe";
1203 default: return "Unknown";
1204 }
1205 }
1206
1207 // Device scan
1208 // smartctl [-d type] --scan[-open] -- [PATTERN] [smartd directive ...]
1209 void scan_devices(const smart_devtype_list & types, bool with_open, char ** argv)
1210 {
1211 bool dont_print = !(ata_debugmode || scsi_debugmode || nvme_debugmode);
1212
1213 const char * pattern = 0;
1214 int ai = 0;
1215 if (argv[ai] && argv[ai][0] != '-')
1216 pattern = argv[ai++];
1217
1218 smart_device_list devlist;
1219 printing_is_off = dont_print;
1220 bool ok = smi()->scan_smart_devices(devlist, types, pattern);
1221 printing_is_off = false;
1222
1223 if (!ok) {
1224 pout("# scan_smart_devices: %s\n", smi()->get_errmsg());
1225 return;
1226 }
1227
1228 for (unsigned i = 0; i < devlist.size(); i++) {
1229 smart_device_auto_ptr dev( devlist.release(i) );
1230
1231 if (with_open) {
1232 printing_is_off = dont_print;
1233 dev.replace ( dev->autodetect_open() );
1234 printing_is_off = false;
1235
1236 if (!dev->is_open()) {
1237 pout("# %s -d %s # %s, %s device open failed: %s\n", dev->get_dev_name(),
1238 dev->get_dev_type(), dev->get_info_name(),
1239 get_protocol_info(dev.get()), dev->get_errmsg());
1240 continue;
1241 }
1242 }
1243
1244 pout("%s -d %s", dev->get_dev_name(), dev->get_dev_type());
1245 if (!argv[ai])
1246 pout(" # %s, %s device\n", dev->get_info_name(), get_protocol_info(dev.get()));
1247 else {
1248 for (int j = ai; argv[j]; j++)
1249 pout(" %s", argv[j]);
1250 pout("\n");
1251 }
1252
1253 if (dev->is_open())
1254 dev->close();
1255 }
1256 }
1257
1258 // Main program without exception handling
1259 static int main_worker(int argc, char **argv)
1260 {
1261 // Throw if runtime environment does not match compile time test.
1262 check_config();
1263
1264 // Initialize interface
1265 smart_interface::init();
1266 if (!smi())
1267 return 1;
1268
1269 // Parse input arguments
1270 ata_print_options ataopts;
1271 scsi_print_options scsiopts;
1272 nvme_print_options nvmeopts;
1273 bool print_type_only = false;
1274 const char * type = parse_options(argc, argv, ataopts, scsiopts, nvmeopts, print_type_only);
1275
1276 const char * name = argv[argc-1];
1277
1278 smart_device_auto_ptr dev;
1279 if (!strcmp(name,"-")) {
1280 // Parse "smartctl -r ataioctl,2 ..." output from stdin
1281 if (type || print_type_only) {
1282 pout("-d option is not allowed in conjunction with device name \"-\".\n");
1283 UsageSummary();
1284 return FAILCMD;
1285 }
1286 dev = get_parsed_ata_device(smi(), name);
1287 }
1288 else
1289 // get device of appropriate type
1290 dev = smi()->get_smart_device(name, type);
1291
1292 if (!dev) {
1293 pout("%s: %s\n", name, smi()->get_errmsg());
1294 if (type)
1295 printvalidarglistmessage('d');
1296 else
1297 pout("Please specify device type with the -d option.\n");
1298 UsageSummary();
1299 return FAILCMD;
1300 }
1301
1302 if (print_type_only)
1303 // Report result of first autodetection
1304 pout("%s: Device of type '%s' [%s] detected\n",
1305 dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
1306
1307 if (dev->is_ata() && ataopts.powermode>=2 && dev->is_powered_down()) {
1308 pout( "%s: Device is in %s mode, exit(%d)\n", dev->get_info_name(), "STANDBY (OS)", FAILPOWER );
1309 return FAILPOWER;
1310 }
1311
1312 // Open device
1313 {
1314 // Save old info
1315 smart_device::device_info oldinfo = dev->get_info();
1316
1317 // Open with autodetect support, may return 'better' device
1318 dev.replace( dev->autodetect_open() );
1319
1320 // Report if type has changed
1321 if ( (ata_debugmode || scsi_debugmode || nvme_debugmode || print_type_only)
1322 && oldinfo.dev_type != dev->get_dev_type() )
1323 pout("%s: Device open changed type from '%s' to '%s'\n",
1324 dev->get_info_name(), oldinfo.dev_type.c_str(), dev->get_dev_type());
1325 }
1326 if (!dev->is_open()) {
1327 pout("Smartctl open device: %s failed: %s\n", dev->get_info_name(), dev->get_errmsg());
1328 return FAILDEV;
1329 }
1330
1331 // now call appropriate ATA or SCSI routine
1332 int retval = 0;
1333 if (print_type_only)
1334 pout("%s: Device of type '%s' [%s] opened\n",
1335 dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
1336 else if (dev->is_ata())
1337 retval = ataPrintMain(dev->to_ata(), ataopts);
1338 else if (dev->is_scsi())
1339 retval = scsiPrintMain(dev->to_scsi(), scsiopts);
1340 else if (dev->is_nvme())
1341 retval = nvmePrintMain(dev->to_nvme(), nvmeopts);
1342 else
1343 // we should never fall into this branch!
1344 pout("%s: Neither ATA, SCSI nor NVMe device\n", dev->get_info_name());
1345
1346 dev->close();
1347 return retval;
1348 }
1349
1350
1351 // Main program
1352 int main(int argc, char **argv)
1353 {
1354 int status;
1355 bool badcode = false;
1356
1357 try {
1358 // Do the real work ...
1359 status = main_worker(argc, argv);
1360 }
1361 catch (int ex) {
1362 // EXIT(status) arrives here
1363 status = ex;
1364 }
1365 catch (const std::bad_alloc & /*ex*/) {
1366 // Memory allocation failed (also thrown by std::operator new)
1367 printf("Smartctl: Out of memory\n");
1368 status = FAILCMD;
1369 }
1370 catch (const std::exception & ex) {
1371 // Other fatal errors
1372 printf("Smartctl: Exception: %s\n", ex.what());
1373 badcode = true;
1374 status = FAILCMD;
1375 }
1376
1377 // Check for remaining device objects
1378 if (smart_device::get_num_objects() != 0) {
1379 printf("Smartctl: Internal Error: %d device object(s) left at exit.\n",
1380 smart_device::get_num_objects());
1381 badcode = true;
1382 status = FAILCMD;
1383 }
1384
1385 if (badcode)
1386 printf("Please inform " PACKAGE_BUGREPORT ", including output of smartctl -V.\n");
1387
1388 return status;
1389 }
1390