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