Ticket #877: smartctl.cpp

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