]> git.proxmox.com Git - mirror_smartmontools-debian.git/blame - smartctl.cpp
Imported Upstream version 5.39.1+svn3124
[mirror_smartmontools-debian.git] / smartctl.cpp
CommitLineData
832b75ed 1/*
4d59bff9 2 * smartctl.cpp
832b75ed
GG
3 *
4 * Home page of code is: http://smartmontools.sourceforge.net
5 *
f4ebf3d1
GI
6 * Copyright (C) 2002-10 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2008-10 Christian Franke <smartmontools-support@lists.sourceforge.net>
832b75ed
GG
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>
2127e193
GI
31#include <stdexcept>
32#include <getopt.h>
832b75ed
GG
33
34#include "config.h"
2127e193
GI
35
36#ifdef HAVE_UNISTD_H
832b75ed
GG
37#include <unistd.h>
38#endif
39
2127e193
GI
40#if defined(__FreeBSD__)
41#include <sys/param.h>
a37e7145
GG
42#endif
43
2127e193
GI
44#if defined(__QNXNTO__)
45#include <new> // TODO: Why is this include necessary on QNX ?
46#endif
a37e7145 47
832b75ed
GG
48#include "int64.h"
49#include "atacmds.h"
2127e193 50#include "dev_interface.h"
832b75ed
GG
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
e9583e0c 59const char * smartctl_cpp_cvsid = "$Id: smartctl.cpp 3119 2010-06-11 16:21:25Z chrfranke $"
2127e193 60 CONFIG_H_CVSID EXTERN_H_CVSID SMARTCTL_H_CVSID;
832b75ed
GG
61
62// This is a block containing all the "control variables". We declare
63// this globally in this file, and externally in other files.
64smartmonctrl *con=NULL;
65
2127e193
GI
66static void printslogan()
67{
68 pout("%s\n", format_version_info("smartctl").c_str());
832b75ed
GG
69}
70
71void UsageSummary(){
72 pout("\nUse smartctl -h to get a usage summary\n\n");
73 return;
74}
75
54965743 76static std::string getvalidarglist(char opt);
2127e193 77
832b75ed
GG
78/* void prints help information for command syntax */
79void Usage (void){
80 printf("Usage: smartctl [options] device\n\n");
832b75ed 81 printf(
2127e193 82"============================================ SHOW INFORMATION OPTIONS =====\n\n"
832b75ed
GG
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"
2127e193
GI
91" -x, --xall\n"
92" Show all information for device\n\n"
e9583e0c
GI
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"
832b75ed 97 );
832b75ed 98 printf(
2127e193 99"================================== SMARTCTL RUN-TIME BEHAVIOR OPTIONS =====\n\n"
832b75ed 100" -q TYPE, --quietmode=TYPE (ATA)\n"
a37e7145 101" Set smartctl quiet mode to one of: errorsonly, silent, noserial\n\n"
832b75ed 102" -d TYPE, --device=TYPE\n"
2127e193 103" Specify device type to one of: %s\n\n"
832b75ed
GG
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"
4d59bff9 110" -n MODE, --nocheck=MODE (ATA)\n"
2127e193 111" No check if: never, sleep, standby, idle (see man page)\n\n",
54965743 112 getvalidarglist('d').c_str()); // TODO: Use this function also for other options ?
832b75ed 113 printf(
2127e193 114"============================== DEVICE FEATURE ENABLE/DISABLE COMMANDS =====\n\n"
832b75ed
GG
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 );
832b75ed 122 printf(
2127e193 123"======================================= READ AND DISPLAY DATA OPTIONS =====\n\n"
832b75ed
GG
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"
2127e193
GI
131" Show device log. TYPE: error, selftest, selective, directory[,g|s],\n"
132" background, sasphy[,reset], sataphy[,reset],\n"
7f0798ef 133" scttemp[sts,hist], scterc[,N,M],\n"
2127e193
GI
134" gplog,N[,RANGE], smartlog,N[,RANGE],\n"
135" xerror[,N][,error], xselftest[,N][,selftest]\n\n"
832b75ed
GG
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"
a37e7145
GG
139" Use firmware bug workaround: none, samsung, samsung2,\n"
140" samsung3, swapid\n\n"
832b75ed
GG
141" -P TYPE, --presets=TYPE (ATA)\n"
142" Drive-specific presets: use, ignore, show, showall\n\n"
2127e193
GI
143" -B [+]FILE, --drivedb=[+]FILE (ATA)\n"
144" Read and replace [add] drive database from FILE\n"
e9583e0c
GI
145" [default is +%s",
146 get_drivedb_path_add()
147 );
2127e193 148#ifdef SMARTMONTOOLS_DRIVEDBDIR
e9583e0c
GI
149 printf(
150 "\n"
151" and then %s",
152 get_drivedb_path_default()
2127e193 153 );
e9583e0c 154#endif
832b75ed 155 printf(
e9583e0c 156 "]\n\n"
2127e193 157"============================================ DEVICE SELF-TEST OPTIONS =====\n\n"
832b75ed 158" -t TEST, --test=TEST\n"
a37e7145
GG
159" Run test. TEST: offline short long conveyance select,M-N\n"
160" pending,N afterselect,[on|off] scttempint,N[,p]\n\n"
832b75ed
GG
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);
54965743
GI
166 std::string examples = smi()->get_app_examples("smartctl");
167 if (!examples.empty())
168 printf("%s\n", examples.c_str());
832b75ed
GG
169}
170
54965743
GI
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 */
173static std::string getvalidarglist(char opt)
2127e193 174{
832b75ed
GG
175 switch (opt) {
176 case 'q':
a37e7145 177 return "errorsonly, silent, noserial";
832b75ed 178 case 'd':
54965743 179 return smi()->get_valid_dev_types_str() + ", test";
832b75ed
GG
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':
7f0798ef 191 return "error, selftest, selective, directory[,g|s], background, scttemp[sts|hist], scterc[,N,M], "
2127e193
GI
192 "sasphy[,reset], sataphy[,reset], gplog,N[,RANGE], smartlog,N[,RANGE], "
193 "xerror[,N][,error], xselftest[,N][,selftest]";
832b75ed
GG
194 case 'P':
195 return "use, ignore, show, showall";
196 case 't':
a37e7145 197 return "offline, short, long, conveyance, select,M-N, pending,N, afterselect,[on|off], scttempint,N[,p]";
832b75ed 198 case 'F':
a37e7145 199 return "none, samsung, samsung2, samsung3, swapid";
4d59bff9
GG
200 case 'n':
201 return "never, sleep, standby, idle";
832b75ed
GG
202 case 'v':
203 default:
54965743 204 return "";
832b75ed
GG
205 }
206}
207
208/* Prints the message "=======> VALID ARGUMENTS ARE: <LIST> \n", where
209 <LIST> is the list of valid arguments for option opt. */
210void printvalidarglistmessage(char opt) {
832b75ed
GG
211
212 if (opt=='v'){
2127e193
GI
213 pout("=======> VALID ARGUMENTS ARE:\n\thelp\n%s\n<=======\n",
214 create_vendor_attribute_arg_list().c_str());
832b75ed
GG
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.
54965743
GI
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);
832b75ed
GG
222 }
223
224 return;
225}
226
2127e193
GI
227// Checksum error mode
228enum checksum_err_mode_t {
229 CHECKSUM_ERR_WARN, CHECKSUM_ERR_EXIT, CHECKSUM_ERR_IGNORE
230};
231
232static checksum_err_mode_t checksum_err_mode = CHECKSUM_ERR_WARN;
233
e9583e0c
GI
234static void scan_devices(const char * type, bool with_open, const char * pattern);
235
832b75ed 236/* Takes command options and sets features to be run */
2127e193
GI
237const char * parse_options(int argc, char** argv,
238 ata_print_options & ataopts,
239 scsi_print_options & scsiopts)
240{
832b75ed 241 // Please update getvalidarglist() if you edit shortopts
2127e193 242 const char *shortopts = "h?Vq:d:T:b:r:s:o:S:HcAl:iaxv:P:t:CXF:n:B:";
832b75ed 243 // Please update getvalidarglist() if you edit longopts
e9583e0c 244 enum { opt_scan = 1000, opt_scan_open = 1001 };
832b75ed
GG
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' },
2127e193 265 { "xall", no_argument, 0, 'x' },
832b75ed
GG
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' },
4d59bff9 272 { "nocheck", required_argument, 0, 'n' },
2127e193 273 { "drivedb", required_argument, 0, 'B' },
e9583e0c
GI
274 { "scan", no_argument, 0, opt_scan },
275 { "scan-open", no_argument, 0, opt_scan_open },
832b75ed
GG
276 { 0, 0, 0, 0 }
277 };
2127e193
GI
278
279 char extraerror[256];
832b75ed
GG
280 memset(extraerror, 0, sizeof(extraerror));
281 memset(con,0,sizeof(*con));
832b75ed 282 opterr=optopt=0;
2127e193
GI
283
284 const char * type = 0; // set to -d optarg
285 bool no_defaultdb = false; // set true on '-B FILE'
e9583e0c 286 int scan = 0; // set by --scan, --scan-open
2127e193
GI
287 bool badarg = false, captive = false;
288 int testcnt = 0; // number of self-tests requested
289
290 int optchar;
291 char *arg;
292
e9583e0c 293 while ((optchar = getopt_long(argc, argv, shortopts, longopts, 0)) != -1) {
832b75ed
GG
294 switch (optchar){
295 case 'V':
2127e193
GI
296 con->dont_print = false;
297 pout("%s", format_version_info("smartctl", true /*full*/).c_str());
298 EXIT(0);
832b75ed
GG
299 break;
300 case 'q':
301 if (!strcmp(optarg,"errorsonly")) {
2127e193
GI
302 con->printing_switchable = true;
303 con->dont_print = false;
832b75ed 304 } else if (!strcmp(optarg,"silent")) {
2127e193
GI
305 con->printing_switchable = false;
306 con->dont_print = true;
a37e7145 307 } else if (!strcmp(optarg,"noserial")) {
2127e193 308 con->dont_print_serial = true;
832b75ed 309 } else {
2127e193 310 badarg = true;
832b75ed
GG
311 }
312 break;
313 case 'd':
2127e193 314 type = optarg;
832b75ed
GG
315 break;
316 case 'T':
317 if (!strcmp(optarg,"normal")) {
2127e193 318 con->conservative = false;
832b75ed
GG
319 con->permissive = 0;
320 } else if (!strcmp(optarg,"conservative")) {
2127e193 321 con->conservative = true;
832b75ed
GG
322 } else if (!strcmp(optarg,"permissive")) {
323 if (con->permissive<0xff)
324 con->permissive++;
325 } else if (!strcmp(optarg,"verypermissive")) {
2127e193 326 con->permissive = 0xff;
832b75ed 327 } else {
2127e193 328 badarg = true;
832b75ed
GG
329 }
330 break;
331 case 'b':
332 if (!strcmp(optarg,"warn")) {
2127e193 333 checksum_err_mode = CHECKSUM_ERR_WARN;
832b75ed 334 } else if (!strcmp(optarg,"exit")) {
2127e193 335 checksum_err_mode = CHECKSUM_ERR_EXIT;
832b75ed 336 } else if (!strcmp(optarg,"ignore")) {
2127e193 337 checksum_err_mode = CHECKSUM_ERR_IGNORE;
832b75ed 338 } else {
2127e193 339 badarg = true;
832b75ed
GG
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))) {
2127e193 350 throw std::bad_alloc();
832b75ed
GG
351 }
352 if (split_report_arg(s, &i)) {
2127e193 353 badarg = true;
832b75ed
GG
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 {
2127e193 361 badarg = true;
832b75ed
GG
362 }
363 free(s);
364 }
365 break;
366 case 's':
367 if (!strcmp(optarg,"on")) {
2127e193
GI
368 ataopts.smart_enable = scsiopts.smart_enable = true;
369 ataopts.smart_disable = scsiopts.smart_disable = false;
832b75ed 370 } else if (!strcmp(optarg,"off")) {
2127e193
GI
371 ataopts.smart_disable = scsiopts.smart_disable = true;
372 ataopts.smart_enable = scsiopts.smart_enable = false;
832b75ed 373 } else {
2127e193 374 badarg = true;
832b75ed
GG
375 }
376 break;
377 case 'o':
378 if (!strcmp(optarg,"on")) {
2127e193
GI
379 ataopts.smart_auto_offl_enable = true;
380 ataopts.smart_auto_offl_disable = false;
832b75ed 381 } else if (!strcmp(optarg,"off")) {
2127e193
GI
382 ataopts.smart_auto_offl_disable = true;
383 ataopts.smart_auto_offl_enable = false;
832b75ed 384 } else {
2127e193 385 badarg = true;
832b75ed
GG
386 }
387 break;
388 case 'S':
389 if (!strcmp(optarg,"on")) {
2127e193
GI
390 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = true;
391 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = false;
832b75ed 392 } else if (!strcmp(optarg,"off")) {
2127e193
GI
393 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = true;
394 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = false;
832b75ed 395 } else {
2127e193 396 badarg = true;
832b75ed
GG
397 }
398 break;
399 case 'H':
2127e193 400 ataopts.smart_check_status = scsiopts.smart_check_status = true;
832b75ed
GG
401 break;
402 case 'F':
403 if (!strcmp(optarg,"none")) {
2127e193 404 ataopts.fix_firmwarebug = FIX_NONE;
832b75ed 405 } else if (!strcmp(optarg,"samsung")) {
2127e193 406 ataopts.fix_firmwarebug = FIX_SAMSUNG;
832b75ed 407 } else if (!strcmp(optarg,"samsung2")) {
2127e193 408 ataopts.fix_firmwarebug = FIX_SAMSUNG2;
a37e7145 409 } else if (!strcmp(optarg,"samsung3")) {
2127e193 410 ataopts.fix_firmwarebug = FIX_SAMSUNG3;
a37e7145 411 } else if (!strcmp(optarg,"swapid")) {
2127e193 412 ataopts.fix_swapped_id = true;
832b75ed 413 } else {
2127e193 414 badarg = true;
832b75ed
GG
415 }
416 break;
417 case 'c':
2127e193 418 ataopts.smart_general_values = true;
832b75ed
GG
419 break;
420 case 'A':
2127e193 421 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = true;
832b75ed
GG
422 break;
423 case 'l':
424 if (!strcmp(optarg,"error")) {
2127e193 425 ataopts.smart_error_log = scsiopts.smart_error_log = true;
832b75ed 426 } else if (!strcmp(optarg,"selftest")) {
2127e193 427 ataopts.smart_selftest_log = scsiopts.smart_selftest_log = true;
832b75ed 428 } else if (!strcmp(optarg, "selective")) {
2127e193 429 ataopts.smart_selective_selftest_log = true;
832b75ed 430 } else if (!strcmp(optarg,"directory")) {
2127e193
GI
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;
4d59bff9 444 } else if (!strcmp(optarg,"background")) {
2127e193 445 scsiopts.smart_background_log = true;
7f0798ef
GI
446 } else if (!strcmp(optarg,"scterc")) {
447 ataopts.sct_erc_get = true;
a37e7145 448 } else if (!strcmp(optarg,"scttemp")) {
2127e193 449 ataopts.sct_temp_sts = ataopts.sct_temp_hist = true;
a37e7145 450 } else if (!strcmp(optarg,"scttempsts")) {
2127e193 451 ataopts.sct_temp_sts = true;
a37e7145 452 } else if (!strcmp(optarg,"scttemphist")) {
2127e193
GI
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
7f0798ef
GI
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 }
2127e193
GI
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 }
832b75ed 526 } else {
2127e193 527 badarg = true;
832b75ed
GG
528 }
529 break;
530 case 'i':
2127e193
GI
531 ataopts.drive_info = scsiopts.drive_info = true;
532 break;
832b75ed 533 case 'a':
2127e193
GI
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;
7f0798ef 556 ataopts.sct_erc_get = true;
2127e193
GI
557 ataopts.sataphy = true;
558 scsiopts.smart_background_log = true;
559 scsiopts.sasphy = true;
832b75ed
GG
560 break;
561 case 'v':
562 // parse vendor-specific definitions of attributes
563 if (!strcmp(optarg,"help")) {
2127e193 564 con->dont_print = false;
832b75ed 565 printslogan();
2127e193
GI
566 pout("The valid arguments to -v are:\n\thelp\n%s\n",
567 create_vendor_attribute_arg_list().c_str());
832b75ed
GG
568 EXIT(0);
569 }
bed94269 570 if (!parse_attribute_def(optarg, ataopts.attribute_defs, PRIOR_USER))
2127e193 571 badarg = true;
832b75ed
GG
572 break;
573 case 'P':
574 if (!strcmp(optarg, "use")) {
2127e193 575 ataopts.ignore_presets = false;
832b75ed 576 } else if (!strcmp(optarg, "ignore")) {
2127e193 577 ataopts.ignore_presets = true;
832b75ed 578 } else if (!strcmp(optarg, "show")) {
2127e193 579 ataopts.show_presets = true;
832b75ed 580 } else if (!strcmp(optarg, "showall")) {
2127e193
GI
581 if (!no_defaultdb && !read_default_drive_databases())
582 EXIT(FAILCMD);
832b75ed
GG
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 {
2127e193 591 badarg = true;
832b75ed
GG
592 }
593 break;
594 case 't':
595 if (!strcmp(optarg,"offline")) {
2127e193
GI
596 testcnt++;
597 ataopts.smart_selftest_type = OFFLINE_FULL_SCAN;
598 scsiopts.smart_default_selftest = true;
832b75ed 599 } else if (!strcmp(optarg,"short")) {
2127e193
GI
600 testcnt++;
601 ataopts.smart_selftest_type = SHORT_SELF_TEST;
602 scsiopts.smart_short_selftest = true;
832b75ed 603 } else if (!strcmp(optarg,"long")) {
2127e193
GI
604 testcnt++;
605 ataopts.smart_selftest_type = EXTEND_SELF_TEST;
606 scsiopts.smart_extend_selftest = true;
832b75ed 607 } else if (!strcmp(optarg,"conveyance")) {
2127e193
GI
608 testcnt++;
609 ataopts.smart_selftest_type = CONVEYANCE_SELF_TEST;
832b75ed 610 } else if (!strcmp(optarg,"afterselect,on")) {
2127e193
GI
611 // scan remainder of disk after doing selected segment
612 ataopts.smart_selective_args.scan_after_select = 2;
832b75ed 613 } else if (!strcmp(optarg,"afterselect,off")) {
2127e193
GI
614 // don't scan remainder of disk after doing selected segments
615 ataopts.smart_selective_args.scan_after_select = 1;
832b75ed
GG
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");
2127e193 624 badarg = true;
832b75ed
GG
625 } else if (i<0 || i>65535) {
626 sprintf(extraerror, "Option -t pending,N (N=%d) must have 0 <= N <= 65535\n", i);
2127e193 627 badarg = true;
832b75ed 628 } else {
2127e193 629 ataopts.smart_selective_args.pending_time = i+1;
832b75ed
GG
630 }
631 } else if (!strncmp(optarg,"select",strlen("select"))) {
e9583e0c
GI
632 if (ataopts.smart_selective_args.num_spans == 0)
633 testcnt++;
a37e7145
GG
634 // parse range of LBAs to test
635 uint64_t start, stop; int mode;
636 if (split_selective_arg(optarg, &start, &stop, &mode)) {
832b75ed 637 sprintf(extraerror, "Option -t select,M-N must have non-negative integer M and N\n");
2127e193 638 badarg = true;
832b75ed 639 } else {
2127e193 640 if (ataopts.smart_selective_args.num_spans >= 5 || start > stop) {
832b75ed
GG
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 }
2127e193 648 badarg = true;
832b75ed 649 }
2127e193
GI
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;
832b75ed 655 }
a37e7145
GG
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");
2127e193 661 badarg = true;
a37e7145 662 }
2127e193
GI
663 ataopts.sct_temp_int = interval;
664 ataopts.sct_temp_int_pers = (n2 == len);
832b75ed 665 } else {
2127e193 666 badarg = true;
832b75ed
GG
667 }
668 break;
669 case 'C':
2127e193 670 captive = true;
832b75ed
GG
671 break;
672 case 'X':
2127e193
GI
673 testcnt++;
674 scsiopts.smart_selftest_abort = true;
675 ataopts.smart_selftest_type = ABORT_SELF_TEST;
832b75ed 676 break;
4d59bff9
GG
677 case 'n':
678 // skip disk check if in low-power mode
679 if (!strcmp(optarg, "never"))
2127e193 680 ataopts.powermode = 1; // do not skip, but print mode
4d59bff9 681 else if (!strcmp(optarg, "sleep"))
2127e193 682 ataopts.powermode = 2;
4d59bff9 683 else if (!strcmp(optarg, "standby"))
2127e193 684 ataopts.powermode = 3;
4d59bff9 685 else if (!strcmp(optarg, "idle"))
2127e193 686 ataopts.powermode = 4;
4d59bff9 687 else
2127e193
GI
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 }
4d59bff9 700 break;
832b75ed 701 case 'h':
2127e193 702 con->dont_print = false;
832b75ed
GG
703 printslogan();
704 Usage();
705 EXIT(0);
706 break;
e9583e0c
GI
707
708 case opt_scan:
709 case opt_scan_open:
710 scan = optchar;
711 break;
712
832b75ed
GG
713 case '?':
714 default:
2127e193 715 con->dont_print = false;
832b75ed 716 printslogan();
832b75ed
GG
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 }
832b75ed
GG
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 }
e9583e0c
GI
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
832b75ed
GG
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)
f4ebf3d1 775 con->dont_print = true;
832b75ed
GG
776
777 // error message if user has asked for more than one test
2127e193
GI
778 if (testcnt > 1) {
779 con->dont_print = false;
832b75ed
GG
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
2127e193
GI
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;
832b75ed 791 printslogan();
2127e193 792 if (ataopts.smart_selective_args.pending_time)
832b75ed
GG
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.
2127e193
GI
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
832b75ed
GG
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);
2127e193
GI
840 }
841
842 // Read or init drive database
843 if (!no_defaultdb && !read_default_drive_databases())
844 EXIT(FAILCMD);
845
846 return type;
832b75ed
GG
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.]
4d59bff9 856void pout(const char *fmt, ...){
832b75ed
GG
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
4d59bff9 873// This function is used by utility.cpp to report LOG_CRIT errors.
832b75ed 874// The smartctl version prints to stdout instead of syslog().
4d59bff9 875void PrintOut(int priority, const char *fmt, ...) {
832b75ed
GG
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
2127e193
GI
888// Used to warn users about invalid checksums. Called from atacmds.cpp.
889// Action to be taken may be altered by the user.
890void checksumwarning(const char * string)
891{
892 // user has asked us to ignore checksum errors
893 if (checksum_err_mode == CHECKSUM_ERR_IGNORE)
894 return;
832b75ed 895
2127e193 896 pout("Warning! %s error: invalid SMART checksum.\n", string);
832b75ed 897
2127e193
GI
898 // user has asked us to fail on checksum errors
899 if (checksum_err_mode == CHECKSUM_ERR_EXIT)
900 EXIT(FAILSMART);
901}
832b75ed 902
2127e193
GI
903// Return info string about device protocol
904static 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}
832b75ed 913
e9583e0c
GI
914// Device scan
915// smartctl [-d type] --scan[-open] [PATTERN]
916void 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
2127e193
GI
952// Main program without exception handling
953int main_worker(int argc, char **argv)
954{
e9583e0c
GI
955 // Throw if CPU endianess does not match compile time test.
956 check_endianness();
957
2127e193
GI
958 // Initialize interface
959 smart_interface::init();
960 if (!smi())
961 return 1;
962
bed94269
GI
963 // define control block for external functions
964 smartmonctrl control;
965 con=&control;
2127e193 966
bed94269
GI
967 // Parse input arguments
968 ata_print_options ataopts;
969 scsi_print_options scsiopts;
970 const char * type = parse_options(argc, argv, ataopts, scsiopts);
832b75ed 971
bed94269
GI
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");
a37e7145
GG
984 UsageSummary();
985 return FAILCMD;
986 }
bed94269
GI
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 }
a37e7145 1002
bed94269
GI
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()));
2127e193 1007
bed94269
GI
1008 // Open device
1009 {
1010 // Save old info
1011 smart_device::device_info oldinfo = dev->get_info();
2127e193 1012
bed94269
GI
1013 // Open with autodetect support, may return 'better' device
1014 dev.replace( dev->autodetect_open() );
2127e193 1015
bed94269
GI
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());
2127e193 1020 }
bed94269
GI
1021 if (!dev->is_open()) {
1022 pout("Smartctl open device: %s failed: %s\n", dev->get_info_name(), dev->get_errmsg());
1023 return FAILDEV;
832b75ed 1024 }
bed94269
GI
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();
2127e193
GI
1040 return retval;
1041}
832b75ed 1042
2127e193
GI
1043
1044// Main program
1045int main(int argc, char **argv)
1046{
1047 int status;
1048 try {
1049 // Do the real work ...
1050 status = main_worker(argc, argv);
832b75ed 1051 }
2127e193
GI
1052 catch (int ex) {
1053 // EXIT(status) arrives here
1054 status = ex;
832b75ed 1055 }
2127e193
GI
1056 catch (const std::bad_alloc & /*ex*/) {
1057 // Memory allocation failed (also thrown by std::operator new)
bed94269 1058 printf("Smartctl: Out of memory\n");
2127e193 1059 status = FAILCMD;
832b75ed 1060 }
2127e193
GI
1061 catch (const std::exception & ex) {
1062 // Other fatal errors
bed94269 1063 printf("Smartctl: Exception: %s\n", ex.what());
2127e193 1064 status = FAILCMD;
832b75ed 1065 }
2127e193 1066 return status;
832b75ed 1067}
2127e193 1068