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