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