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