]> git.proxmox.com Git - mirror_smartmontools-debian.git/blob - smartctl.cpp
Imported Upstream version 5.40+svn3296
[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-11 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, write to the Free
17 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 *
19 * This code was originally developed as a Senior Thesis by Michael Cornwell
20 * at the Concurrent Systems Laboratory (now part of the Storage Systems
21 * Research Center), Jack Baskin School of Engineering, University of
22 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
23 *
24 */
25
26 #include <errno.h>
27 #include <stdio.h>
28 #include <sys/types.h>
29 #include <string.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 #if defined(__QNXNTO__)
45 #include <new> // TODO: Why is this include necessary on QNX ?
46 #endif
47
48 #include "int64.h"
49 #include "atacmds.h"
50 #include "dev_interface.h"
51 #include "ataprint.h"
52 #include "knowndrives.h"
53 #include "scsicmds.h"
54 #include "scsiprint.h"
55 #include "smartctl.h"
56 #include "utility.h"
57
58 const char * smartctl_cpp_cvsid = "$Id: smartctl.cpp 3283 2011-03-04 20:13:57Z chrfranke $"
59 CONFIG_H_CVSID SMARTCTL_H_CVSID;
60
61 // Globals to control printing
62 bool printing_is_switchable = false;
63 bool printing_is_off = false;
64
65 static void printslogan()
66 {
67 pout("%s\n", format_version_info("smartctl").c_str());
68 }
69
70 static void UsageSummary()
71 {
72 pout("\nUse smartctl -h to get a usage summary\n\n");
73 return;
74 }
75
76 static std::string getvalidarglist(char opt);
77
78 /* void prints help information for command syntax */
79 static 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 " -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 );
123 printf(
124 "======================================= READ AND DISPLAY DATA OPTIONS =====\n\n"
125 " -H, --health\n"
126 " Show device SMART health status\n\n"
127 " -c, --capabilities (ATA)\n"
128 " Show device SMART capabilities\n\n"
129 " -A, --attributes \n"
130 " Show device SMART vendor-specific Attributes and values\n\n"
131 " -l TYPE, --log=TYPE\n"
132 " Show device log. TYPE: error, selftest, selective, directory[,g|s],\n"
133 " background, sasphy[,reset], sataphy[,reset],\n"
134 " scttemp[sts,hist], scterc[,N,M],\n"
135 " gplog,N[,RANGE], smartlog,N[,RANGE],\n"
136 " xerror[,N][,error], xselftest[,N][,selftest]\n\n"
137 " -v N,OPTION , --vendorattribute=N,OPTION (ATA)\n"
138 " Set display OPTION for vendor Attribute N (see man page)\n\n"
139 " -F TYPE, --firmwarebug=TYPE (ATA)\n"
140 " Use firmware bug workaround: none, samsung, samsung2,\n"
141 " samsung3, swapid\n\n"
142 " -P TYPE, --presets=TYPE (ATA)\n"
143 " Drive-specific presets: use, ignore, show, showall\n\n"
144 " -B [+]FILE, --drivedb=[+]FILE (ATA)\n"
145 " Read and replace [add] drive database from FILE\n"
146 " [default is +%s",
147 get_drivedb_path_add()
148 );
149 #ifdef SMARTMONTOOLS_DRIVEDBDIR
150 printf(
151 "\n"
152 " and then %s",
153 get_drivedb_path_default()
154 );
155 #endif
156 printf(
157 "]\n\n"
158 "============================================ DEVICE SELF-TEST OPTIONS =====\n\n"
159 " -t TEST, --test=TEST\n"
160 " Run test. TEST: offline short long conveyance vendor,N select,M-N\n"
161 " pending,N afterselect,[on|off] scttempint,N[,p]\n\n"
162 " -C, --captive\n"
163 " Do test in captive mode (along with -t)\n\n"
164 " -X, --abort\n"
165 " Abort any non-captive test on device\n\n"
166 );
167 std::string examples = smi()->get_app_examples("smartctl");
168 if (!examples.empty())
169 printf("%s\n", examples.c_str());
170 }
171
172 /* Returns a string containing a formatted list of the valid arguments
173 to the option opt or empty on failure. Note 'v' case different */
174 static std::string getvalidarglist(char opt)
175 {
176 switch (opt) {
177 case 'q':
178 return "errorsonly, silent, noserial";
179 case 'd':
180 return smi()->get_valid_dev_types_str() + ", auto, test";
181 case 'T':
182 return "normal, conservative, permissive, verypermissive";
183 case 'b':
184 return "warn, exit, ignore";
185 case 'r':
186 return "ioctl[,N], ataioctl[,N], scsiioctl[,N]";
187 case 's':
188 case 'o':
189 case 'S':
190 return "on, off";
191 case 'l':
192 return "error, selftest, selective, directory[,g|s], background, scttemp[sts|hist], scterc[,N,M], "
193 "sasphy[,reset], sataphy[,reset], gplog,N[,RANGE], smartlog,N[,RANGE], "
194 "xerror[,N][,error], xselftest[,N][,selftest]";
195 case 'P':
196 return "use, ignore, show, showall";
197 case 't':
198 return "offline, short, long, conveyance, vendor,N, select,M-N, "
199 "pending,N, afterselect,[on|off], scttempint,N[,p]";
200 case 'F':
201 return "none, samsung, samsung2, samsung3, swapid";
202 case 'n':
203 return "never, sleep, standby, idle";
204 case 'v':
205 default:
206 return "";
207 }
208 }
209
210 /* Prints the message "=======> VALID ARGUMENTS ARE: <LIST> \n", where
211 <LIST> is the list of valid arguments for option opt. */
212 static void printvalidarglistmessage(char opt)
213 {
214 if (opt=='v'){
215 pout("=======> VALID ARGUMENTS ARE:\n\thelp\n%s\n<=======\n",
216 create_vendor_attribute_arg_list().c_str());
217 }
218 else {
219 // getvalidarglist() might produce a multiline or single line string. We
220 // need to figure out which to get the formatting right.
221 std::string s = getvalidarglist(opt);
222 char separator = strchr(s.c_str(), '\n') ? '\n' : ' ';
223 pout("=======> VALID ARGUMENTS ARE:%c%s%c<=======\n", separator, s.c_str(), separator);
224 }
225
226 return;
227 }
228
229 // Checksum error mode
230 enum checksum_err_mode_t {
231 CHECKSUM_ERR_WARN, CHECKSUM_ERR_EXIT, CHECKSUM_ERR_IGNORE
232 };
233
234 static checksum_err_mode_t checksum_err_mode = CHECKSUM_ERR_WARN;
235
236 static void scan_devices(const char * type, bool with_open, char ** argv);
237
238 /* Takes command options and sets features to be run */
239 static const char * parse_options(int argc, char** argv,
240 ata_print_options & ataopts,
241 scsi_print_options & scsiopts)
242 {
243 // Please update getvalidarglist() if you edit shortopts
244 const char *shortopts = "h?Vq:d:T:b:r:s:o:S:HcAl:iaxv:P:t:CXF:n:B:";
245 // Please update getvalidarglist() if you edit longopts
246 enum { opt_scan = 1000, opt_scan_open = 1001 };
247 struct option longopts[] = {
248 { "help", no_argument, 0, 'h' },
249 { "usage", no_argument, 0, 'h' },
250 { "version", no_argument, 0, 'V' },
251 { "copyright", no_argument, 0, 'V' },
252 { "license", no_argument, 0, 'V' },
253 { "quietmode", required_argument, 0, 'q' },
254 { "device", required_argument, 0, 'd' },
255 { "tolerance", required_argument, 0, 'T' },
256 { "badsum", required_argument, 0, 'b' },
257 { "report", required_argument, 0, 'r' },
258 { "smart", required_argument, 0, 's' },
259 { "offlineauto", required_argument, 0, 'o' },
260 { "saveauto", required_argument, 0, 'S' },
261 { "health", no_argument, 0, 'H' },
262 { "capabilities", no_argument, 0, 'c' },
263 { "attributes", no_argument, 0, 'A' },
264 { "log", required_argument, 0, 'l' },
265 { "info", no_argument, 0, 'i' },
266 { "all", no_argument, 0, 'a' },
267 { "xall", no_argument, 0, 'x' },
268 { "vendorattribute", required_argument, 0, 'v' },
269 { "presets", required_argument, 0, 'P' },
270 { "test", required_argument, 0, 't' },
271 { "captive", no_argument, 0, 'C' },
272 { "abort", no_argument, 0, 'X' },
273 { "firmwarebug", required_argument, 0, 'F' },
274 { "nocheck", required_argument, 0, 'n' },
275 { "drivedb", required_argument, 0, 'B' },
276 { "scan", no_argument, 0, opt_scan },
277 { "scan-open", no_argument, 0, opt_scan_open },
278 { 0, 0, 0, 0 }
279 };
280
281 char extraerror[256];
282 memset(extraerror, 0, sizeof(extraerror));
283 opterr=optopt=0;
284
285 const char * type = 0; // set to -d optarg
286 bool no_defaultdb = false; // set true on '-B FILE'
287 int scan = 0; // set by --scan, --scan-open
288 bool badarg = false, captive = false;
289 int testcnt = 0; // number of self-tests requested
290
291 int optchar;
292 char *arg;
293
294 while ((optchar = getopt_long(argc, argv, shortopts, longopts, 0)) != -1) {
295 switch (optchar){
296 case 'V':
297 printing_is_off = false;
298 pout("%s", format_version_info("smartctl", true /*full*/).c_str());
299 EXIT(0);
300 break;
301 case 'q':
302 if (!strcmp(optarg,"errorsonly")) {
303 printing_is_switchable = true;
304 printing_is_off = false;
305 } else if (!strcmp(optarg,"silent")) {
306 printing_is_switchable = false;
307 printing_is_off = true;
308 } else if (!strcmp(optarg,"noserial")) {
309 dont_print_serial_number = true;
310 } else {
311 badarg = true;
312 }
313 break;
314 case 'd':
315 type = (strcmp(optarg, "auto") ? optarg : (char *)0);
316 break;
317 case 'T':
318 if (!strcmp(optarg,"normal")) {
319 failuretest_conservative = false;
320 failuretest_permissive = 0;
321 } else if (!strcmp(optarg,"conservative")) {
322 failuretest_conservative = true;
323 } else if (!strcmp(optarg,"permissive")) {
324 if (failuretest_permissive < 0xff)
325 failuretest_permissive++;
326 } else if (!strcmp(optarg,"verypermissive")) {
327 failuretest_permissive = 0xff;
328 } else {
329 badarg = true;
330 }
331 break;
332 case 'b':
333 if (!strcmp(optarg,"warn")) {
334 checksum_err_mode = CHECKSUM_ERR_WARN;
335 } else if (!strcmp(optarg,"exit")) {
336 checksum_err_mode = CHECKSUM_ERR_EXIT;
337 } else if (!strcmp(optarg,"ignore")) {
338 checksum_err_mode = CHECKSUM_ERR_IGNORE;
339 } else {
340 badarg = true;
341 }
342 break;
343 case 'r':
344 {
345 int i;
346 char *s;
347
348 // split_report_arg() may modify its first argument string, so use a
349 // copy of optarg in case we want optarg for an error message.
350 if (!(s = strdup(optarg))) {
351 throw std::bad_alloc();
352 }
353 if (split_report_arg(s, &i)) {
354 badarg = true;
355 } else if (!strcmp(s,"ioctl")) {
356 ata_debugmode = scsi_debugmode = i;
357 } else if (!strcmp(s,"ataioctl")) {
358 ata_debugmode = i;
359 } else if (!strcmp(s,"scsiioctl")) {
360 scsi_debugmode = i;
361 } else {
362 badarg = true;
363 }
364 free(s);
365 }
366 break;
367 case 's':
368 if (!strcmp(optarg,"on")) {
369 ataopts.smart_enable = scsiopts.smart_enable = true;
370 ataopts.smart_disable = scsiopts.smart_disable = false;
371 } else if (!strcmp(optarg,"off")) {
372 ataopts.smart_disable = scsiopts.smart_disable = true;
373 ataopts.smart_enable = scsiopts.smart_enable = false;
374 } else {
375 badarg = true;
376 }
377 break;
378 case 'o':
379 if (!strcmp(optarg,"on")) {
380 ataopts.smart_auto_offl_enable = true;
381 ataopts.smart_auto_offl_disable = false;
382 } else if (!strcmp(optarg,"off")) {
383 ataopts.smart_auto_offl_disable = true;
384 ataopts.smart_auto_offl_enable = false;
385 } else {
386 badarg = true;
387 }
388 break;
389 case 'S':
390 if (!strcmp(optarg,"on")) {
391 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = true;
392 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = false;
393 } else if (!strcmp(optarg,"off")) {
394 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = true;
395 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = false;
396 } else {
397 badarg = true;
398 }
399 break;
400 case 'H':
401 ataopts.smart_check_status = scsiopts.smart_check_status = true;
402 break;
403 case 'F':
404 if (!strcmp(optarg,"none")) {
405 ataopts.fix_firmwarebug = FIX_NONE;
406 } else if (!strcmp(optarg,"samsung")) {
407 ataopts.fix_firmwarebug = FIX_SAMSUNG;
408 } else if (!strcmp(optarg,"samsung2")) {
409 ataopts.fix_firmwarebug = FIX_SAMSUNG2;
410 } else if (!strcmp(optarg,"samsung3")) {
411 ataopts.fix_firmwarebug = FIX_SAMSUNG3;
412 } else if (!strcmp(optarg,"swapid")) {
413 ataopts.fix_swapped_id = true;
414 } else {
415 badarg = true;
416 }
417 break;
418 case 'c':
419 ataopts.smart_general_values = true;
420 break;
421 case 'A':
422 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = true;
423 break;
424 case 'l':
425 if (!strcmp(optarg,"error")) {
426 ataopts.smart_error_log = scsiopts.smart_error_log = true;
427 } else if (!strcmp(optarg,"selftest")) {
428 ataopts.smart_selftest_log = scsiopts.smart_selftest_log = true;
429 } else if (!strcmp(optarg, "selective")) {
430 ataopts.smart_selective_selftest_log = true;
431 } else if (!strcmp(optarg,"directory")) {
432 ataopts.smart_logdir = ataopts.gp_logdir = true; // SMART+GPL
433 } else if (!strcmp(optarg,"directory,s")) {
434 ataopts.smart_logdir = true; // SMART
435 } else if (!strcmp(optarg,"directory,g")) {
436 ataopts.gp_logdir = true; // GPL
437 } else if (!strcmp(optarg,"sasphy")) {
438 scsiopts.sasphy = true;
439 } else if (!strcmp(optarg,"sasphy,reset")) {
440 scsiopts.sasphy = scsiopts.sasphy_reset = true;
441 } else if (!strcmp(optarg,"sataphy")) {
442 ataopts.sataphy = true;
443 } else if (!strcmp(optarg,"sataphy,reset")) {
444 ataopts.sataphy = ataopts.sataphy_reset = true;
445 } else if (!strcmp(optarg,"background")) {
446 scsiopts.smart_background_log = true;
447 } else if (!strcmp(optarg,"scterc")) {
448 ataopts.sct_erc_get = true;
449 } else if (!strcmp(optarg,"scttemp")) {
450 ataopts.sct_temp_sts = ataopts.sct_temp_hist = true;
451 } else if (!strcmp(optarg,"scttempsts")) {
452 ataopts.sct_temp_sts = true;
453 } else if (!strcmp(optarg,"scttemphist")) {
454 ataopts.sct_temp_hist = true;
455
456 } else if (!strncmp(optarg, "xerror", sizeof("xerror")-1)) {
457 int n1 = -1, n2 = -1, len = strlen(optarg);
458 unsigned val = 8;
459 sscanf(optarg, "xerror%n,error%n", &n1, &n2);
460 if (!(n1 == len || n2 == len)) {
461 n1 = n2 = -1;
462 sscanf(optarg, "xerror,%u%n,error%n", &val, &n1, &n2);
463 }
464 if ((n1 == len || n2 == len) && val > 0) {
465 ataopts.smart_ext_error_log = val;
466 ataopts.retry_error_log = (n2 == len);
467 }
468 else
469 badarg = true;
470
471 } else if (!strncmp(optarg, "xselftest", sizeof("xselftest")-1)) {
472 int n1 = -1, n2 = -1, len = strlen(optarg);
473 unsigned val = 25;
474 sscanf(optarg, "xselftest%n,selftest%n", &n1, &n2);
475 if (!(n1 == len || n2 == len)) {
476 n1 = n2 = -1;
477 sscanf(optarg, "xselftest,%u%n,selftest%n", &val, &n1, &n2);
478 }
479 if ((n1 == len || n2 == len) && val > 0) {
480 ataopts.smart_ext_selftest_log = val;
481 ataopts.retry_selftest_log = (n2 == len);
482 }
483 else
484 badarg = true;
485
486 } else if (!strncmp(optarg, "scterc,", sizeof("scterc,")-1)) {
487 unsigned rt = ~0, wt = ~0; int n = -1;
488 sscanf(optarg,"scterc,%u,%u%n", &rt, &wt, &n);
489 if (n == (int)strlen(optarg) && rt <= 999 && wt <= 999) {
490 ataopts.sct_erc_set = true;
491 ataopts.sct_erc_readtime = rt;
492 ataopts.sct_erc_writetime = wt;
493 }
494 else {
495 sprintf(extraerror, "Option -l scterc,[READTIME,WRITETIME] syntax error\n");
496 badarg = true;
497 }
498 } else if ( !strncmp(optarg, "gplog," , sizeof("gplog," )-1)
499 || !strncmp(optarg, "smartlog,", sizeof("smartlog,")-1)) {
500 unsigned logaddr = ~0U; unsigned page = 0, nsectors = 1; char sign = 0;
501 int n1 = -1, n2 = -1, n3 = -1, len = strlen(optarg);
502 sscanf(optarg, "%*[a-z],0x%x%n,%u%n%c%u%n",
503 &logaddr, &n1, &page, &n2, &sign, &nsectors, &n3);
504 if (len > n2 && n3 == -1 && !strcmp(optarg+n2, "-max")) {
505 nsectors = ~0U; sign = '+'; n3 = len;
506 }
507 bool gpl = (optarg[0] == 'g');
508 const char * erropt = (gpl ? "gplog" : "smartlog");
509 if (!( n1 == len || n2 == len
510 || (n3 == len && (sign == '+' || sign == '-')))) {
511 sprintf(extraerror, "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] syntax error\n", erropt);
512 badarg = true;
513 }
514 else if (!( logaddr <= 0xff && page <= (gpl ? 0xffffU : 0x00ffU)
515 && 0 < nsectors
516 && (nsectors <= (gpl ? 0xffffU : 0xffU) || nsectors == ~0U)
517 && (sign != '-' || page <= nsectors) )) {
518 sprintf(extraerror, "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] parameter out of range\n", erropt);
519 badarg = true;
520 }
521 else {
522 ata_log_request req;
523 req.gpl = gpl; req.logaddr = logaddr; req.page = page;
524 req.nsectors = (sign == '-' ? nsectors-page+1 : nsectors);
525 ataopts.log_requests.push_back(req);
526 }
527 } else {
528 badarg = true;
529 }
530 break;
531 case 'i':
532 ataopts.drive_info = scsiopts.drive_info = true;
533 break;
534 case 'a':
535 ataopts.drive_info = scsiopts.drive_info = true;
536 ataopts.smart_check_status = scsiopts.smart_check_status = true;
537 ataopts.smart_general_values = true;
538 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = true;
539 ataopts.smart_error_log = scsiopts.smart_error_log = true;
540 ataopts.smart_selftest_log = scsiopts.smart_selftest_log = true;
541 ataopts.smart_selective_selftest_log = true;
542 /* scsiopts.smart_background_log = true; */
543 break;
544 case 'x':
545 ataopts.drive_info = scsiopts.drive_info = true;
546 ataopts.smart_check_status = scsiopts.smart_check_status = true;
547 ataopts.smart_general_values = true;
548 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = true;
549 ataopts.smart_ext_error_log = 8;
550 ataopts.retry_error_log = true;
551 ataopts.smart_ext_selftest_log = 25;
552 ataopts.retry_selftest_log = true;
553 scsiopts.smart_error_log = scsiopts.smart_selftest_log = true;
554 ataopts.smart_selective_selftest_log = true;
555 ataopts.smart_logdir = ataopts.gp_logdir = true;
556 ataopts.sct_temp_sts = ataopts.sct_temp_hist = true;
557 ataopts.sct_erc_get = true;
558 ataopts.sataphy = true;
559 scsiopts.smart_background_log = true;
560 scsiopts.sasphy = true;
561 break;
562 case 'v':
563 // parse vendor-specific definitions of attributes
564 if (!strcmp(optarg,"help")) {
565 printing_is_off = false;
566 printslogan();
567 pout("The valid arguments to -v are:\n\thelp\n%s\n",
568 create_vendor_attribute_arg_list().c_str());
569 EXIT(0);
570 }
571 if (!parse_attribute_def(optarg, ataopts.attribute_defs, PRIOR_USER))
572 badarg = true;
573 break;
574 case 'P':
575 if (!strcmp(optarg, "use")) {
576 ataopts.ignore_presets = false;
577 } else if (!strcmp(optarg, "ignore")) {
578 ataopts.ignore_presets = true;
579 } else if (!strcmp(optarg, "show")) {
580 ataopts.show_presets = true;
581 } else if (!strcmp(optarg, "showall")) {
582 if (!no_defaultdb && !read_default_drive_databases())
583 EXIT(FAILCMD);
584 if (optind < argc) { // -P showall MODEL [FIRMWARE]
585 int cnt = showmatchingpresets(argv[optind], (optind+1<argc ? argv[optind+1] : NULL));
586 EXIT(cnt); // report #matches
587 }
588 if (showallpresets())
589 EXIT(FAILCMD); // report regexp syntax error
590 EXIT(0);
591 } else {
592 badarg = true;
593 }
594 break;
595 case 't':
596 if (!strcmp(optarg,"offline")) {
597 testcnt++;
598 ataopts.smart_selftest_type = OFFLINE_FULL_SCAN;
599 scsiopts.smart_default_selftest = true;
600 } else if (!strcmp(optarg,"short")) {
601 testcnt++;
602 ataopts.smart_selftest_type = SHORT_SELF_TEST;
603 scsiopts.smart_short_selftest = true;
604 } else if (!strcmp(optarg,"long")) {
605 testcnt++;
606 ataopts.smart_selftest_type = EXTEND_SELF_TEST;
607 scsiopts.smart_extend_selftest = true;
608 } else if (!strcmp(optarg,"conveyance")) {
609 testcnt++;
610 ataopts.smart_selftest_type = CONVEYANCE_SELF_TEST;
611 } else if (!strcmp(optarg,"afterselect,on")) {
612 // scan remainder of disk after doing selected segment
613 ataopts.smart_selective_args.scan_after_select = 2;
614 } else if (!strcmp(optarg,"afterselect,off")) {
615 // don't scan remainder of disk after doing selected segments
616 ataopts.smart_selective_args.scan_after_select = 1;
617 } else if (!strncmp(optarg,"pending,",strlen("pending,"))) {
618 // parse number of minutes that test should be pending
619 int i;
620 char *tailptr=NULL;
621 errno=0;
622 i=(int)strtol(optarg+strlen("pending,"), &tailptr, 10);
623 if (errno || *tailptr != '\0') {
624 sprintf(extraerror, "Option -t pending,N requires N to be a non-negative integer\n");
625 badarg = true;
626 } else if (i<0 || i>65535) {
627 sprintf(extraerror, "Option -t pending,N (N=%d) must have 0 <= N <= 65535\n", i);
628 badarg = true;
629 } else {
630 ataopts.smart_selective_args.pending_time = i+1;
631 }
632 } else if (!strncmp(optarg,"select",strlen("select"))) {
633 if (ataopts.smart_selective_args.num_spans == 0)
634 testcnt++;
635 // parse range of LBAs to test
636 uint64_t start, stop; int mode;
637 if (split_selective_arg(optarg, &start, &stop, &mode)) {
638 sprintf(extraerror, "Option -t select,M-N must have non-negative integer M and N\n");
639 badarg = true;
640 } else {
641 if (ataopts.smart_selective_args.num_spans >= 5 || start > stop) {
642 if (start > stop) {
643 sprintf(extraerror, "ERROR: Start LBA (%"PRIu64") > ending LBA (%"PRId64") in argument \"%s\"\n",
644 start, stop, optarg);
645 } else {
646 sprintf(extraerror,"ERROR: No more than five selective self-test spans may be"
647 " defined\n");
648 }
649 badarg = true;
650 }
651 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].start = start;
652 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].end = stop;
653 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].mode = mode;
654 ataopts.smart_selective_args.num_spans++;
655 ataopts.smart_selftest_type = SELECTIVE_SELF_TEST;
656 }
657 } else if (!strncmp(optarg, "scttempint,", sizeof("scstempint,")-1)) {
658 unsigned interval = 0; int n1 = -1, n2 = -1, len = strlen(optarg);
659 if (!( sscanf(optarg,"scttempint,%u%n,p%n", &interval, &n1, &n2) == 1
660 && 0 < interval && interval <= 0xffff && (n1 == len || n2 == len))) {
661 strcpy(extraerror, "Option -t scttempint,N[,p] must have positive integer N\n");
662 badarg = true;
663 }
664 ataopts.sct_temp_int = interval;
665 ataopts.sct_temp_int_pers = (n2 == len);
666 } else if (!strncmp(optarg, "vendor,", sizeof("vendor,")-1)) {
667 unsigned subcmd = ~0U; int n = -1;
668 if (!( sscanf(optarg, "%*[a-z],0x%x%n", &subcmd, &n) == 1
669 && subcmd <= 0xff && n == (int)strlen(optarg))) {
670 strcpy(extraerror, "Option -t vendor,0xNN syntax error\n");
671 badarg = true;
672 }
673 else
674 ataopts.smart_selftest_type = subcmd;
675 } else {
676 badarg = true;
677 }
678 break;
679 case 'C':
680 captive = true;
681 break;
682 case 'X':
683 testcnt++;
684 scsiopts.smart_selftest_abort = true;
685 ataopts.smart_selftest_type = ABORT_SELF_TEST;
686 break;
687 case 'n':
688 // skip disk check if in low-power mode
689 if (!strcmp(optarg, "never"))
690 ataopts.powermode = 1; // do not skip, but print mode
691 else if (!strcmp(optarg, "sleep"))
692 ataopts.powermode = 2;
693 else if (!strcmp(optarg, "standby"))
694 ataopts.powermode = 3;
695 else if (!strcmp(optarg, "idle"))
696 ataopts.powermode = 4;
697 else
698 badarg = true;
699 break;
700 case 'B':
701 {
702 const char * path = optarg;
703 if (*path == '+' && path[1])
704 path++;
705 else
706 no_defaultdb = true;
707 if (!read_drive_database(path))
708 EXIT(FAILCMD);
709 }
710 break;
711 case 'h':
712 printing_is_off = false;
713 printslogan();
714 Usage();
715 EXIT(0);
716 break;
717
718 case opt_scan:
719 case opt_scan_open:
720 scan = optchar;
721 break;
722
723 case '?':
724 default:
725 printing_is_off = false;
726 printslogan();
727 // Point arg to the argument in which this option was found.
728 arg = argv[optind-1];
729 // Check whether the option is a long option that doesn't map to -h.
730 if (arg[1] == '-' && optchar != 'h') {
731 // Iff optopt holds a valid option then argument must be missing.
732 if (optopt && (strchr(shortopts, optopt) != NULL)) {
733 pout("=======> ARGUMENT REQUIRED FOR OPTION: %s\n", arg+2);
734 printvalidarglistmessage(optopt);
735 } else
736 pout("=======> UNRECOGNIZED OPTION: %s\n",arg+2);
737 if (extraerror[0])
738 pout("=======> %s", extraerror);
739 UsageSummary();
740 EXIT(FAILCMD);
741 }
742 if (optopt) {
743 // Iff optopt holds a valid option then argument must be
744 // missing. Note (BA) this logic seems to fail using Solaris
745 // getopt!
746 if (strchr(shortopts, optopt) != NULL) {
747 pout("=======> ARGUMENT REQUIRED FOR OPTION: %c\n", optopt);
748 printvalidarglistmessage(optopt);
749 } else
750 pout("=======> UNRECOGNIZED OPTION: %c\n",optopt);
751 if (extraerror[0])
752 pout("=======> %s", extraerror);
753 UsageSummary();
754 EXIT(FAILCMD);
755 }
756 Usage();
757 EXIT(0);
758 } // closes switch statement to process command-line options
759
760 // Check to see if option had an unrecognized or incorrect argument.
761 if (badarg) {
762 printslogan();
763 // It would be nice to print the actual option name given by the user
764 // here, but we just print the short form. Please fix this if you know
765 // a clean way to do it.
766 pout("=======> INVALID ARGUMENT TO -%c: %s\n", optchar, optarg);
767 printvalidarglistmessage(optchar);
768 if (extraerror[0])
769 pout("=======> %s", extraerror);
770 UsageSummary();
771 EXIT(FAILCMD);
772 }
773 }
774
775 // Special handling of --scan, --scanopen
776 if (scan) {
777 // Read or init drive database to allow USB ID check.
778 if (!no_defaultdb && !read_default_drive_databases())
779 EXIT(FAILCMD);
780 scan_devices(type, (scan == opt_scan_open), argv + optind);
781 EXIT(0);
782 }
783
784 // At this point we have processed all command-line options. If the
785 // print output is switchable, then start with the print output
786 // turned off
787 if (printing_is_switchable)
788 printing_is_off = true;
789
790 // error message if user has asked for more than one test
791 if (testcnt > 1) {
792 printing_is_off = false;
793 printslogan();
794 pout("\nERROR: smartctl can only run a single test type (or abort) at a time.\n");
795 UsageSummary();
796 EXIT(FAILCMD);
797 }
798
799 // error message if user has set selective self-test options without
800 // asking for a selective self-test
801 if ( (ataopts.smart_selective_args.pending_time || ataopts.smart_selective_args.scan_after_select)
802 && !ataopts.smart_selective_args.num_spans) {
803 printing_is_off = false;
804 printslogan();
805 if (ataopts.smart_selective_args.pending_time)
806 pout("\nERROR: smartctl -t pending,N must be used with -t select,N-M.\n");
807 else
808 pout("\nERROR: smartctl -t afterselect,(on|off) must be used with -t select,N-M.\n");
809 UsageSummary();
810 EXIT(FAILCMD);
811 }
812
813 // If captive option was used, change test type if appropriate.
814 if (captive)
815 switch (ataopts.smart_selftest_type) {
816 case SHORT_SELF_TEST:
817 ataopts.smart_selftest_type = SHORT_CAPTIVE_SELF_TEST;
818 scsiopts.smart_short_selftest = false;
819 scsiopts.smart_short_cap_selftest = true;
820 break;
821 case EXTEND_SELF_TEST:
822 ataopts.smart_selftest_type = EXTEND_CAPTIVE_SELF_TEST;
823 scsiopts.smart_extend_selftest = false;
824 scsiopts.smart_extend_cap_selftest = true;
825 break;
826 case CONVEYANCE_SELF_TEST:
827 ataopts.smart_selftest_type = CONVEYANCE_CAPTIVE_SELF_TEST;
828 break;
829 case SELECTIVE_SELF_TEST:
830 ataopts.smart_selftest_type = SELECTIVE_CAPTIVE_SELF_TEST;
831 break;
832 }
833
834 // From here on, normal operations...
835 printslogan();
836
837 // Warn if the user has provided no device name
838 if (argc-optind<1){
839 pout("ERROR: smartctl requires a device name as the final command-line argument.\n\n");
840 UsageSummary();
841 EXIT(FAILCMD);
842 }
843
844 // Warn if the user has provided more than one device name
845 if (argc-optind>1){
846 int i;
847 pout("ERROR: smartctl takes ONE device name as the final command-line argument.\n");
848 pout("You have provided %d device names:\n",argc-optind);
849 for (i=0; i<argc-optind; i++)
850 pout("%s\n",argv[optind+i]);
851 UsageSummary();
852 EXIT(FAILCMD);
853 }
854
855 // Read or init drive database
856 if (!no_defaultdb && !read_default_drive_databases())
857 EXIT(FAILCMD);
858
859 return type;
860 }
861
862 // Printing function (controlled by global printing_is_off)
863 // [From GLIBC Manual: Since the prototype doesn't specify types for
864 // optional arguments, in a call to a variadic function the default
865 // argument promotions are performed on the optional argument
866 // values. This means the objects of type char or short int (whether
867 // signed or not) are promoted to either int or unsigned int, as
868 // appropriate.]
869 void pout(const char *fmt, ...){
870 va_list ap;
871
872 // initialize variable argument list
873 va_start(ap,fmt);
874 if (printing_is_off) {
875 va_end(ap);
876 return;
877 }
878
879 // print out
880 vprintf(fmt,ap);
881 va_end(ap);
882 fflush(stdout);
883 return;
884 }
885
886 // Globals to set failuretest() policy
887 bool failuretest_conservative = false;
888 unsigned char failuretest_permissive = 0;
889
890 // Compares failure type to policy in effect, and either exits or
891 // simply returns to the calling routine.
892 // Used in ataprint.cpp and scsiprint.cpp.
893 void failuretest(failure_type type, int returnvalue)
894 {
895 // If this is an error in an "optional" SMART command
896 if (type == OPTIONAL_CMD) {
897 if (!failuretest_conservative)
898 return;
899 pout("An optional SMART command failed: exiting. Remove '-T conservative' option to continue.\n");
900 EXIT(returnvalue);
901 }
902
903 // If this is an error in a "mandatory" SMART command
904 if (type == MANDATORY_CMD) {
905 if (failuretest_permissive--)
906 return;
907 pout("A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.\n");
908 EXIT(returnvalue);
909 }
910
911 throw std::logic_error("failuretest: Unknown type");
912 }
913
914 // Used to warn users about invalid checksums. Called from atacmds.cpp.
915 // Action to be taken may be altered by the user.
916 void checksumwarning(const char * string)
917 {
918 // user has asked us to ignore checksum errors
919 if (checksum_err_mode == CHECKSUM_ERR_IGNORE)
920 return;
921
922 pout("Warning! %s error: invalid SMART checksum.\n", string);
923
924 // user has asked us to fail on checksum errors
925 if (checksum_err_mode == CHECKSUM_ERR_EXIT)
926 EXIT(FAILSMART);
927 }
928
929 // Return info string about device protocol
930 static const char * get_protocol_info(const smart_device * dev)
931 {
932 switch ((int)dev->is_ata() | ((int)dev->is_scsi() << 1)) {
933 case 0x1: return "ATA";
934 case 0x2: return "SCSI";
935 case 0x3: return "ATA+SCSI";
936 default: return "Unknown";
937 }
938 }
939
940 // Device scan
941 // smartctl [-d type] --scan[-open] -- [PATTERN] [smartd directive ...]
942 void scan_devices(const char * type, bool with_open, char ** argv)
943 {
944 bool dont_print = !(ata_debugmode || scsi_debugmode);
945
946 const char * pattern = 0;
947 int ai = 0;
948 if (argv[ai] && argv[ai][0] != '-')
949 pattern = argv[ai++];
950
951 smart_device_list devlist;
952 printing_is_off = dont_print;
953 bool ok = smi()->scan_smart_devices(devlist, type , pattern);
954 printing_is_off = false;
955
956 if (!ok) {
957 pout("# scan_smart_devices: %s\n", smi()->get_errmsg());
958 return;
959 }
960
961 for (unsigned i = 0; i < devlist.size(); i++) {
962 smart_device_auto_ptr dev( devlist.release(i) );
963
964 if (with_open) {
965 printing_is_off = dont_print;
966 dev.replace ( dev->autodetect_open() );
967 printing_is_off = false;
968
969 if (!dev->is_open()) {
970 pout("# %s -d %s # %s, %s device open failed: %s\n", dev->get_dev_name(),
971 dev->get_dev_type(), dev->get_info_name(),
972 get_protocol_info(dev.get()), dev->get_errmsg());
973 continue;
974 }
975 }
976
977 pout("%s -d %s", dev->get_dev_name(), dev->get_dev_type());
978 if (!argv[ai])
979 pout(" # %s, %s device\n", dev->get_info_name(), get_protocol_info(dev.get()));
980 else {
981 for (int j = ai; argv[j]; j++)
982 pout(" %s", argv[j]);
983 pout("\n");
984 }
985
986 if (dev->is_open())
987 dev->close();
988 }
989 }
990
991 // Main program without exception handling
992 static int main_worker(int argc, char **argv)
993 {
994 // Throw if CPU endianess does not match compile time test.
995 check_endianness();
996
997 // Initialize interface
998 smart_interface::init();
999 if (!smi())
1000 return 1;
1001
1002 // Parse input arguments
1003 ata_print_options ataopts;
1004 scsi_print_options scsiopts;
1005 const char * type = parse_options(argc, argv, ataopts, scsiopts);
1006
1007 // '-d test' -> Report result of autodetection
1008 bool print_type_only = (type && !strcmp(type, "test"));
1009 if (print_type_only)
1010 type = 0;
1011
1012 const char * name = argv[argc-1];
1013
1014 smart_device_auto_ptr dev;
1015 if (!strcmp(name,"-")) {
1016 // Parse "smartctl -r ataioctl,2 ..." output from stdin
1017 if (type || print_type_only) {
1018 pout("Smartctl: -d option is not allowed in conjunction with device name \"-\".\n");
1019 UsageSummary();
1020 return FAILCMD;
1021 }
1022 dev = get_parsed_ata_device(smi(), name);
1023 }
1024 else
1025 // get device of appropriate type
1026 dev = smi()->get_smart_device(name, type);
1027
1028 if (!dev) {
1029 pout("%s: %s\n", name, smi()->get_errmsg());
1030 if (type)
1031 printvalidarglistmessage('d');
1032 else
1033 pout("Smartctl: please specify device type with the -d option.\n");
1034 UsageSummary();
1035 return FAILCMD;
1036 }
1037
1038 if (print_type_only)
1039 // Report result of first autodetection
1040 pout("%s: Device of type '%s' [%s] detected\n",
1041 dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
1042
1043 // Open device
1044 {
1045 // Save old info
1046 smart_device::device_info oldinfo = dev->get_info();
1047
1048 // Open with autodetect support, may return 'better' device
1049 dev.replace( dev->autodetect_open() );
1050
1051 // Report if type has changed
1052 if ((type || print_type_only) && oldinfo.dev_type != dev->get_dev_type())
1053 pout("%s: Device open changed type from '%s' to '%s'\n",
1054 dev->get_info_name(), oldinfo.dev_type.c_str(), dev->get_dev_type());
1055 }
1056 if (!dev->is_open()) {
1057 pout("Smartctl open device: %s failed: %s\n", dev->get_info_name(), dev->get_errmsg());
1058 return FAILDEV;
1059 }
1060
1061 // now call appropriate ATA or SCSI routine
1062 int retval = 0;
1063 if (print_type_only)
1064 pout("%s: Device of type '%s' [%s] opened\n",
1065 dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
1066 else if (dev->is_ata())
1067 retval = ataPrintMain(dev->to_ata(), ataopts);
1068 else if (dev->is_scsi())
1069 retval = scsiPrintMain(dev->to_scsi(), scsiopts);
1070 else
1071 // we should never fall into this branch!
1072 pout("%s: Neither ATA nor SCSI device\n", dev->get_info_name());
1073
1074 dev->close();
1075 return retval;
1076 }
1077
1078
1079 // Main program
1080 int main(int argc, char **argv)
1081 {
1082 int status;
1083 try {
1084 // Do the real work ...
1085 status = main_worker(argc, argv);
1086 }
1087 catch (int ex) {
1088 // EXIT(status) arrives here
1089 status = ex;
1090 }
1091 catch (const std::bad_alloc & /*ex*/) {
1092 // Memory allocation failed (also thrown by std::operator new)
1093 printf("Smartctl: Out of memory\n");
1094 status = FAILCMD;
1095 }
1096 catch (const std::exception & ex) {
1097 // Other fatal errors
1098 printf("Smartctl: Exception: %s\n", ex.what());
1099 status = FAILCMD;
1100 }
1101 return status;
1102 }
1103