smartmontools  SVN Rev 4347
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-16 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 4334 2016-08-17 21:37:48Z 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, --nocheck=MODE (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, standby, idle";
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  else if (!strcmp(optarg, "sleep"))
806  ataopts.powermode = 2;
807  else if (!strcmp(optarg, "standby"))
808  ataopts.powermode = 3;
809  else if (!strcmp(optarg, "idle"))
810  ataopts.powermode = 4;
811  else
812  badarg = true;
813  break;
814  case 'f':
815  if (!strcmp(optarg, "old")) {
816  ataopts.output_format &= ~ata_print_options::FMT_BRIEF;
817  output_format_set = true;
818  }
819  else if (!strcmp(optarg, "brief")) {
821  output_format_set = true;
822  }
823  else if (!strcmp(optarg, "hex"))
826  else if (!strcmp(optarg, "hex,id"))
828  else if (!strcmp(optarg, "hex,val"))
830  else
831  badarg = true;
832  break;
833  case 'B':
834  {
835  const char * path = optarg;
836  if (*path == '+' && path[1])
837  path++;
838  else
839  use_default_db = false;
840  if (!read_drive_database(path))
841  EXIT(FAILCMD);
842  }
843  break;
844  case 'h':
845  printing_is_off = false;
846  printslogan();
847  Usage();
848  EXIT(0);
849  break;
850 
851  case 'g':
852  case_s_continued: // -s, see above
853  case opt_set: // --set
854  {
855  ataopts.get_set_used = true;
856  bool get = (optchar == 'g');
857  char name[16+1]; unsigned val;
858  int n1 = -1, n2 = -1, n3 = -1, len = strlen(optarg);
859  if (sscanf(optarg, "%16[^,=]%n%*[,=]%n%u%n", name, &n1, &n2, &val, &n3) >= 1
860  && (n1 == len || (!get && n2 > 0))) {
861  bool on = false;
862  bool off = false;
863  bool ata = false;
864  bool persistent = false;
865 
866  if (n2 > 0) {
867  int len2 = strlen(optarg + n2);
868  char * tmp = strstr(optarg+n2, ",p");
869  // handle ",p" in persistent options like: wcache-sct,[ata|on|off],p
870  if (tmp && (strlen(tmp) == 2)) {
871  persistent = true;
872  len2 = strlen(optarg+n2) - 2;
873 
874  // the ,p option only works for set of SCT Feature Control command
875  if (strcmp(name, "wcache-sct") != 0 &&
876  strcmp(name, "wcreorder") != 0)
877  badarg = true;
878  }
879  on = !strncmp(optarg+n2, "on", len2);
880  off = !strncmp(optarg+n2, "off", len2);
881  ata = !strncmp(optarg+n2, "ata", len2);
882  }
883  if (n3 != len)
884  val = ~0U;
885 
886  if (get && !strcmp(name, "all")) {
887  ataopts.get_aam = ataopts.get_apm = true;
888  ataopts.get_security = true;
889  ataopts.get_lookahead = ataopts.get_wcache = true;
890  scsiopts.get_rcd = scsiopts.get_wce = true;
891  }
892  else if (!strcmp(name, "aam")) {
893  if (get)
894  ataopts.get_aam = true;
895  else if (off)
896  ataopts.set_aam = -1;
897  else if (val <= 254)
898  ataopts.set_aam = val + 1;
899  else {
900  snprintf(extraerror, sizeof(extraerror), "Option -s aam,N must have 0 <= N <= 254\n");
901  badarg = true;
902  }
903  }
904  else if (!strcmp(name, "apm")) {
905  if (get)
906  ataopts.get_apm = true;
907  else if (off)
908  ataopts.set_apm = -1;
909  else if (1 <= val && val <= 254)
910  ataopts.set_apm = val + 1;
911  else {
912  snprintf(extraerror, sizeof(extraerror), "Option -s apm,N must have 1 <= N <= 254\n");
913  badarg = true;
914  }
915  }
916  else if (!strcmp(name, "lookahead")) {
917  if (get) {
918  ataopts.get_lookahead = true;
919  }
920  else if (off)
921  ataopts.set_lookahead = -1;
922  else if (on)
923  ataopts.set_lookahead = 1;
924  else
925  badarg = true;
926  }
927  else if (!strcmp(name, "wcreorder")) {
928  ataopts.sct_wcache_reorder_set_pers = persistent;
929  if (get) {
930  ataopts.sct_wcache_reorder_get = true;
931  }
932  else if (off)
933  ataopts.sct_wcache_reorder_set = -1;
934  else if (on)
935  ataopts.sct_wcache_reorder_set = 1;
936  else
937  badarg = true;
938  }
939  else if (!strcmp(name, "wcache-sct")) {
940  ataopts.sct_wcache_sct_set_pers = persistent;
941  if (get) {
942  ataopts.sct_wcache_sct_get = true;
943  }
944  else if (off)
945  ataopts.sct_wcache_sct_set = 3;
946  else if (on)
947  ataopts.sct_wcache_sct_set = 2;
948  else if (ata)
949  ataopts.sct_wcache_sct_set = 1;
950  else
951  badarg = true;
952  }
953  else if (!strcmp(name, "rcache")) {
954  if (get)
955  scsiopts.get_rcd = true;
956  else if (off)
957  scsiopts.set_rcd = -1;
958  else if (on)
959  scsiopts.set_rcd = 1;
960  else
961  badarg = true;
962  }
963  else if (get && !strcmp(name, "security")) {
964  ataopts.get_security = true;
965  }
966  else if (!get && !strcmp(optarg, "security-freeze")) {
967  ataopts.set_security_freeze = true;
968  }
969  else if (!get && !strcmp(optarg, "standby,now")) {
970  ataopts.set_standby_now = true;
971  }
972  else if (!get && !strcmp(name, "standby")) {
973  if (off)
974  ataopts.set_standby = 0 + 1;
975  else if (val <= 255)
976  ataopts.set_standby = val + 1;
977  else {
978  snprintf(extraerror, sizeof(extraerror), "Option -s standby,N must have 0 <= N <= 255\n");
979  badarg = true;
980  }
981  }
982  else if (!strcmp(name, "wcache")) {
983  if (get) {
984  ataopts.get_wcache = true;
985  scsiopts.get_wce = true;
986  }
987  else if (off) {
988  ataopts.set_wcache = -1;
989  scsiopts.set_wce = -1;
990  }
991  else if (on) {
992  ataopts.set_wcache = 1;
993  scsiopts.set_wce = 1;
994  }
995  else
996  badarg = true;
997  }
998  else
999  badarg = true;
1000  }
1001  else
1002  badarg = true;
1003  }
1004  break;
1005 
1006  case opt_scan:
1007  case opt_scan_open:
1008  scan = optchar;
1009  break;
1010 
1011  case '?':
1012  default:
1013  printing_is_off = false;
1014  printslogan();
1015  // Point arg to the argument in which this option was found.
1016  arg = argv[optind-1];
1017  // Check whether the option is a long option that doesn't map to -h.
1018  if (arg[1] == '-' && optchar != 'h') {
1019  // Iff optopt holds a valid option then argument must be missing.
1020  if (optopt && (optopt >= opt_scan || strchr(shortopts, optopt))) {
1021  pout("=======> ARGUMENT REQUIRED FOR OPTION: %s\n", arg+2);
1022  printvalidarglistmessage(optopt);
1023  } else
1024  pout("=======> UNRECOGNIZED OPTION: %s\n",arg+2);
1025  if (extraerror[0])
1026  pout("=======> %s", extraerror);
1027  UsageSummary();
1028  EXIT(FAILCMD);
1029  }
1030  if (0 < optopt && optopt < '~') {
1031  // Iff optopt holds a valid option then argument must be
1032  // missing. Note (BA) this logic seems to fail using Solaris
1033  // getopt!
1034  if (strchr(shortopts, optopt) != NULL) {
1035  pout("=======> ARGUMENT REQUIRED FOR OPTION: %c\n", optopt);
1036  printvalidarglistmessage(optopt);
1037  } else
1038  pout("=======> UNRECOGNIZED OPTION: %c\n",optopt);
1039  if (extraerror[0])
1040  pout("=======> %s", extraerror);
1041  UsageSummary();
1042  EXIT(FAILCMD);
1043  }
1044  Usage();
1045  EXIT(0);
1046  } // closes switch statement to process command-line options
1047 
1048  // Check to see if option had an unrecognized or incorrect argument.
1049  if (badarg) {
1050  printslogan();
1051  // It would be nice to print the actual option name given by the user
1052  // here, but we just print the short form. Please fix this if you know
1053  // a clean way to do it.
1054  char optstr[] = { (char)optchar, 0 };
1055  pout("=======> INVALID ARGUMENT TO -%s: %s\n",
1056  (optchar == opt_identify ? "-identify" :
1057  optchar == opt_set ? "-set" :
1058  optchar == opt_smart ? "-smart" : optstr), optarg);
1059  printvalidarglistmessage(optchar);
1060  if (extraerror[0])
1061  pout("=======> %s", extraerror);
1062  UsageSummary();
1063  EXIT(FAILCMD);
1064  }
1065  }
1066 
1067  // Special handling of --scan, --scanopen
1068  if (scan) {
1069  // Read or init drive database to allow USB ID check.
1070  if (!init_drive_database(use_default_db))
1071  EXIT(FAILCMD);
1072  scan_devices(scan_types, (scan == opt_scan_open), argv + optind);
1073  EXIT(0);
1074  }
1075 
1076  // At this point we have processed all command-line options. If the
1077  // print output is switchable, then start with the print output
1078  // turned off
1080  printing_is_off = true;
1081 
1082  // Check for multiple -d TYPE options
1083  if (scan_types.size() > 1) {
1084  printing_is_off = false;
1085  printslogan();
1086  pout("ERROR: multiple -d TYPE options are only allowed with --scan\n");
1087  UsageSummary();
1088  EXIT(FAILCMD);
1089  }
1090 
1091  // error message if user has asked for more than one test
1092  if (testcnt > 1) {
1093  printing_is_off = false;
1094  printslogan();
1095  pout("\nERROR: smartctl can only run a single test type (or abort) at a time.\n");
1096  UsageSummary();
1097  EXIT(FAILCMD);
1098  }
1099 
1100  // error message if user has set selective self-test options without
1101  // asking for a selective self-test
1103  && !ataopts.smart_selective_args.num_spans) {
1104  printing_is_off = false;
1105  printslogan();
1106  if (ataopts.smart_selective_args.pending_time)
1107  pout("\nERROR: smartctl -t pending,N must be used with -t select,N-M.\n");
1108  else
1109  pout("\nERROR: smartctl -t afterselect,(on|off) must be used with -t select,N-M.\n");
1110  UsageSummary();
1111  EXIT(FAILCMD);
1112  }
1113 
1114  // If captive option was used, change test type if appropriate.
1115  if (captive)
1116  switch (ataopts.smart_selftest_type) {
1117  case SHORT_SELF_TEST:
1119  scsiopts.smart_short_selftest = false;
1120  scsiopts.smart_short_cap_selftest = true;
1121  break;
1122  case EXTEND_SELF_TEST:
1124  scsiopts.smart_extend_selftest = false;
1125  scsiopts.smart_extend_cap_selftest = true;
1126  break;
1127  case CONVEYANCE_SELF_TEST:
1129  break;
1130  case SELECTIVE_SELF_TEST:
1132  break;
1133  }
1134 
1135  // From here on, normal operations...
1136  printslogan();
1137 
1138  // Warn if the user has provided no device name
1139  if (argc-optind<1){
1140  pout("ERROR: smartctl requires a device name as the final command-line argument.\n\n");
1141  UsageSummary();
1142  EXIT(FAILCMD);
1143  }
1144 
1145  // Warn if the user has provided more than one device name
1146  if (argc-optind>1){
1147  int i;
1148  pout("ERROR: smartctl takes ONE device name as the final command-line argument.\n");
1149  pout("You have provided %d device names:\n",argc-optind);
1150  for (i=0; i<argc-optind; i++)
1151  pout("%s\n",argv[optind+i]);
1152  UsageSummary();
1153  EXIT(FAILCMD);
1154  }
1155 
1156  // Read or init drive database
1157  if (!init_drive_database(use_default_db))
1158  EXIT(FAILCMD);
1159 
1160  return type;
1161 }
1162 
1163 // Printing function (controlled by global printing_is_off)
1164 // [From GLIBC Manual: Since the prototype doesn't specify types for
1165 // optional arguments, in a call to a variadic function the default
1166 // argument promotions are performed on the optional argument
1167 // values. This means the objects of type char or short int (whether
1168 // signed or not) are promoted to either int or unsigned int, as
1169 // appropriate.]
1170 void pout(const char *fmt, ...){
1171  va_list ap;
1172 
1173  // initialize variable argument list
1174  va_start(ap,fmt);
1175  if (printing_is_off) {
1176  va_end(ap);
1177  return;
1178  }
1179 
1180  // print out
1181  vprintf(fmt,ap);
1182  va_end(ap);
1183  fflush(stdout);
1184  return;
1185 }
1186 
1187 // Globals to set failuretest() policy
1189 unsigned char failuretest_permissive = 0;
1190 
1191 // Compares failure type to policy in effect, and either exits or
1192 // simply returns to the calling routine.
1193 // Used in ataprint.cpp and scsiprint.cpp.
1194 void failuretest(failure_type type, int returnvalue)
1195 {
1196  // If this is an error in an "optional" SMART command
1197  if (type == OPTIONAL_CMD) {
1198  if (!failuretest_conservative)
1199  return;
1200  pout("An optional SMART command failed: exiting. Remove '-T conservative' option to continue.\n");
1201  EXIT(returnvalue);
1202  }
1203 
1204  // If this is an error in a "mandatory" SMART command
1205  if (type == MANDATORY_CMD) {
1206  if (failuretest_permissive--)
1207  return;
1208  pout("A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.\n");
1209  EXIT(returnvalue);
1210  }
1211 
1212  throw std::logic_error("failuretest: Unknown type");
1213 }
1214 
1215 // Used to warn users about invalid checksums. Called from atacmds.cpp.
1216 // Action to be taken may be altered by the user.
1217 void checksumwarning(const char * string)
1218 {
1219  // user has asked us to ignore checksum errors
1221  return;
1222 
1223  pout("Warning! %s error: invalid SMART checksum.\n", string);
1224 
1225  // user has asked us to fail on checksum errors
1227  EXIT(FAILSMART);
1228 }
1229 
1230 // Return info string about device protocol
1231 static const char * get_protocol_info(const smart_device * dev)
1232 {
1233  switch ( (int)dev->is_ata()
1234  | ((int)dev->is_scsi() << 1)
1235  | ((int)dev->is_nvme() << 2)) {
1236  case 0x1: return "ATA";
1237  case 0x2: return "SCSI";
1238  case 0x3: return "ATA+SCSI";
1239  case 0x4: return "NVMe";
1240  default: return "Unknown";
1241  }
1242 }
1243 
1244 // Device scan
1245 // smartctl [-d type] --scan[-open] -- [PATTERN] [smartd directive ...]
1246 void scan_devices(const smart_devtype_list & types, bool with_open, char ** argv)
1247 {
1248  bool dont_print = !(ata_debugmode || scsi_debugmode || nvme_debugmode);
1249 
1250  const char * pattern = 0;
1251  int ai = 0;
1252  if (argv[ai] && argv[ai][0] != '-')
1253  pattern = argv[ai++];
1254 
1255  smart_device_list devlist;
1256  printing_is_off = dont_print;
1257  bool ok = smi()->scan_smart_devices(devlist, types, pattern);
1258  printing_is_off = false;
1259 
1260  if (!ok) {
1261  pout("# scan_smart_devices: %s\n", smi()->get_errmsg());
1262  return;
1263  }
1264 
1265  for (unsigned i = 0; i < devlist.size(); i++) {
1266  smart_device_auto_ptr dev( devlist.release(i) );
1267 
1268  if (with_open) {
1269  printing_is_off = dont_print;
1270  dev.replace ( dev->autodetect_open() );
1271  printing_is_off = false;
1272 
1273  if (!dev->is_open()) {
1274  pout("# %s -d %s # %s, %s device open failed: %s\n", dev->get_dev_name(),
1275  dev->get_dev_type(), dev->get_info_name(),
1276  get_protocol_info(dev.get()), dev->get_errmsg());
1277  continue;
1278  }
1279  }
1280 
1281  pout("%s -d %s", dev->get_dev_name(), dev->get_dev_type());
1282  if (!argv[ai])
1283  pout(" # %s, %s device\n", dev->get_info_name(), get_protocol_info(dev.get()));
1284  else {
1285  for (int j = ai; argv[j]; j++)
1286  pout(" %s", argv[j]);
1287  pout("\n");
1288  }
1289 
1290  if (dev->is_open())
1291  dev->close();
1292  }
1293 }
1294 
1295 // Main program without exception handling
1296 static int main_worker(int argc, char **argv)
1297 {
1298  // Throw if runtime environment does not match compile time test.
1299  check_config();
1300 
1301  // Initialize interface
1303  if (!smi())
1304  return 1;
1305 
1306  // Parse input arguments
1307  ata_print_options ataopts;
1308  scsi_print_options scsiopts;
1309  nvme_print_options nvmeopts;
1310  bool print_type_only = false;
1311  const char * type = parse_options(argc, argv, ataopts, scsiopts, nvmeopts, print_type_only);
1312 
1313  const char * name = argv[argc-1];
1314 
1316  if (!strcmp(name,"-")) {
1317  // Parse "smartctl -r ataioctl,2 ..." output from stdin
1318  if (type || print_type_only) {
1319  pout("-d option is not allowed in conjunction with device name \"-\".\n");
1320  UsageSummary();
1321  return FAILCMD;
1322  }
1323  dev = get_parsed_ata_device(smi(), name);
1324  }
1325  else
1326  // get device of appropriate type
1327  dev = smi()->get_smart_device(name, type);
1328 
1329  if (!dev) {
1330  pout("%s: %s\n", name, smi()->get_errmsg());
1331  if (type)
1333  else
1334  pout("Please specify device type with the -d option.\n");
1335  UsageSummary();
1336  return FAILCMD;
1337  }
1338 
1339  if (print_type_only)
1340  // Report result of first autodetection
1341  pout("%s: Device of type '%s' [%s] detected\n",
1342  dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
1343 
1344  if (dev->is_ata() && ataopts.powermode>=2 && dev->is_powered_down()) {
1345  pout( "%s: Device is in %s mode, exit(%d)\n", dev->get_info_name(), "STANDBY (OS)", FAILPOWER );
1346  return FAILPOWER;
1347  }
1348 
1349  // Open device
1350  {
1351  // Save old info
1352  smart_device::device_info oldinfo = dev->get_info();
1353 
1354  // Open with autodetect support, may return 'better' device
1355  dev.replace( dev->autodetect_open() );
1356 
1357  // Report if type has changed
1358  if ( (ata_debugmode || scsi_debugmode || nvme_debugmode || print_type_only)
1359  && oldinfo.dev_type != dev->get_dev_type() )
1360  pout("%s: Device open changed type from '%s' to '%s'\n",
1361  dev->get_info_name(), oldinfo.dev_type.c_str(), dev->get_dev_type());
1362  }
1363  if (!dev->is_open()) {
1364  pout("Smartctl open device: %s failed: %s\n", dev->get_info_name(), dev->get_errmsg());
1365  return FAILDEV;
1366  }
1367 
1368  // now call appropriate ATA or SCSI routine
1369  int retval = 0;
1370  if (print_type_only)
1371  pout("%s: Device of type '%s' [%s] opened\n",
1372  dev->get_info_name(), dev->get_dev_type(), get_protocol_info(dev.get()));
1373  else if (dev->is_ata())
1374  retval = ataPrintMain(dev->to_ata(), ataopts);
1375  else if (dev->is_scsi())
1376  retval = scsiPrintMain(dev->to_scsi(), scsiopts);
1377  else if (dev->is_nvme())
1378  retval = nvmePrintMain(dev->to_nvme(), nvmeopts);
1379  else
1380  // we should never fall into this branch!
1381  pout("%s: Neither ATA, SCSI nor NVMe device\n", dev->get_info_name());
1382 
1383  dev->close();
1384  return retval;
1385 }
1386 
1387 
1388 // Main program
1389 int main(int argc, char **argv)
1390 {
1391  int status;
1392  bool badcode = false;
1393 
1394  try {
1395  // Do the real work ...
1396  status = main_worker(argc, argv);
1397  }
1398  catch (int ex) {
1399  // EXIT(status) arrives here
1400  status = ex;
1401  }
1402  catch (const std::bad_alloc & /*ex*/) {
1403  // Memory allocation failed (also thrown by std::operator new)
1404  printf("Smartctl: Out of memory\n");
1405  status = FAILCMD;
1406  }
1407  catch (const std::exception & ex) {
1408  // Other fatal errors
1409  printf("Smartctl: Exception: %s\n", ex.what());
1410  badcode = true;
1411  status = FAILCMD;
1412  }
1413 
1414  // Check for remaining device objects
1415  if (smart_device::get_num_objects() != 0) {
1416  printf("Smartctl: Internal Error: %d device object(s) left at exit.\n",
1418  badcode = true;
1419  status = FAILCMD;
1420  }
1421 
1422  if (badcode)
1423  printf("Please inform " PACKAGE_BUGREPORT ", including output of smartctl -V.\n");
1424 
1425  return status;
1426 }
1427 
#define CONVEYANCE_CAPTIVE_SELF_TEST
Definition: atacmds.h:119
checksum_err_mode_t
Definition: smartctl.cpp:260
int main(int argc, char **argv)
Definition: smartctl.cpp:1389
#define PRIu64
Definition: int64.h:76
static void UsageSummary()
Definition: smartctl.cpp:67
unsigned char failuretest_permissive
Definition: smartctl.cpp:1189
u16 s[6]
Definition: megaraid.h:97
bool sct_wcache_sct_get
Definition: ataprint.h:112
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:114
static int main_worker(int argc, char **argv)
Definition: smartctl.cpp:1296
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:109
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:113
#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:1188
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:115
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:1217
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:106
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:116
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:1170
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:111
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:3018
bool sct_wcache_reorder_set_pers
Definition: ataprint.h:111
int ataPrintMain(ata_device *device, const ata_print_options &options)
Definition: ataprint.cpp:2527
Device info strings.
Definition: dev_interface.h:44
bool smart_auto_offl_disable
Definition: ataprint.h:74
#define CONVEYANCE_SELF_TEST
Definition: atacmds.h:114
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:118
#define SELECTIVE_CAPTIVE_SELF_TEST
Definition: atacmds.h:120
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:113
Base class for all devices.
Definition: dev_interface.h:39
bool ignore_presets
Definition: ataprint.h:92
bool set_standby_now
Definition: ataprint.h:104
#define SHORT_SELF_TEST
Definition: atacmds.h:112
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:1231
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:1246
void failuretest(failure_type type, int returnvalue)
Definition: smartctl.cpp:1194
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:110
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:117
bool smart_auto_offl_enable
Definition: ataprint.h:74
bool smart_vendor_attrib
Definition: scsiprint.h:39