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