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