]> git.proxmox.com Git - mirror_smartmontools-debian.git/blame - smartctl.cpp
New upstream version 6.6
[mirror_smartmontools-debian.git] / smartctl.cpp
CommitLineData
832b75ed 1/*
4d59bff9 2 * smartctl.cpp
832b75ed 3 *
a86ec89e 4 * Home page of code is: http://www.smartmontools.org
832b75ed 5 *
a86ec89e 6 * Copyright (C) 2002-11 Bruce Allen
f9e10201 7 * Copyright (C) 2008-17 Christian Franke
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
ee38a438 16 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
832b75ed
GG
17 *
18 * This code was originally developed as a Senior Thesis by Michael Cornwell
19 * at the Concurrent Systems Laboratory (now part of the Storage Systems
20 * Research Center), Jack Baskin School of Engineering, University of
21 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
22 *
23 */
24
25#include <errno.h>
26#include <stdio.h>
27#include <sys/types.h>
28#include <string.h>
d2e702cf 29#include <stdlib.h>
832b75ed 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
832b75ed
GG
44#include "int64.h"
45#include "atacmds.h"
2127e193 46#include "dev_interface.h"
832b75ed 47#include "ataprint.h"
832b75ed
GG
48#include "knowndrives.h"
49#include "scsicmds.h"
50#include "scsiprint.h"
a86ec89e 51#include "nvmeprint.h"
832b75ed
GG
52#include "smartctl.h"
53#include "utility.h"
54
f9e10201 55const char * smartctl_cpp_cvsid = "$Id: smartctl.cpp 4585 2017-11-04 13:41:03Z chrfranke $"
cfbba5b9 56 CONFIG_H_CVSID SMARTCTL_H_CVSID;
832b75ed 57
cfbba5b9
GI
58// Globals to control printing
59bool printing_is_switchable = false;
60bool printing_is_off = false;
832b75ed 61
2127e193
GI
62static void printslogan()
63{
64 pout("%s\n", format_version_info("smartctl").c_str());
832b75ed
GG
65}
66
cfbba5b9
GI
67static void UsageSummary()
68{
832b75ed
GG
69 pout("\nUse smartctl -h to get a usage summary\n\n");
70 return;
71}
72
d008864d 73static std::string getvalidarglist(int opt);
2127e193 74
832b75ed 75/* void prints help information for command syntax */
cfbba5b9
GI
76static void Usage()
77{
832b75ed 78 printf("Usage: smartctl [options] device\n\n");
832b75ed 79 printf(
2127e193 80"============================================ SHOW INFORMATION OPTIONS =====\n\n"
832b75ed
GG
81" -h, --help, --usage\n"
82" Display this help and exit\n\n"
83" -V, --version, --copyright, --license\n"
84" Print license, copyright, and version information and exit\n\n"
d008864d 85" -i, --info\n"
832b75ed 86" Show identity information for device\n\n"
ee38a438
GI
87" --identify[=[w][nvb]]\n"
88" Show words and bits from IDENTIFY DEVICE data (ATA)\n\n"
d008864d 89" -g NAME, --get=NAME\n"
f9e10201
JD
90" Get device setting: all, aam, apm, dsn, lookahead, security,\n"
91" wcache, rcache, wcreorder, wcache-sct\n\n"
d008864d 92" -a, --all\n"
832b75ed 93" Show all SMART information for device\n\n"
2127e193
GI
94" -x, --xall\n"
95" Show all information for device\n\n"
e9583e0c
GI
96" --scan\n"
97" Scan for devices\n\n"
98" --scan-open\n"
99" Scan for devices and try to open each device\n\n"
832b75ed 100 );
832b75ed 101 printf(
2127e193 102"================================== SMARTCTL RUN-TIME BEHAVIOR OPTIONS =====\n\n"
832b75ed 103" -q TYPE, --quietmode=TYPE (ATA)\n"
a37e7145 104" Set smartctl quiet mode to one of: errorsonly, silent, noserial\n\n"
832b75ed 105" -d TYPE, --device=TYPE\n"
f9e10201
JD
106" Specify device type to one of:\n"
107" %s\n\n" // TODO: fold this string
832b75ed
GG
108" -T TYPE, --tolerance=TYPE (ATA)\n"
109" Tolerance: normal, conservative, permissive, verypermissive\n\n"
110" -b TYPE, --badsum=TYPE (ATA)\n"
111" Set action on bad checksum to one of: warn, exit, ignore\n\n"
112" -r TYPE, --report=TYPE\n"
113" Report transactions (see man page)\n\n"
f9e10201 114" -n MODE[,STATUS], --nocheck=MODE[,STATUS] (ATA)\n"
2127e193 115" No check if: never, sleep, standby, idle (see man page)\n\n",
54965743 116 getvalidarglist('d').c_str()); // TODO: Use this function also for other options ?
832b75ed 117 printf(
2127e193 118"============================== DEVICE FEATURE ENABLE/DISABLE COMMANDS =====\n\n"
832b75ed
GG
119" -s VALUE, --smart=VALUE\n"
120" Enable/disable SMART on device (on/off)\n\n"
121" -o VALUE, --offlineauto=VALUE (ATA)\n"
122" Enable/disable automatic offline testing on device (on/off)\n\n"
123" -S VALUE, --saveauto=VALUE (ATA)\n"
124" Enable/disable Attribute autosave on device (on/off)\n\n"
d008864d
GI
125" -s NAME[,VALUE], --set=NAME[,VALUE]\n"
126" Enable/disable/change device setting: aam,[N|off], apm,[N|off],\n"
f9e10201
JD
127" dsn,[on|off], lookahead,[on|off], security-freeze,\n"
128" standby,[N|off|now], wcache,[on|off], rcache,[on|off],\n"
129" wcreorder,[on|off[,p]], wcache-sct,[ata|on|off[,p]]\n\n"
832b75ed 130 );
832b75ed 131 printf(
2127e193 132"======================================= READ AND DISPLAY DATA OPTIONS =====\n\n"
832b75ed
GG
133" -H, --health\n"
134" Show device SMART health status\n\n"
a86ec89e 135" -c, --capabilities (ATA, NVMe)\n"
832b75ed 136" Show device SMART capabilities\n\n"
a7e8ffec 137" -A, --attributes\n"
832b75ed 138" Show device SMART vendor-specific Attributes and values\n\n"
a7e8ffec 139" -f FORMAT, --format=FORMAT (ATA)\n"
e165493d 140" Set output format for attributes: old, brief, hex[,id|val]\n\n"
832b75ed 141" -l TYPE, --log=TYPE\n"
2127e193 142" Show device log. TYPE: error, selftest, selective, directory[,g|s],\n"
f9e10201
JD
143" xerror[,N][,error], xselftest[,N][,selftest], background,\n"
144" sasphy[,reset], sataphy[,reset], scttemp[sts,hist],\n"
145" scttempint,N[,p], scterc[,N,M], devstat[,N], defects[,N], ssd,\n"
146" gplog,N[,RANGE], smartlog,N[,RANGE], nvmelog,N,SIZE\n\n"
832b75ed
GG
147" -v N,OPTION , --vendorattribute=N,OPTION (ATA)\n"
148" Set display OPTION for vendor Attribute N (see man page)\n\n"
149" -F TYPE, --firmwarebug=TYPE (ATA)\n"
ee38a438
GI
150" Use firmware bug workaround:\n"
151" %s, swapid\n\n"
832b75ed
GG
152" -P TYPE, --presets=TYPE (ATA)\n"
153" Drive-specific presets: use, ignore, show, showall\n\n"
2127e193
GI
154" -B [+]FILE, --drivedb=[+]FILE (ATA)\n"
155" Read and replace [add] drive database from FILE\n"
e9583e0c 156" [default is +%s",
ee38a438 157 get_valid_firmwarebug_args(),
e9583e0c
GI
158 get_drivedb_path_add()
159 );
2127e193 160#ifdef SMARTMONTOOLS_DRIVEDBDIR
e9583e0c
GI
161 printf(
162 "\n"
163" and then %s",
164 get_drivedb_path_default()
2127e193 165 );
e9583e0c 166#endif
832b75ed 167 printf(
e9583e0c 168 "]\n\n"
2127e193 169"============================================ DEVICE SELF-TEST OPTIONS =====\n\n"
832b75ed 170" -t TEST, --test=TEST\n"
d008864d
GI
171" Run test. TEST: offline, short, long, conveyance, force, vendor,N,\n"
172" select,M-N, pending,N, afterselect,[on|off]\n\n"
832b75ed
GG
173" -C, --captive\n"
174" Do test in captive mode (along with -t)\n\n"
175" -X, --abort\n"
176" Abort any non-captive test on device\n\n"
177);
54965743
GI
178 std::string examples = smi()->get_app_examples("smartctl");
179 if (!examples.empty())
180 printf("%s\n", examples.c_str());
832b75ed
GG
181}
182
d008864d 183// Values for --long only options, see parse_options()
ee38a438 184enum { opt_identify = 1000, opt_scan, opt_scan_open, opt_set, opt_smart };
d008864d 185
54965743
GI
186/* Returns a string containing a formatted list of the valid arguments
187 to the option opt or empty on failure. Note 'v' case different */
d008864d 188static std::string getvalidarglist(int opt)
2127e193 189{
832b75ed
GG
190 switch (opt) {
191 case 'q':
a37e7145 192 return "errorsonly, silent, noserial";
832b75ed 193 case 'd':
cfbba5b9 194 return smi()->get_valid_dev_types_str() + ", auto, test";
832b75ed
GG
195 case 'T':
196 return "normal, conservative, permissive, verypermissive";
197 case 'b':
198 return "warn, exit, ignore";
f9e10201
JD
199 case 'B':
200 return "[+]<FILE_NAME>";
832b75ed 201 case 'r':
a86ec89e 202 return "ioctl[,N], ataioctl[,N], scsiioctl[,N], nvmeioctl[,N]";
d008864d 203 case opt_smart:
832b75ed
GG
204 case 'o':
205 case 'S':
206 return "on, off";
207 case 'l':
d008864d
GI
208 return "error, selftest, selective, directory[,g|s], "
209 "xerror[,N][,error], xselftest[,N][,selftest], "
210 "background, sasphy[,reset], sataphy[,reset], "
211 "scttemp[sts,hist], scttempint,N[,p], "
f9e10201 212 "scterc[,N,M], devstat[,N], defects[,N], ssd, "
a86ec89e
GI
213 "gplog,N[,RANGE], smartlog,N[,RANGE], "
214 "nvmelog,N,SIZE";
832b75ed
GG
215 case 'P':
216 return "use, ignore, show, showall";
217 case 't':
d008864d
GI
218 return "offline, short, long, conveyance, force, vendor,N, select,M-N, "
219 "pending,N, afterselect,[on|off]";
832b75ed 220 case 'F':
ee38a438 221 return std::string(get_valid_firmwarebug_args()) + ", swapid";
4d59bff9 222 case 'n':
f9e10201 223 return "never, sleep[,STATUS], standby[,STATUS], idle[,STATUS]";
a7e8ffec 224 case 'f':
e165493d 225 return "old, brief, hex[,id|val]";
d008864d 226 case 'g':
f9e10201 227 return "aam, apm, dsn, lookahead, security, wcache, rcache, wcreorder, wcache-sct";
d008864d 228 case opt_set:
f9e10201
JD
229 return "aam,[N|off], apm,[N|off], dsn,[on|off], lookahead,[on|off], security-freeze, "
230 "standby,[N|off|now], wcache,[on|off], rcache,[on|off], wcreorder,[on|off[,p]], "
231 "wcache-sct,[ata|on|off[,p]]";
d008864d
GI
232 case 's':
233 return getvalidarglist(opt_smart)+", "+getvalidarglist(opt_set);
ee38a438
GI
234 case opt_identify:
235 return "n, wn, w, v, wv, wb";
832b75ed
GG
236 case 'v':
237 default:
54965743 238 return "";
832b75ed
GG
239 }
240}
241
242/* Prints the message "=======> VALID ARGUMENTS ARE: <LIST> \n", where
243 <LIST> is the list of valid arguments for option opt. */
d008864d 244static void printvalidarglistmessage(int opt)
cfbba5b9 245{
832b75ed 246 if (opt=='v'){
2127e193
GI
247 pout("=======> VALID ARGUMENTS ARE:\n\thelp\n%s\n<=======\n",
248 create_vendor_attribute_arg_list().c_str());
832b75ed
GG
249 }
250 else {
251 // getvalidarglist() might produce a multiline or single line string. We
252 // need to figure out which to get the formatting right.
54965743
GI
253 std::string s = getvalidarglist(opt);
254 char separator = strchr(s.c_str(), '\n') ? '\n' : ' ';
255 pout("=======> VALID ARGUMENTS ARE:%c%s%c<=======\n", separator, s.c_str(), separator);
832b75ed
GG
256 }
257
258 return;
259}
260
2127e193
GI
261// Checksum error mode
262enum checksum_err_mode_t {
263 CHECKSUM_ERR_WARN, CHECKSUM_ERR_EXIT, CHECKSUM_ERR_IGNORE
264};
265
266static checksum_err_mode_t checksum_err_mode = CHECKSUM_ERR_WARN;
267
a86ec89e 268static void scan_devices(const smart_devtype_list & types, bool with_open, char ** argv);
e9583e0c 269
d008864d 270
832b75ed 271/* Takes command options and sets features to be run */
cfbba5b9 272static const char * parse_options(int argc, char** argv,
d008864d 273 ata_print_options & ataopts, scsi_print_options & scsiopts,
a86ec89e 274 nvme_print_options & nvmeopts, bool & print_type_only)
2127e193 275{
832b75ed 276 // Please update getvalidarglist() if you edit shortopts
d008864d 277 const char *shortopts = "h?Vq:d:T:b:r:s:o:S:HcAl:iaxv:P:t:CXF:n:B:f:g:";
832b75ed
GG
278 // Please update getvalidarglist() if you edit longopts
279 struct option longopts[] = {
280 { "help", no_argument, 0, 'h' },
281 { "usage", no_argument, 0, 'h' },
282 { "version", no_argument, 0, 'V' },
283 { "copyright", no_argument, 0, 'V' },
284 { "license", no_argument, 0, 'V' },
285 { "quietmode", required_argument, 0, 'q' },
286 { "device", required_argument, 0, 'd' },
287 { "tolerance", required_argument, 0, 'T' },
288 { "badsum", required_argument, 0, 'b' },
289 { "report", required_argument, 0, 'r' },
d008864d 290 { "smart", required_argument, 0, opt_smart },
832b75ed
GG
291 { "offlineauto", required_argument, 0, 'o' },
292 { "saveauto", required_argument, 0, 'S' },
293 { "health", no_argument, 0, 'H' },
294 { "capabilities", no_argument, 0, 'c' },
295 { "attributes", no_argument, 0, 'A' },
296 { "log", required_argument, 0, 'l' },
297 { "info", no_argument, 0, 'i' },
298 { "all", no_argument, 0, 'a' },
2127e193 299 { "xall", no_argument, 0, 'x' },
832b75ed
GG
300 { "vendorattribute", required_argument, 0, 'v' },
301 { "presets", required_argument, 0, 'P' },
302 { "test", required_argument, 0, 't' },
303 { "captive", no_argument, 0, 'C' },
304 { "abort", no_argument, 0, 'X' },
305 { "firmwarebug", required_argument, 0, 'F' },
4d59bff9 306 { "nocheck", required_argument, 0, 'n' },
2127e193 307 { "drivedb", required_argument, 0, 'B' },
a7e8ffec 308 { "format", required_argument, 0, 'f' },
d008864d 309 { "get", required_argument, 0, 'g' },
ee38a438 310 { "identify", optional_argument, 0, opt_identify },
d008864d 311 { "set", required_argument, 0, opt_set },
e9583e0c
GI
312 { "scan", no_argument, 0, opt_scan },
313 { "scan-open", no_argument, 0, opt_scan_open },
832b75ed
GG
314 { 0, 0, 0, 0 }
315 };
2127e193
GI
316
317 char extraerror[256];
832b75ed 318 memset(extraerror, 0, sizeof(extraerror));
832b75ed 319 opterr=optopt=0;
2127e193
GI
320
321 const char * type = 0; // set to -d optarg
a86ec89e
GI
322 smart_devtype_list scan_types; // multiple -d TYPE options for --scan
323 bool use_default_db = true; // set false on '-B FILE'
a7e8ffec 324 bool output_format_set = false; // set true on '-f FORMAT'
e9583e0c 325 int scan = 0; // set by --scan, --scan-open
2127e193
GI
326 bool badarg = false, captive = false;
327 int testcnt = 0; // number of self-tests requested
328
329 int optchar;
330 char *arg;
331
e9583e0c 332 while ((optchar = getopt_long(argc, argv, shortopts, longopts, 0)) != -1) {
832b75ed
GG
333 switch (optchar){
334 case 'V':
cfbba5b9 335 printing_is_off = false;
2127e193
GI
336 pout("%s", format_version_info("smartctl", true /*full*/).c_str());
337 EXIT(0);
832b75ed
GG
338 break;
339 case 'q':
340 if (!strcmp(optarg,"errorsonly")) {
cfbba5b9
GI
341 printing_is_switchable = true;
342 printing_is_off = false;
832b75ed 343 } else if (!strcmp(optarg,"silent")) {
cfbba5b9
GI
344 printing_is_switchable = false;
345 printing_is_off = true;
a37e7145 346 } else if (!strcmp(optarg,"noserial")) {
cfbba5b9 347 dont_print_serial_number = true;
832b75ed 348 } else {
2127e193 349 badarg = true;
832b75ed
GG
350 }
351 break;
352 case 'd':
d008864d
GI
353 if (!strcmp(optarg, "test"))
354 print_type_only = true;
a86ec89e
GI
355 else if (!strcmp(optarg, "auto")) {
356 type = 0;
357 scan_types.clear();
358 }
359 else {
360 type = optarg;
361 scan_types.push_back(optarg);
362 }
832b75ed
GG
363 break;
364 case 'T':
365 if (!strcmp(optarg,"normal")) {
cfbba5b9
GI
366 failuretest_conservative = false;
367 failuretest_permissive = 0;
832b75ed 368 } else if (!strcmp(optarg,"conservative")) {
cfbba5b9 369 failuretest_conservative = true;
832b75ed 370 } else if (!strcmp(optarg,"permissive")) {
cfbba5b9
GI
371 if (failuretest_permissive < 0xff)
372 failuretest_permissive++;
832b75ed 373 } else if (!strcmp(optarg,"verypermissive")) {
cfbba5b9 374 failuretest_permissive = 0xff;
832b75ed 375 } else {
2127e193 376 badarg = true;
832b75ed
GG
377 }
378 break;
379 case 'b':
380 if (!strcmp(optarg,"warn")) {
2127e193 381 checksum_err_mode = CHECKSUM_ERR_WARN;
832b75ed 382 } else if (!strcmp(optarg,"exit")) {
2127e193 383 checksum_err_mode = CHECKSUM_ERR_EXIT;
832b75ed 384 } else if (!strcmp(optarg,"ignore")) {
2127e193 385 checksum_err_mode = CHECKSUM_ERR_IGNORE;
832b75ed 386 } else {
2127e193 387 badarg = true;
832b75ed
GG
388 }
389 break;
390 case 'r':
391 {
a86ec89e
GI
392 int n1 = -1, n2 = -1, len = strlen(optarg);
393 char s[9+1]; unsigned i = 1;
394 sscanf(optarg, "%9[a-z]%n,%u%n", s, &n1, &i, &n2);
395 if (!((n1 == len || n2 == len) && 1 <= i && i <= 4)) {
2127e193 396 badarg = true;
832b75ed 397 } else if (!strcmp(s,"ioctl")) {
a86ec89e 398 ata_debugmode = scsi_debugmode = nvme_debugmode = i;
832b75ed 399 } else if (!strcmp(s,"ataioctl")) {
cfbba5b9 400 ata_debugmode = i;
832b75ed 401 } else if (!strcmp(s,"scsiioctl")) {
cfbba5b9 402 scsi_debugmode = i;
a86ec89e
GI
403 } else if (!strcmp(s,"nvmeioctl")) {
404 nvme_debugmode = i;
832b75ed 405 } else {
2127e193 406 badarg = true;
832b75ed 407 }
832b75ed
GG
408 }
409 break;
d008864d 410
832b75ed 411 case 's':
d008864d 412 case opt_smart: // --smart
832b75ed 413 if (!strcmp(optarg,"on")) {
2127e193
GI
414 ataopts.smart_enable = scsiopts.smart_enable = true;
415 ataopts.smart_disable = scsiopts.smart_disable = false;
832b75ed 416 } else if (!strcmp(optarg,"off")) {
2127e193
GI
417 ataopts.smart_disable = scsiopts.smart_disable = true;
418 ataopts.smart_enable = scsiopts.smart_enable = false;
d008864d
GI
419 } else if (optchar == 's') {
420 goto case_s_continued; // --set, see below
832b75ed 421 } else {
2127e193 422 badarg = true;
832b75ed
GG
423 }
424 break;
d008864d 425
832b75ed
GG
426 case 'o':
427 if (!strcmp(optarg,"on")) {
2127e193
GI
428 ataopts.smart_auto_offl_enable = true;
429 ataopts.smart_auto_offl_disable = false;
832b75ed 430 } else if (!strcmp(optarg,"off")) {
2127e193
GI
431 ataopts.smart_auto_offl_disable = true;
432 ataopts.smart_auto_offl_enable = false;
832b75ed 433 } else {
2127e193 434 badarg = true;
832b75ed
GG
435 }
436 break;
437 case 'S':
438 if (!strcmp(optarg,"on")) {
2127e193
GI
439 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = true;
440 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = false;
832b75ed 441 } else if (!strcmp(optarg,"off")) {
2127e193
GI
442 ataopts.smart_auto_save_disable = scsiopts.smart_auto_save_disable = true;
443 ataopts.smart_auto_save_enable = scsiopts.smart_auto_save_enable = false;
832b75ed 444 } else {
2127e193 445 badarg = true;
832b75ed
GG
446 }
447 break;
448 case 'H':
a86ec89e 449 ataopts.smart_check_status = scsiopts.smart_check_status = nvmeopts.smart_check_status = true;
d008864d 450 scsiopts.smart_ss_media_log = true;
832b75ed
GG
451 break;
452 case 'F':
ee38a438 453 if (!strcmp(optarg, "swapid"))
2127e193 454 ataopts.fix_swapped_id = true;
ee38a438 455 else if (!parse_firmwarebug_def(optarg, ataopts.firmwarebugs))
2127e193 456 badarg = true;
832b75ed
GG
457 break;
458 case 'c':
a86ec89e 459 ataopts.smart_general_values = nvmeopts.drive_capabilities = true;
832b75ed
GG
460 break;
461 case 'A':
a86ec89e 462 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = nvmeopts.smart_vendor_attrib = true;
832b75ed
GG
463 break;
464 case 'l':
a86ec89e
GI
465 if (str_starts_with(optarg, "error")) {
466 int n1 = -1, n2 = -1, len = strlen(optarg);
467 unsigned val = ~0;
468 sscanf(optarg, "error%n,%u%n", &n1, &val, &n2);
2127e193 469 ataopts.smart_error_log = scsiopts.smart_error_log = true;
a86ec89e
GI
470 if (n1 == len)
471 nvmeopts.error_log_entries = 16;
472 else if (n2 == len && val > 0)
473 nvmeopts.error_log_entries = val;
474 else
475 badarg = true;
832b75ed 476 } else if (!strcmp(optarg,"selftest")) {
2127e193 477 ataopts.smart_selftest_log = scsiopts.smart_selftest_log = true;
832b75ed 478 } else if (!strcmp(optarg, "selective")) {
2127e193 479 ataopts.smart_selective_selftest_log = true;
832b75ed 480 } else if (!strcmp(optarg,"directory")) {
2127e193
GI
481 ataopts.smart_logdir = ataopts.gp_logdir = true; // SMART+GPL
482 } else if (!strcmp(optarg,"directory,s")) {
483 ataopts.smart_logdir = true; // SMART
484 } else if (!strcmp(optarg,"directory,g")) {
485 ataopts.gp_logdir = true; // GPL
486 } else if (!strcmp(optarg,"sasphy")) {
487 scsiopts.sasphy = true;
488 } else if (!strcmp(optarg,"sasphy,reset")) {
489 scsiopts.sasphy = scsiopts.sasphy_reset = true;
490 } else if (!strcmp(optarg,"sataphy")) {
491 ataopts.sataphy = true;
492 } else if (!strcmp(optarg,"sataphy,reset")) {
493 ataopts.sataphy = ataopts.sataphy_reset = true;
4d59bff9 494 } else if (!strcmp(optarg,"background")) {
2127e193 495 scsiopts.smart_background_log = true;
d008864d
GI
496 } else if (!strcmp(optarg,"ssd")) {
497 ataopts.devstat_ssd_page = true;
498 scsiopts.smart_ss_media_log = true;
7f0798ef
GI
499 } else if (!strcmp(optarg,"scterc")) {
500 ataopts.sct_erc_get = true;
a37e7145 501 } else if (!strcmp(optarg,"scttemp")) {
2127e193 502 ataopts.sct_temp_sts = ataopts.sct_temp_hist = true;
a37e7145 503 } else if (!strcmp(optarg,"scttempsts")) {
2127e193 504 ataopts.sct_temp_sts = true;
a37e7145 505 } else if (!strcmp(optarg,"scttemphist")) {
2127e193
GI
506 ataopts.sct_temp_hist = true;
507
d008864d
GI
508 } else if (!strncmp(optarg, "scttempint,", sizeof("scstempint,")-1)) {
509 unsigned interval = 0; int n1 = -1, n2 = -1, len = strlen(optarg);
510 if (!( sscanf(optarg,"scttempint,%u%n,p%n", &interval, &n1, &n2) == 1
511 && 0 < interval && interval <= 0xffff && (n1 == len || n2 == len))) {
ee38a438 512 snprintf(extraerror, sizeof(extraerror), "Option -l scttempint,N[,p] must have positive integer N\n");
d008864d
GI
513 badarg = true;
514 }
515 ataopts.sct_temp_int = interval;
516 ataopts.sct_temp_int_pers = (n2 == len);
517
518 } else if (!strncmp(optarg, "devstat", sizeof("devstat")-1)) {
519 int n1 = -1, n2 = -1, len = strlen(optarg);
520 unsigned val = ~0;
521 sscanf(optarg, "devstat%n,%u%n", &n1, &val, &n2);
522 if (n1 == len)
523 ataopts.devstat_all_pages = true;
a86ec89e
GI
524 else {
525 if (n2 != len) // retry with hex
526 sscanf(optarg, "devstat,0x%x%n", &val, &n2);
527 if (n2 == len && val <= 0xff)
528 ataopts.devstat_pages.push_back(val);
529 else
530 badarg = true;
531 }
d008864d 532
f9e10201
JD
533 } else if (str_starts_with(optarg, "defects")) {
534 int n1 = -1, n2 = -1, len = strlen(optarg);
535 unsigned val = ~0;
536 sscanf(optarg, "defects%n,%u%n", &n1, &val, &n2);
537 if (n1 == len)
538 ataopts.pending_defects_log = 31; // Entries of first page
539 else if (n2 == len && val <= 0xffff * 32 - 1)
540 ataopts.pending_defects_log = val;
541 else
542 badarg = true;
543
2127e193
GI
544 } else if (!strncmp(optarg, "xerror", sizeof("xerror")-1)) {
545 int n1 = -1, n2 = -1, len = strlen(optarg);
546 unsigned val = 8;
547 sscanf(optarg, "xerror%n,error%n", &n1, &n2);
548 if (!(n1 == len || n2 == len)) {
549 n1 = n2 = -1;
550 sscanf(optarg, "xerror,%u%n,error%n", &val, &n1, &n2);
551 }
552 if ((n1 == len || n2 == len) && val > 0) {
553 ataopts.smart_ext_error_log = val;
554 ataopts.retry_error_log = (n2 == len);
555 }
556 else
557 badarg = true;
558
559 } else if (!strncmp(optarg, "xselftest", sizeof("xselftest")-1)) {
560 int n1 = -1, n2 = -1, len = strlen(optarg);
561 unsigned val = 25;
562 sscanf(optarg, "xselftest%n,selftest%n", &n1, &n2);
563 if (!(n1 == len || n2 == len)) {
564 n1 = n2 = -1;
565 sscanf(optarg, "xselftest,%u%n,selftest%n", &val, &n1, &n2);
566 }
567 if ((n1 == len || n2 == len) && val > 0) {
568 ataopts.smart_ext_selftest_log = val;
569 ataopts.retry_selftest_log = (n2 == len);
570 }
571 else
572 badarg = true;
573
7f0798ef
GI
574 } else if (!strncmp(optarg, "scterc,", sizeof("scterc,")-1)) {
575 unsigned rt = ~0, wt = ~0; int n = -1;
576 sscanf(optarg,"scterc,%u,%u%n", &rt, &wt, &n);
577 if (n == (int)strlen(optarg) && rt <= 999 && wt <= 999) {
578 ataopts.sct_erc_set = true;
579 ataopts.sct_erc_readtime = rt;
580 ataopts.sct_erc_writetime = wt;
581 }
582 else {
ee38a438 583 snprintf(extraerror, sizeof(extraerror), "Option -l scterc,[READTIME,WRITETIME] syntax error\n");
7f0798ef
GI
584 badarg = true;
585 }
2127e193
GI
586 } else if ( !strncmp(optarg, "gplog," , sizeof("gplog," )-1)
587 || !strncmp(optarg, "smartlog,", sizeof("smartlog,")-1)) {
588 unsigned logaddr = ~0U; unsigned page = 0, nsectors = 1; char sign = 0;
589 int n1 = -1, n2 = -1, n3 = -1, len = strlen(optarg);
590 sscanf(optarg, "%*[a-z],0x%x%n,%u%n%c%u%n",
591 &logaddr, &n1, &page, &n2, &sign, &nsectors, &n3);
592 if (len > n2 && n3 == -1 && !strcmp(optarg+n2, "-max")) {
593 nsectors = ~0U; sign = '+'; n3 = len;
594 }
595 bool gpl = (optarg[0] == 'g');
596 const char * erropt = (gpl ? "gplog" : "smartlog");
597 if (!( n1 == len || n2 == len
598 || (n3 == len && (sign == '+' || sign == '-')))) {
ee38a438 599 snprintf(extraerror, sizeof(extraerror), "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] syntax error\n", erropt);
2127e193
GI
600 badarg = true;
601 }
602 else if (!( logaddr <= 0xff && page <= (gpl ? 0xffffU : 0x00ffU)
603 && 0 < nsectors
604 && (nsectors <= (gpl ? 0xffffU : 0xffU) || nsectors == ~0U)
605 && (sign != '-' || page <= nsectors) )) {
ee38a438 606 snprintf(extraerror, sizeof(extraerror), "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] parameter out of range\n", erropt);
2127e193
GI
607 badarg = true;
608 }
609 else {
610 ata_log_request req;
611 req.gpl = gpl; req.logaddr = logaddr; req.page = page;
612 req.nsectors = (sign == '-' ? nsectors-page+1 : nsectors);
613 ataopts.log_requests.push_back(req);
614 }
a86ec89e
GI
615 }
616
617 else if (str_starts_with(optarg, "nvmelog,")) {
618 int n = -1, len = strlen(optarg);
619 unsigned page = 0, size = 0;
620 sscanf(optarg, "nvmelog,0x%x,0x%x%n", &page, &size, &n);
621 if (n == len && page <= 0xff && 0 < size && size <= 0x4000) {
622 nvmeopts.log_page = page; nvmeopts.log_page_size = size;
623 }
624 else
625 badarg = true;
626 }
627
628 else {
2127e193 629 badarg = true;
832b75ed
GG
630 }
631 break;
632 case 'i':
a86ec89e 633 ataopts.drive_info = scsiopts.drive_info = nvmeopts.drive_info = true;
2127e193 634 break;
ee38a438
GI
635
636 case opt_identify:
637 ataopts.identify_word_level = ataopts.identify_bit_level = 0;
638 if (optarg) {
639 for (int i = 0; optarg[i]; i++) {
640 switch (optarg[i]) {
641 case 'w': ataopts.identify_word_level = 1; break;
642 case 'n': ataopts.identify_bit_level = -1; break;
643 case 'v': ataopts.identify_bit_level = 1; break;
644 case 'b': ataopts.identify_bit_level = 2; break;
645 default: badarg = true;
646 }
647 }
648 }
649 break;
650
832b75ed 651 case 'a':
a86ec89e
GI
652 ataopts.drive_info = scsiopts.drive_info = nvmeopts.drive_info = true;
653 ataopts.smart_check_status = scsiopts.smart_check_status = nvmeopts.smart_check_status = true;
654 ataopts.smart_general_values = nvmeopts.drive_capabilities = true;
655 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = nvmeopts.smart_vendor_attrib = true;
2127e193 656 ataopts.smart_error_log = scsiopts.smart_error_log = true;
a86ec89e 657 nvmeopts.error_log_entries = 16;
2127e193
GI
658 ataopts.smart_selftest_log = scsiopts.smart_selftest_log = true;
659 ataopts.smart_selective_selftest_log = true;
660 /* scsiopts.smart_background_log = true; */
d008864d 661 scsiopts.smart_ss_media_log = true;
2127e193
GI
662 break;
663 case 'x':
a86ec89e
GI
664 ataopts.drive_info = scsiopts.drive_info = nvmeopts.drive_info = true;
665 ataopts.smart_check_status = scsiopts.smart_check_status = nvmeopts.smart_check_status = true;
666 ataopts.smart_general_values = nvmeopts.drive_capabilities = true;
667 ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = nvmeopts.smart_vendor_attrib = true;
2127e193
GI
668 ataopts.smart_ext_error_log = 8;
669 ataopts.retry_error_log = true;
a86ec89e 670 nvmeopts.error_log_entries = 16;
2127e193
GI
671 ataopts.smart_ext_selftest_log = 25;
672 ataopts.retry_selftest_log = true;
673 scsiopts.smart_error_log = scsiopts.smart_selftest_log = true;
674 ataopts.smart_selective_selftest_log = true;
675 ataopts.smart_logdir = ataopts.gp_logdir = true;
676 ataopts.sct_temp_sts = ataopts.sct_temp_hist = true;
7f0798ef 677 ataopts.sct_erc_get = true;
3d17a85c 678 ataopts.sct_wcache_reorder_get = true;
ee38a438 679 ataopts.devstat_all_pages = true;
f9e10201
JD
680 // ataopts.pending_defects_log = 31; // TODO: Add if no longer EXPERIMENTAL
681 ataopts.pending_defects_info = true; // TODO: Remove then
2127e193 682 ataopts.sataphy = true;
d008864d
GI
683 ataopts.get_set_used = true;
684 ataopts.get_aam = ataopts.get_apm = true;
685 ataopts.get_security = true;
686 ataopts.get_lookahead = ataopts.get_wcache = true;
f9e10201 687 ataopts.get_dsn = true;
ee38a438 688 scsiopts.get_rcd = scsiopts.get_wce = true;
2127e193 689 scsiopts.smart_background_log = true;
d008864d 690 scsiopts.smart_ss_media_log = true;
2127e193 691 scsiopts.sasphy = true;
a7e8ffec 692 if (!output_format_set)
e165493d 693 ataopts.output_format |= ata_print_options::FMT_BRIEF;
832b75ed
GG
694 break;
695 case 'v':
696 // parse vendor-specific definitions of attributes
697 if (!strcmp(optarg,"help")) {
cfbba5b9 698 printing_is_off = false;
832b75ed 699 printslogan();
2127e193
GI
700 pout("The valid arguments to -v are:\n\thelp\n%s\n",
701 create_vendor_attribute_arg_list().c_str());
832b75ed
GG
702 EXIT(0);
703 }
bed94269 704 if (!parse_attribute_def(optarg, ataopts.attribute_defs, PRIOR_USER))
2127e193 705 badarg = true;
832b75ed
GG
706 break;
707 case 'P':
708 if (!strcmp(optarg, "use")) {
2127e193 709 ataopts.ignore_presets = false;
832b75ed 710 } else if (!strcmp(optarg, "ignore")) {
2127e193 711 ataopts.ignore_presets = true;
832b75ed 712 } else if (!strcmp(optarg, "show")) {
2127e193 713 ataopts.show_presets = true;
832b75ed 714 } else if (!strcmp(optarg, "showall")) {
a86ec89e 715 if (!init_drive_database(use_default_db))
2127e193 716 EXIT(FAILCMD);
832b75ed
GG
717 if (optind < argc) { // -P showall MODEL [FIRMWARE]
718 int cnt = showmatchingpresets(argv[optind], (optind+1<argc ? argv[optind+1] : NULL));
719 EXIT(cnt); // report #matches
720 }
721 if (showallpresets())
722 EXIT(FAILCMD); // report regexp syntax error
723 EXIT(0);
724 } else {
2127e193 725 badarg = true;
832b75ed
GG
726 }
727 break;
728 case 't':
729 if (!strcmp(optarg,"offline")) {
2127e193
GI
730 testcnt++;
731 ataopts.smart_selftest_type = OFFLINE_FULL_SCAN;
732 scsiopts.smart_default_selftest = true;
832b75ed 733 } else if (!strcmp(optarg,"short")) {
2127e193
GI
734 testcnt++;
735 ataopts.smart_selftest_type = SHORT_SELF_TEST;
736 scsiopts.smart_short_selftest = true;
832b75ed 737 } else if (!strcmp(optarg,"long")) {
2127e193
GI
738 testcnt++;
739 ataopts.smart_selftest_type = EXTEND_SELF_TEST;
740 scsiopts.smart_extend_selftest = true;
832b75ed 741 } else if (!strcmp(optarg,"conveyance")) {
2127e193
GI
742 testcnt++;
743 ataopts.smart_selftest_type = CONVEYANCE_SELF_TEST;
d008864d
GI
744 } else if (!strcmp(optarg,"force")) {
745 ataopts.smart_selftest_force = true;
ee38a438 746 scsiopts.smart_selftest_force = true;
832b75ed 747 } else if (!strcmp(optarg,"afterselect,on")) {
2127e193
GI
748 // scan remainder of disk after doing selected segment
749 ataopts.smart_selective_args.scan_after_select = 2;
832b75ed 750 } else if (!strcmp(optarg,"afterselect,off")) {
2127e193
GI
751 // don't scan remainder of disk after doing selected segments
752 ataopts.smart_selective_args.scan_after_select = 1;
832b75ed
GG
753 } else if (!strncmp(optarg,"pending,",strlen("pending,"))) {
754 // parse number of minutes that test should be pending
755 int i;
756 char *tailptr=NULL;
757 errno=0;
758 i=(int)strtol(optarg+strlen("pending,"), &tailptr, 10);
759 if (errno || *tailptr != '\0') {
ee38a438 760 snprintf(extraerror, sizeof(extraerror), "Option -t pending,N requires N to be a non-negative integer\n");
2127e193 761 badarg = true;
832b75ed 762 } else if (i<0 || i>65535) {
ee38a438 763 snprintf(extraerror, sizeof(extraerror), "Option -t pending,N (N=%d) must have 0 <= N <= 65535\n", i);
2127e193 764 badarg = true;
832b75ed 765 } else {
2127e193 766 ataopts.smart_selective_args.pending_time = i+1;
832b75ed
GG
767 }
768 } else if (!strncmp(optarg,"select",strlen("select"))) {
e9583e0c
GI
769 if (ataopts.smart_selective_args.num_spans == 0)
770 testcnt++;
a37e7145
GG
771 // parse range of LBAs to test
772 uint64_t start, stop; int mode;
773 if (split_selective_arg(optarg, &start, &stop, &mode)) {
ee38a438 774 snprintf(extraerror, sizeof(extraerror), "Option -t select,M-N must have non-negative integer M and N\n");
2127e193 775 badarg = true;
832b75ed 776 } else {
2127e193 777 if (ataopts.smart_selective_args.num_spans >= 5 || start > stop) {
832b75ed 778 if (start > stop) {
d2e702cf 779 snprintf(extraerror, sizeof(extraerror), "ERROR: Start LBA (%" PRIu64 ") > ending LBA (%" PRId64 ") in argument \"%s\"\n",
832b75ed
GG
780 start, stop, optarg);
781 } else {
ee38a438 782 snprintf(extraerror, sizeof(extraerror),"ERROR: No more than five selective self-test spans may be"
832b75ed
GG
783 " defined\n");
784 }
2127e193 785 badarg = true;
832b75ed 786 }
2127e193
GI
787 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].start = start;
788 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].end = stop;
789 ataopts.smart_selective_args.span[ataopts.smart_selective_args.num_spans].mode = mode;
790 ataopts.smart_selective_args.num_spans++;
791 ataopts.smart_selftest_type = SELECTIVE_SELF_TEST;
832b75ed 792 }
d008864d 793 } else if (!strncmp(optarg, "scttempint", sizeof("scstempint")-1)) {
ee38a438 794 snprintf(extraerror, sizeof(extraerror), "-t scttempint is no longer supported, use -l scttempint instead\n");
d008864d 795 badarg = true;
cfbba5b9
GI
796 } else if (!strncmp(optarg, "vendor,", sizeof("vendor,")-1)) {
797 unsigned subcmd = ~0U; int n = -1;
798 if (!( sscanf(optarg, "%*[a-z],0x%x%n", &subcmd, &n) == 1
799 && subcmd <= 0xff && n == (int)strlen(optarg))) {
ee38a438 800 snprintf(extraerror, sizeof(extraerror), "Option -t vendor,0xNN syntax error\n");
cfbba5b9
GI
801 badarg = true;
802 }
803 else
804 ataopts.smart_selftest_type = subcmd;
832b75ed 805 } else {
2127e193 806 badarg = true;
832b75ed
GG
807 }
808 break;
809 case 'C':
2127e193 810 captive = true;
832b75ed
GG
811 break;
812 case 'X':
2127e193
GI
813 testcnt++;
814 scsiopts.smart_selftest_abort = true;
815 ataopts.smart_selftest_type = ABORT_SELF_TEST;
832b75ed 816 break;
4d59bff9
GG
817 case 'n':
818 // skip disk check if in low-power mode
f9e10201 819 if (!strcmp(optarg, "never")) {
2127e193 820 ataopts.powermode = 1; // do not skip, but print mode
f9e10201
JD
821 }
822 else {
823 int n1 = -1, n2 = -1, len = strlen(optarg);
824 char s[7+1]; unsigned i = FAILPOWER;
825 sscanf(optarg, "%9[a-z]%n,%u%n", s, &n1, &i, &n2);
826 if (!((n1 == len || n2 == len) && i <= 255))
827 badarg = true;
828 else if (!strcmp(s, "sleep"))
829 ataopts.powermode = 2;
830 else if (!strcmp(s, "standby"))
831 ataopts.powermode = 3;
832 else if (!strcmp(s, "idle"))
833 ataopts.powermode = 4;
834 else
835 badarg = true;
836 ataopts.powerexit = i;
837 }
2127e193 838 break;
a7e8ffec 839 case 'f':
e165493d
GI
840 if (!strcmp(optarg, "old")) {
841 ataopts.output_format &= ~ata_print_options::FMT_BRIEF;
842 output_format_set = true;
843 }
844 else if (!strcmp(optarg, "brief")) {
845 ataopts.output_format |= ata_print_options::FMT_BRIEF;
846 output_format_set = true;
a7e8ffec 847 }
e165493d
GI
848 else if (!strcmp(optarg, "hex"))
849 ataopts.output_format |= ata_print_options::FMT_HEX_ID
850 | ata_print_options::FMT_HEX_VAL;
851 else if (!strcmp(optarg, "hex,id"))
852 ataopts.output_format |= ata_print_options::FMT_HEX_ID;
853 else if (!strcmp(optarg, "hex,val"))
854 ataopts.output_format |= ata_print_options::FMT_HEX_VAL;
855 else
856 badarg = true;
a7e8ffec 857 break;
2127e193
GI
858 case 'B':
859 {
860 const char * path = optarg;
861 if (*path == '+' && path[1])
862 path++;
863 else
a86ec89e 864 use_default_db = false;
2127e193
GI
865 if (!read_drive_database(path))
866 EXIT(FAILCMD);
867 }
4d59bff9 868 break;
832b75ed 869 case 'h':
cfbba5b9 870 printing_is_off = false;
832b75ed
GG
871 printslogan();
872 Usage();
873 EXIT(0);
874 break;
e9583e0c 875
d008864d
GI
876 case 'g':
877 case_s_continued: // -s, see above
878 case opt_set: // --set
879 {
880 ataopts.get_set_used = true;
881 bool get = (optchar == 'g');
882 char name[16+1]; unsigned val;
883 int n1 = -1, n2 = -1, n3 = -1, len = strlen(optarg);
884 if (sscanf(optarg, "%16[^,=]%n%*[,=]%n%u%n", name, &n1, &n2, &val, &n3) >= 1
885 && (n1 == len || (!get && n2 > 0))) {
f9e10201
JD
886 bool on = false;
887 bool off = false;
888 bool ata = false;
889 bool persistent = false;
890
891 if (n2 > 0) {
892 int len2 = strlen(optarg + n2);
893 char * tmp = strstr(optarg+n2, ",p");
894 // handle ",p" in persistent options like: wcache-sct,[ata|on|off],p
895 if (tmp && (strlen(tmp) == 2)) {
896 persistent = true;
897 len2 = strlen(optarg+n2) - 2;
898
899 // the ,p option only works for set of SCT Feature Control command
900 if (strcmp(name, "wcache-sct") != 0 &&
901 strcmp(name, "wcreorder") != 0)
902 badarg = true;
903 }
904 on = !strncmp(optarg+n2, "on", len2);
905 off = !strncmp(optarg+n2, "off", len2);
906 ata = !strncmp(optarg+n2, "ata", len2);
907 }
d008864d
GI
908 if (n3 != len)
909 val = ~0U;
910
911 if (get && !strcmp(name, "all")) {
912 ataopts.get_aam = ataopts.get_apm = true;
913 ataopts.get_security = true;
914 ataopts.get_lookahead = ataopts.get_wcache = true;
f9e10201 915 ataopts.get_dsn = true;
ee38a438 916 scsiopts.get_rcd = scsiopts.get_wce = true;
d008864d
GI
917 }
918 else if (!strcmp(name, "aam")) {
919 if (get)
920 ataopts.get_aam = true;
921 else if (off)
922 ataopts.set_aam = -1;
923 else if (val <= 254)
924 ataopts.set_aam = val + 1;
925 else {
ee38a438 926 snprintf(extraerror, sizeof(extraerror), "Option -s aam,N must have 0 <= N <= 254\n");
d008864d
GI
927 badarg = true;
928 }
929 }
930 else if (!strcmp(name, "apm")) {
931 if (get)
932 ataopts.get_apm = true;
933 else if (off)
934 ataopts.set_apm = -1;
935 else if (1 <= val && val <= 254)
936 ataopts.set_apm = val + 1;
937 else {
ee38a438 938 snprintf(extraerror, sizeof(extraerror), "Option -s apm,N must have 1 <= N <= 254\n");
d008864d
GI
939 badarg = true;
940 }
941 }
942 else if (!strcmp(name, "lookahead")) {
ee38a438 943 if (get) {
d008864d 944 ataopts.get_lookahead = true;
ee38a438 945 }
d008864d
GI
946 else if (off)
947 ataopts.set_lookahead = -1;
948 else if (on)
949 ataopts.set_lookahead = 1;
950 else
951 badarg = true;
952 }
3d17a85c 953 else if (!strcmp(name, "wcreorder")) {
f9e10201 954 ataopts.sct_wcache_reorder_set_pers = persistent;
3d17a85c
GI
955 if (get) {
956 ataopts.sct_wcache_reorder_get = true;
957 }
958 else if (off)
959 ataopts.sct_wcache_reorder_set = -1;
960 else if (on)
961 ataopts.sct_wcache_reorder_set = 1;
962 else
963 badarg = true;
964 }
f9e10201
JD
965 else if (!strcmp(name, "wcache-sct")) {
966 ataopts.sct_wcache_sct_set_pers = persistent;
967 if (get) {
968 ataopts.sct_wcache_sct_get = true;
969 }
970 else if (off)
971 ataopts.sct_wcache_sct_set = 3;
972 else if (on)
973 ataopts.sct_wcache_sct_set = 2;
974 else if (ata)
975 ataopts.sct_wcache_sct_set = 1;
976 else
977 badarg = true;
978 }
ee38a438
GI
979 else if (!strcmp(name, "rcache")) {
980 if (get)
981 scsiopts.get_rcd = true;
982 else if (off)
983 scsiopts.set_rcd = -1;
984 else if (on)
985 scsiopts.set_rcd = 1;
986 else
987 badarg = true;
988 }
d008864d
GI
989 else if (get && !strcmp(name, "security")) {
990 ataopts.get_security = true;
991 }
992 else if (!get && !strcmp(optarg, "security-freeze")) {
993 ataopts.set_security_freeze = true;
994 }
995 else if (!get && !strcmp(optarg, "standby,now")) {
996 ataopts.set_standby_now = true;
997 }
998 else if (!get && !strcmp(name, "standby")) {
999 if (off)
1000 ataopts.set_standby = 0 + 1;
1001 else if (val <= 255)
1002 ataopts.set_standby = val + 1;
1003 else {
ee38a438 1004 snprintf(extraerror, sizeof(extraerror), "Option -s standby,N must have 0 <= N <= 255\n");
d008864d
GI
1005 badarg = true;
1006 }
1007 }
1008 else if (!strcmp(name, "wcache")) {
ee38a438 1009 if (get) {
d008864d 1010 ataopts.get_wcache = true;
ee38a438
GI
1011 scsiopts.get_wce = true;
1012 }
1013 else if (off) {
d008864d 1014 ataopts.set_wcache = -1;
ee38a438
GI
1015 scsiopts.set_wce = -1;
1016 }
1017 else if (on) {
d008864d 1018 ataopts.set_wcache = 1;
ee38a438
GI
1019 scsiopts.set_wce = 1;
1020 }
d008864d
GI
1021 else
1022 badarg = true;
1023 }
f9e10201
JD
1024 else if (!strcmp(name, "dsn")) {
1025 if (get) {
1026 ataopts.get_dsn = true;
1027 }
1028 else if (off) {
1029 ataopts.set_dsn = -1;
1030 }
1031 else if (on) {
1032 ataopts.set_dsn = 1;
1033 }
1034 else
1035 badarg = true;
1036 }
d008864d
GI
1037 else
1038 badarg = true;
1039 }
1040 else
1041 badarg = true;
1042 }
1043 break;
1044
e9583e0c
GI
1045 case opt_scan:
1046 case opt_scan_open:
1047 scan = optchar;
1048 break;
1049
832b75ed
GG
1050 case '?':
1051 default:
cfbba5b9 1052 printing_is_off = false;
832b75ed 1053 printslogan();
832b75ed
GG
1054 // Point arg to the argument in which this option was found.
1055 arg = argv[optind-1];
1056 // Check whether the option is a long option that doesn't map to -h.
1057 if (arg[1] == '-' && optchar != 'h') {
1058 // Iff optopt holds a valid option then argument must be missing.
d008864d 1059 if (optopt && (optopt >= opt_scan || strchr(shortopts, optopt))) {
832b75ed
GG
1060 pout("=======> ARGUMENT REQUIRED FOR OPTION: %s\n", arg+2);
1061 printvalidarglistmessage(optopt);
1062 } else
1063 pout("=======> UNRECOGNIZED OPTION: %s\n",arg+2);
1064 if (extraerror[0])
1065 pout("=======> %s", extraerror);
1066 UsageSummary();
1067 EXIT(FAILCMD);
1068 }
d008864d 1069 if (0 < optopt && optopt < '~') {
832b75ed
GG
1070 // Iff optopt holds a valid option then argument must be
1071 // missing. Note (BA) this logic seems to fail using Solaris
1072 // getopt!
1073 if (strchr(shortopts, optopt) != NULL) {
1074 pout("=======> ARGUMENT REQUIRED FOR OPTION: %c\n", optopt);
1075 printvalidarglistmessage(optopt);
1076 } else
1077 pout("=======> UNRECOGNIZED OPTION: %c\n",optopt);
1078 if (extraerror[0])
1079 pout("=======> %s", extraerror);
1080 UsageSummary();
1081 EXIT(FAILCMD);
1082 }
1083 Usage();
1084 EXIT(0);
1085 } // closes switch statement to process command-line options
1086
1087 // Check to see if option had an unrecognized or incorrect argument.
1088 if (badarg) {
1089 printslogan();
1090 // It would be nice to print the actual option name given by the user
1091 // here, but we just print the short form. Please fix this if you know
1092 // a clean way to do it.
d008864d
GI
1093 char optstr[] = { (char)optchar, 0 };
1094 pout("=======> INVALID ARGUMENT TO -%s: %s\n",
ee38a438
GI
1095 (optchar == opt_identify ? "-identify" :
1096 optchar == opt_set ? "-set" :
d008864d 1097 optchar == opt_smart ? "-smart" : optstr), optarg);
832b75ed
GG
1098 printvalidarglistmessage(optchar);
1099 if (extraerror[0])
1100 pout("=======> %s", extraerror);
1101 UsageSummary();
1102 EXIT(FAILCMD);
1103 }
1104 }
e9583e0c
GI
1105
1106 // Special handling of --scan, --scanopen
1107 if (scan) {
cfbba5b9 1108 // Read or init drive database to allow USB ID check.
a86ec89e 1109 if (!init_drive_database(use_default_db))
cfbba5b9 1110 EXIT(FAILCMD);
a86ec89e 1111 scan_devices(scan_types, (scan == opt_scan_open), argv + optind);
e9583e0c
GI
1112 EXIT(0);
1113 }
1114
832b75ed
GG
1115 // At this point we have processed all command-line options. If the
1116 // print output is switchable, then start with the print output
1117 // turned off
cfbba5b9
GI
1118 if (printing_is_switchable)
1119 printing_is_off = true;
832b75ed 1120
a86ec89e
GI
1121 // Check for multiple -d TYPE options
1122 if (scan_types.size() > 1) {
1123 printing_is_off = false;
1124 printslogan();
1125 pout("ERROR: multiple -d TYPE options are only allowed with --scan\n");
1126 UsageSummary();
1127 EXIT(FAILCMD);
1128 }
1129
832b75ed 1130 // error message if user has asked for more than one test
2127e193 1131 if (testcnt > 1) {
cfbba5b9 1132 printing_is_off = false;
832b75ed
GG
1133 printslogan();
1134 pout("\nERROR: smartctl can only run a single test type (or abort) at a time.\n");
1135 UsageSummary();
1136 EXIT(FAILCMD);
1137 }
1138
1139 // error message if user has set selective self-test options without
1140 // asking for a selective self-test
2127e193
GI
1141 if ( (ataopts.smart_selective_args.pending_time || ataopts.smart_selective_args.scan_after_select)
1142 && !ataopts.smart_selective_args.num_spans) {
cfbba5b9 1143 printing_is_off = false;
832b75ed 1144 printslogan();
2127e193 1145 if (ataopts.smart_selective_args.pending_time)
832b75ed
GG
1146 pout("\nERROR: smartctl -t pending,N must be used with -t select,N-M.\n");
1147 else
1148 pout("\nERROR: smartctl -t afterselect,(on|off) must be used with -t select,N-M.\n");
1149 UsageSummary();
1150 EXIT(FAILCMD);
1151 }
1152
1153 // If captive option was used, change test type if appropriate.
2127e193
GI
1154 if (captive)
1155 switch (ataopts.smart_selftest_type) {
1156 case SHORT_SELF_TEST:
1157 ataopts.smart_selftest_type = SHORT_CAPTIVE_SELF_TEST;
1158 scsiopts.smart_short_selftest = false;
1159 scsiopts.smart_short_cap_selftest = true;
1160 break;
1161 case EXTEND_SELF_TEST:
1162 ataopts.smart_selftest_type = EXTEND_CAPTIVE_SELF_TEST;
1163 scsiopts.smart_extend_selftest = false;
1164 scsiopts.smart_extend_cap_selftest = true;
1165 break;
1166 case CONVEYANCE_SELF_TEST:
1167 ataopts.smart_selftest_type = CONVEYANCE_CAPTIVE_SELF_TEST;
1168 break;
1169 case SELECTIVE_SELF_TEST:
1170 ataopts.smart_selftest_type = SELECTIVE_CAPTIVE_SELF_TEST;
1171 break;
1172 }
1173
832b75ed
GG
1174 // From here on, normal operations...
1175 printslogan();
1176
1177 // Warn if the user has provided no device name
1178 if (argc-optind<1){
1179 pout("ERROR: smartctl requires a device name as the final command-line argument.\n\n");
1180 UsageSummary();
1181 EXIT(FAILCMD);
1182 }
1183
1184 // Warn if the user has provided more than one device name
1185 if (argc-optind>1){
1186 int i;
1187 pout("ERROR: smartctl takes ONE device name as the final command-line argument.\n");
1188 pout("You have provided %d device names:\n",argc-optind);
1189 for (i=0; i<argc-optind; i++)
1190 pout("%s\n",argv[optind+i]);
1191 UsageSummary();
1192 EXIT(FAILCMD);
2127e193
GI
1193 }
1194
1195 // Read or init drive database
a86ec89e 1196 if (!init_drive_database(use_default_db))
2127e193
GI
1197 EXIT(FAILCMD);
1198
1199 return type;
832b75ed
GG
1200}
1201
cfbba5b9 1202// Printing function (controlled by global printing_is_off)
832b75ed
GG
1203// [From GLIBC Manual: Since the prototype doesn't specify types for
1204// optional arguments, in a call to a variadic function the default
1205// argument promotions are performed on the optional argument
1206// values. This means the objects of type char or short int (whether
1207// signed or not) are promoted to either int or unsigned int, as
1208// appropriate.]
4d59bff9 1209void pout(const char *fmt, ...){
832b75ed
GG
1210 va_list ap;
1211
1212 // initialize variable argument list
1213 va_start(ap,fmt);
cfbba5b9 1214 if (printing_is_off) {
832b75ed
GG
1215 va_end(ap);
1216 return;
1217 }
1218
1219 // print out
1220 vprintf(fmt,ap);
1221 va_end(ap);
1222 fflush(stdout);
1223 return;
1224}
1225
cfbba5b9
GI
1226// Globals to set failuretest() policy
1227bool failuretest_conservative = false;
1228unsigned char failuretest_permissive = 0;
832b75ed 1229
cfbba5b9
GI
1230// Compares failure type to policy in effect, and either exits or
1231// simply returns to the calling routine.
1232// Used in ataprint.cpp and scsiprint.cpp.
1233void failuretest(failure_type type, int returnvalue)
1234{
1235 // If this is an error in an "optional" SMART command
1236 if (type == OPTIONAL_CMD) {
1237 if (!failuretest_conservative)
1238 return;
1239 pout("An optional SMART command failed: exiting. Remove '-T conservative' option to continue.\n");
1240 EXIT(returnvalue);
1241 }
832b75ed 1242
cfbba5b9
GI
1243 // If this is an error in a "mandatory" SMART command
1244 if (type == MANDATORY_CMD) {
1245 if (failuretest_permissive--)
1246 return;
1247 pout("A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.\n");
1248 EXIT(returnvalue);
1249 }
1250
1251 throw std::logic_error("failuretest: Unknown type");
832b75ed
GG
1252}
1253
2127e193
GI
1254// Used to warn users about invalid checksums. Called from atacmds.cpp.
1255// Action to be taken may be altered by the user.
1256void checksumwarning(const char * string)
1257{
1258 // user has asked us to ignore checksum errors
1259 if (checksum_err_mode == CHECKSUM_ERR_IGNORE)
1260 return;
832b75ed 1261
2127e193 1262 pout("Warning! %s error: invalid SMART checksum.\n", string);
832b75ed 1263
2127e193
GI
1264 // user has asked us to fail on checksum errors
1265 if (checksum_err_mode == CHECKSUM_ERR_EXIT)
1266 EXIT(FAILSMART);
1267}
832b75ed 1268
2127e193
GI
1269// Return info string about device protocol
1270static const char * get_protocol_info(const smart_device * dev)
1271{
a86ec89e
GI
1272 switch ( (int)dev->is_ata()
1273 | ((int)dev->is_scsi() << 1)
1274 | ((int)dev->is_nvme() << 2)) {
2127e193
GI
1275 case 0x1: return "ATA";
1276 case 0x2: return "SCSI";
1277 case 0x3: return "ATA+SCSI";
a86ec89e 1278 case 0x4: return "NVMe";
2127e193
GI
1279 default: return "Unknown";
1280 }
1281}
832b75ed 1282
e9583e0c 1283// Device scan
cfbba5b9 1284// smartctl [-d type] --scan[-open] -- [PATTERN] [smartd directive ...]
a86ec89e 1285void scan_devices(const smart_devtype_list & types, bool with_open, char ** argv)
e9583e0c 1286{
a86ec89e 1287 bool dont_print = !(ata_debugmode || scsi_debugmode || nvme_debugmode);
cfbba5b9
GI
1288
1289 const char * pattern = 0;
1290 int ai = 0;
1291 if (argv[ai] && argv[ai][0] != '-')
1292 pattern = argv[ai++];
e9583e0c 1293
cfbba5b9
GI
1294 smart_device_list devlist;
1295 printing_is_off = dont_print;
a86ec89e 1296 bool ok = smi()->scan_smart_devices(devlist, types, pattern);
cfbba5b9 1297 printing_is_off = false;
e9583e0c
GI
1298
1299 if (!ok) {
cfbba5b9 1300 pout("# scan_smart_devices: %s\n", smi()->get_errmsg());
e9583e0c
GI
1301 return;
1302 }
1303
1304 for (unsigned i = 0; i < devlist.size(); i++) {
cfbba5b9 1305 smart_device_auto_ptr dev( devlist.release(i) );
e9583e0c 1306
e9583e0c 1307 if (with_open) {
cfbba5b9
GI
1308 printing_is_off = dont_print;
1309 dev.replace ( dev->autodetect_open() );
1310 printing_is_off = false;
e9583e0c 1311
cfbba5b9
GI
1312 if (!dev->is_open()) {
1313 pout("# %s -d %s # %s, %s device open failed: %s\n", dev->get_dev_name(),
1314 dev->get_dev_type(), dev->get_info_name(),
1315 get_protocol_info(dev.get()), dev->get_errmsg());
1316 continue;
1317 }
1318 }
1319
1320 pout("%s -d %s", dev->get_dev_name(), dev->get_dev_type());
1321 if (!argv[ai])
1322 pout(" # %s, %s device\n", dev->get_info_name(), get_protocol_info(dev.get()));
1323 else {
1324 for (int j = ai; argv[j]; j++)
1325 pout(" %s", argv[j]);
1326 pout("\n");
e9583e0c
GI
1327 }
1328
e9583e0c
GI
1329 if (dev->is_open())
1330 dev->close();
1331 }
1332}
1333
2127e193 1334// Main program without exception handling
cfbba5b9 1335static int main_worker(int argc, char **argv)
2127e193 1336{
d2e702cf
GI
1337 // Throw if runtime environment does not match compile time test.
1338 check_config();
e9583e0c 1339
2127e193
GI
1340 // Initialize interface
1341 smart_interface::init();
1342 if (!smi())
1343 return 1;
1344
bed94269
GI
1345 // Parse input arguments
1346 ata_print_options ataopts;
1347 scsi_print_options scsiopts;
a86ec89e 1348 nvme_print_options nvmeopts;
d008864d 1349 bool print_type_only = false;
a86ec89e 1350 const char * type = parse_options(argc, argv, ataopts, scsiopts, nvmeopts, print_type_only);
bed94269
GI
1351
1352 const char * name = argv[argc-1];
1353
1354 smart_device_auto_ptr dev;
1355 if (!strcmp(name,"-")) {
1356 // Parse "smartctl -r ataioctl,2 ..." output from stdin
1357 if (type || print_type_only) {
ee38a438 1358 pout("-d option is not allowed in conjunction with device name \"-\".\n");
a37e7145
GG
1359 UsageSummary();
1360 return FAILCMD;
1361 }
bed94269
GI
1362 dev = get_parsed_ata_device(smi(), name);
1363 }
1364 else
1365 // get device of appropriate type
1366 dev = smi()->get_smart_device(name, type);
1367
1368 if (!dev) {
1369 pout("%s: %s\n", name, smi()->get_errmsg());
1370 if (type)
1371 printvalidarglistmessage('d');
1372 else
ee38a438 1373 pout("Please specify device type with the -d option.\n");
bed94269
GI
1374 UsageSummary();
1375 return FAILCMD;
1376 }
a37e7145 1377
bed94269
GI
1378 if (print_type_only)
1379 // Report result of first autodetection
1380 pout("%s: Device of type '%s' [%s] detected\n",
1381 dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
2127e193 1382
a86ec89e 1383 if (dev->is_ata() && ataopts.powermode>=2 && dev->is_powered_down()) {
f9e10201
JD
1384 pout("Device is in STANDBY (OS) mode, exit(%d)\n", ataopts.powerexit);
1385 return ataopts.powerexit;
a86ec89e
GI
1386 }
1387
bed94269
GI
1388 // Open device
1389 {
1390 // Save old info
1391 smart_device::device_info oldinfo = dev->get_info();
2127e193 1392
bed94269
GI
1393 // Open with autodetect support, may return 'better' device
1394 dev.replace( dev->autodetect_open() );
2127e193 1395
bed94269 1396 // Report if type has changed
a86ec89e
GI
1397 if ( (ata_debugmode || scsi_debugmode || nvme_debugmode || print_type_only)
1398 && oldinfo.dev_type != dev->get_dev_type() )
bed94269
GI
1399 pout("%s: Device open changed type from '%s' to '%s'\n",
1400 dev->get_info_name(), oldinfo.dev_type.c_str(), dev->get_dev_type());
2127e193 1401 }
bed94269
GI
1402 if (!dev->is_open()) {
1403 pout("Smartctl open device: %s failed: %s\n", dev->get_info_name(), dev->get_errmsg());
1404 return FAILDEV;
832b75ed 1405 }
bed94269
GI
1406
1407 // now call appropriate ATA or SCSI routine
1408 int retval = 0;
1409 if (print_type_only)
1410 pout("%s: Device of type '%s' [%s] opened\n",
1411 dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
1412 else if (dev->is_ata())
1413 retval = ataPrintMain(dev->to_ata(), ataopts);
1414 else if (dev->is_scsi())
1415 retval = scsiPrintMain(dev->to_scsi(), scsiopts);
a86ec89e
GI
1416 else if (dev->is_nvme())
1417 retval = nvmePrintMain(dev->to_nvme(), nvmeopts);
bed94269
GI
1418 else
1419 // we should never fall into this branch!
a86ec89e 1420 pout("%s: Neither ATA, SCSI nor NVMe device\n", dev->get_info_name());
bed94269
GI
1421
1422 dev->close();
2127e193
GI
1423 return retval;
1424}
832b75ed 1425
2127e193
GI
1426
1427// Main program
1428int main(int argc, char **argv)
1429{
1430 int status;
a86ec89e
GI
1431 bool badcode = false;
1432
2127e193
GI
1433 try {
1434 // Do the real work ...
1435 status = main_worker(argc, argv);
832b75ed 1436 }
2127e193
GI
1437 catch (int ex) {
1438 // EXIT(status) arrives here
1439 status = ex;
832b75ed 1440 }
2127e193
GI
1441 catch (const std::bad_alloc & /*ex*/) {
1442 // Memory allocation failed (also thrown by std::operator new)
bed94269 1443 printf("Smartctl: Out of memory\n");
2127e193 1444 status = FAILCMD;
832b75ed 1445 }
2127e193
GI
1446 catch (const std::exception & ex) {
1447 // Other fatal errors
bed94269 1448 printf("Smartctl: Exception: %s\n", ex.what());
a86ec89e 1449 badcode = true;
2127e193 1450 status = FAILCMD;
832b75ed 1451 }
a86ec89e
GI
1452
1453 // Check for remaining device objects
1454 if (smart_device::get_num_objects() != 0) {
1455 printf("Smartctl: Internal Error: %d device object(s) left at exit.\n",
1456 smart_device::get_num_objects());
1457 badcode = true;
1458 status = FAILCMD;
1459 }
1460
1461 if (badcode)
1462 printf("Please inform " PACKAGE_BUGREPORT ", including output of smartctl -V.\n");
1463
2127e193 1464 return status;
832b75ed 1465}
2127e193 1466