4 * Home page of code is: http://www.smartmontools.org
6 * Copyright (C) 2002-11 Bruce Allen
7 * Copyright (C) 2008-18 Christian Franke
8 * Copyright (C) 2000 Michael Cornwell <cornwell@acm.org>
10 * SPDX-License-Identifier: GPL-2.0-or-later
14 #define __STDC_FORMAT_MACROS 1 // enable PRI* for C++
19 #include <sys/types.h>
30 #if defined(__FreeBSD__)
31 #include <sys/param.h>
35 #include "dev_interface.h"
37 #include "knowndrives.h"
39 #include "scsiprint.h"
40 #include "nvmeprint.h"
43 #include "svnversion.h"
45 const char * smartctl_cpp_cvsid
= "$Id: smartctl.cpp 4871 2018-12-27 20:03:12Z chrfranke $"
46 CONFIG_H_CVSID SMARTCTL_H_CVSID
;
48 // Globals to control printing
49 bool printing_is_switchable
= false;
50 bool printing_is_off
= false;
52 // Control JSON output
54 static bool print_as_json
= false;
55 static json::print_options print_as_json_options
;
56 static bool print_as_json_output
= false;
57 static bool print_as_json_impl
= false;
58 static bool print_as_json_unimpl
= false;
60 static void printslogan()
62 jout("%s\n", format_version_info("smartctl").c_str());
65 static void UsageSummary()
67 pout("\nUse smartctl -h to get a usage summary\n\n");
71 static void js_initialize(int argc
, char **argv
, bool verbose
)
73 if (jglb
.is_enabled())
79 // Major.minor version of JSON format
80 jglb
["json_format_version"][0] = 1;
81 jglb
["json_format_version"][1] = 0;
83 // Smartctl version info
84 json::ref jref
= jglb
["smartctl"];
85 int ver
[3] = { 0, 0, 0 };
86 sscanf(PACKAGE_VERSION
, "%d.%d.%d", ver
, ver
+1, ver
+2);
87 jref
["version"][0] = ver
[0];
88 jref
["version"][1] = ver
[1];
90 jref
["version"][2] = ver
[2];
92 #ifdef SMARTMONTOOLS_SVN_REV
93 jref
["svn_revision"] = SMARTMONTOOLS_SVN_REV
;
95 jref
["platform_info"] = smi()->get_os_version_str();
97 jref
["build_info"] = BUILD_INFO
;
100 jref
["argv"][0] = "smartctl";
101 for (int i
= 1; i
< argc
; i
++)
102 jref
["argv"][i
] = argv
[i
];
105 static std::string
getvalidarglist(int opt
);
107 /* void prints help information for command syntax */
110 pout("Usage: smartctl [options] device\n\n");
112 "============================================ SHOW INFORMATION OPTIONS =====\n\n"
113 " -h, --help, --usage\n"
114 " Display this help and exit\n\n"
115 " -V, --version, --copyright, --license\n"
116 " Print license, copyright, and version information and exit\n\n"
118 " Show identity information for device\n\n"
119 " --identify[=[w][nvb]]\n"
120 " Show words and bits from IDENTIFY DEVICE data (ATA)\n\n"
121 " -g NAME, --get=NAME\n"
122 " Get device setting: all, aam, apm, dsn, lookahead, security,\n"
123 " wcache, rcache, wcreorder, wcache-sct\n\n"
125 " Show all SMART information for device\n\n"
127 " Show all information for device\n\n"
129 " Scan for devices\n\n"
131 " Scan for devices and try to open each device\n\n"
134 "================================== SMARTCTL RUN-TIME BEHAVIOR OPTIONS =====\n\n"
135 " -j, --json[=[cgiosuv]]\n"
136 " Print output in JSON format\n\n"
137 " -q TYPE, --quietmode=TYPE (ATA)\n"
138 " Set smartctl quiet mode to one of: errorsonly, silent, noserial\n\n"
139 " -d TYPE, --device=TYPE\n"
140 " Specify device type to one of:\n"
141 " %s\n\n" // TODO: fold this string
142 " -T TYPE, --tolerance=TYPE (ATA)\n"
143 " Tolerance: normal, conservative, permissive, verypermissive\n\n"
144 " -b TYPE, --badsum=TYPE (ATA)\n"
145 " Set action on bad checksum to one of: warn, exit, ignore\n\n"
146 " -r TYPE, --report=TYPE\n"
147 " Report transactions (see man page)\n\n"
148 " -n MODE[,STATUS], --nocheck=MODE[,STATUS] (ATA)\n"
149 " No check if: never, sleep, standby, idle (see man page)\n\n",
150 getvalidarglist('d').c_str()); // TODO: Use this function also for other options ?
152 "============================== DEVICE FEATURE ENABLE/DISABLE COMMANDS =====\n\n"
153 " -s VALUE, --smart=VALUE\n"
154 " Enable/disable SMART on device (on/off)\n\n"
155 " -o VALUE, --offlineauto=VALUE (ATA)\n"
156 " Enable/disable automatic offline testing on device (on/off)\n\n"
157 " -S VALUE, --saveauto=VALUE (ATA)\n"
158 " Enable/disable Attribute autosave on device (on/off)\n\n"
159 " -s NAME[,VALUE], --set=NAME[,VALUE]\n"
160 " Enable/disable/change device setting: aam,[N|off], apm,[N|off],\n"
161 " dsn,[on|off], lookahead,[on|off], security-freeze,\n"
162 " standby,[N|off|now], wcache,[on|off], rcache,[on|off],\n"
163 " wcreorder,[on|off[,p]], wcache-sct,[ata|on|off[,p]]\n\n"
166 "======================================= READ AND DISPLAY DATA OPTIONS =====\n\n"
168 " Show device SMART health status\n\n"
169 " -c, --capabilities (ATA, NVMe)\n"
170 " Show device SMART capabilities\n\n"
171 " -A, --attributes\n"
172 " Show device SMART vendor-specific Attributes and values\n\n"
173 " -f FORMAT, --format=FORMAT (ATA)\n"
174 " Set output format for attributes: old, brief, hex[,id|val]\n\n"
175 " -l TYPE, --log=TYPE\n"
176 " Show device log. TYPE: error, selftest, selective, directory[,g|s],\n"
177 " xerror[,N][,error], xselftest[,N][,selftest], background,\n"
178 " sasphy[,reset], sataphy[,reset], scttemp[sts,hist],\n"
179 " scttempint,N[,p], scterc[,N,M], devstat[,N], defects[,N], ssd,\n"
180 " gplog,N[,RANGE], smartlog,N[,RANGE], nvmelog,N,SIZE\n\n"
181 " -v N,OPTION , --vendorattribute=N,OPTION (ATA)\n"
182 " Set display OPTION for vendor Attribute N (see man page)\n\n"
183 " -F TYPE, --firmwarebug=TYPE (ATA)\n"
184 " Use firmware bug workaround:\n"
186 " -P TYPE, --presets=TYPE (ATA)\n"
187 " Drive-specific presets: use, ignore, show, showall\n\n"
188 " -B [+]FILE, --drivedb=[+]FILE (ATA)\n"
189 " Read and replace [add] drive database from FILE\n"
191 get_valid_firmwarebug_args(),
192 get_drivedb_path_add()
194 #ifdef SMARTMONTOOLS_DRIVEDBDIR
198 get_drivedb_path_default()
203 "============================================ DEVICE SELF-TEST OPTIONS =====\n\n"
204 " -t TEST, --test=TEST\n"
205 " Run test. TEST: offline, short, long, conveyance, force, vendor,N,\n"
206 " select,M-N, pending,N, afterselect,[on|off]\n\n"
208 " Do test in captive mode (along with -t)\n\n"
210 " Abort any non-captive test on device\n\n"
212 std::string examples
= smi()->get_app_examples("smartctl");
213 if (!examples
.empty())
214 pout("%s\n", examples
.c_str());
217 // Values for --long only options, see parse_options()
218 enum { opt_identify
= 1000, opt_scan
, opt_scan_open
, opt_set
, opt_smart
};
220 /* Returns a string containing a formatted list of the valid arguments
221 to the option opt or empty on failure. Note 'v' case different */
222 static std::string
getvalidarglist(int opt
)
226 return "errorsonly, silent, noserial";
228 return smi()->get_valid_dev_types_str() + ", auto, test";
230 return "normal, conservative, permissive, verypermissive";
232 return "warn, exit, ignore";
234 return "[+]<FILE_NAME>";
236 return "ioctl[,N], ataioctl[,N], scsiioctl[,N], nvmeioctl[,N]";
242 return "error, selftest, selective, directory[,g|s], "
243 "xerror[,N][,error], xselftest[,N][,selftest], "
244 "background, sasphy[,reset], sataphy[,reset], "
245 "scttemp[sts,hist], scttempint,N[,p], "
246 "scterc[,N,M], devstat[,N], defects[,N], ssd, "
247 "gplog,N[,RANGE], smartlog,N[,RANGE], "
250 return "use, ignore, show, showall";
252 return "offline, short, long, conveyance, force, vendor,N, select,M-N, "
253 "pending,N, afterselect,[on|off]";
255 return std::string(get_valid_firmwarebug_args()) + ", swapid";
257 return "never, sleep[,STATUS], standby[,STATUS], idle[,STATUS]";
259 return "old, brief, hex[,id|val]";
261 return "aam, apm, dsn, lookahead, security, wcache, rcache, wcreorder, wcache-sct";
263 return "aam,[N|off], apm,[N|off], dsn,[on|off], lookahead,[on|off], security-freeze, "
264 "standby,[N|off|now], wcache,[on|off], rcache,[on|off], wcreorder,[on|off[,p]], "
265 "wcache-sct,[ata|on|off[,p]]";
267 return getvalidarglist(opt_smart
)+", "+getvalidarglist(opt_set
);
269 return "c, g, i, o, s, u, v";
271 return "n, wn, w, v, wv, wb";
278 /* Prints the message "=======> VALID ARGUMENTS ARE: <LIST> \n", where
279 <LIST> is the list of valid arguments for option opt. */
280 static void printvalidarglistmessage(int opt
)
283 jerr("=======> VALID ARGUMENTS ARE:\n\thelp\n%s\n<=======\n",
284 create_vendor_attribute_arg_list().c_str());
287 // getvalidarglist() might produce a multiline or single line string. We
288 // need to figure out which to get the formatting right.
289 std::string s
= getvalidarglist(opt
);
290 char separator
= strchr(s
.c_str(), '\n') ? '\n' : ' ';
291 jerr("=======> VALID ARGUMENTS ARE:%c%s%c<=======\n", separator
, s
.c_str(), separator
);
297 // Checksum error mode
298 enum checksum_err_mode_t
{
299 CHECKSUM_ERR_WARN
, CHECKSUM_ERR_EXIT
, CHECKSUM_ERR_IGNORE
302 static checksum_err_mode_t checksum_err_mode
= CHECKSUM_ERR_WARN
;
304 static void scan_devices(const smart_devtype_list
& types
, bool with_open
, char ** argv
);
307 /* Takes command options and sets features to be run */
308 static int parse_options(int argc
, char** argv
, const char * & type
,
309 ata_print_options
& ataopts
, scsi_print_options
& scsiopts
,
310 nvme_print_options
& nvmeopts
, bool & print_type_only
)
312 // Please update getvalidarglist() if you edit shortopts
313 const char *shortopts
= "h?Vq:d:T:b:r:s:o:S:HcAl:iaxv:P:t:CXF:n:B:f:g:j";
314 // Please update getvalidarglist() if you edit longopts
315 struct option longopts
[] = {
316 { "help", no_argument
, 0, 'h' },
317 { "usage", no_argument
, 0, 'h' },
318 { "version", no_argument
, 0, 'V' },
319 { "copyright", no_argument
, 0, 'V' },
320 { "license", no_argument
, 0, 'V' },
321 { "quietmode", required_argument
, 0, 'q' },
322 { "device", required_argument
, 0, 'd' },
323 { "tolerance", required_argument
, 0, 'T' },
324 { "badsum", required_argument
, 0, 'b' },
325 { "report", required_argument
, 0, 'r' },
326 { "smart", required_argument
, 0, opt_smart
},
327 { "offlineauto", required_argument
, 0, 'o' },
328 { "saveauto", required_argument
, 0, 'S' },
329 { "health", no_argument
, 0, 'H' },
330 { "capabilities", no_argument
, 0, 'c' },
331 { "attributes", no_argument
, 0, 'A' },
332 { "log", required_argument
, 0, 'l' },
333 { "info", no_argument
, 0, 'i' },
334 { "all", no_argument
, 0, 'a' },
335 { "xall", no_argument
, 0, 'x' },
336 { "vendorattribute", required_argument
, 0, 'v' },
337 { "presets", required_argument
, 0, 'P' },
338 { "test", required_argument
, 0, 't' },
339 { "captive", no_argument
, 0, 'C' },
340 { "abort", no_argument
, 0, 'X' },
341 { "firmwarebug", required_argument
, 0, 'F' },
342 { "nocheck", required_argument
, 0, 'n' },
343 { "drivedb", required_argument
, 0, 'B' },
344 { "format", required_argument
, 0, 'f' },
345 { "get", required_argument
, 0, 'g' },
346 { "json", optional_argument
, 0, 'j' },
347 { "identify", optional_argument
, 0, opt_identify
},
348 { "set", required_argument
, 0, opt_set
},
349 { "scan", no_argument
, 0, opt_scan
},
350 { "scan-open", no_argument
, 0, opt_scan_open
},
354 char extraerror
[256];
355 memset(extraerror
, 0, sizeof(extraerror
));
358 smart_devtype_list scan_types
; // multiple -d TYPE options for --scan
359 bool use_default_db
= true; // set false on '-B FILE'
360 bool output_format_set
= false; // set true on '-f FORMAT'
361 int scan
= 0; // set by --scan, --scan-open
362 bool badarg
= false, captive
= false;
363 int testcnt
= 0; // number of self-tests requested
368 while ((optchar
= getopt_long(argc
, argv
, shortopts
, longopts
, 0)) != -1) {
370 // Clang analyzer: Workaround for false positive messages
371 // 'Dereference of null pointer' and 'Null pointer argument'
372 bool optarg_is_set
= !!optarg
;
373 #ifdef __clang_analyzer__
374 if (!optarg_is_set
) optarg
= (char *)"";
379 printing_is_off
= false;
380 pout("%s", format_version_info("smartctl", true /*full*/).c_str());
383 if (!strcmp(optarg
,"errorsonly")) {
384 printing_is_switchable
= true;
385 printing_is_off
= false;
386 } else if (!strcmp(optarg
,"silent")) {
387 printing_is_switchable
= false;
388 printing_is_off
= true;
389 } else if (!strcmp(optarg
,"noserial")) {
390 dont_print_serial_number
= true;
396 if (!strcmp(optarg
, "test"))
397 print_type_only
= true;
398 else if (!strcmp(optarg
, "auto")) {
404 scan_types
.push_back(optarg
);
408 if (!strcmp(optarg
,"normal")) {
409 failuretest_conservative
= false;
410 failuretest_permissive
= 0;
411 } else if (!strcmp(optarg
,"conservative")) {
412 failuretest_conservative
= true;
413 } else if (!strcmp(optarg
,"permissive")) {
414 if (failuretest_permissive
< 0xff)
415 failuretest_permissive
++;
416 } else if (!strcmp(optarg
,"verypermissive")) {
417 failuretest_permissive
= 0xff;
423 if (!strcmp(optarg
,"warn")) {
424 checksum_err_mode
= CHECKSUM_ERR_WARN
;
425 } else if (!strcmp(optarg
,"exit")) {
426 checksum_err_mode
= CHECKSUM_ERR_EXIT
;
427 } else if (!strcmp(optarg
,"ignore")) {
428 checksum_err_mode
= CHECKSUM_ERR_IGNORE
;
435 int n1
= -1, n2
= -1, len
= strlen(optarg
);
436 char s
[9+1]; unsigned i
= 1;
437 sscanf(optarg
, "%9[a-z]%n,%u%n", s
, &n1
, &i
, &n2
);
438 if (!((n1
== len
|| n2
== len
) && 1 <= i
&& i
<= 4)) {
440 } else if (!strcmp(s
,"ioctl")) {
441 ata_debugmode
= scsi_debugmode
= nvme_debugmode
= i
;
442 } else if (!strcmp(s
,"ataioctl")) {
444 } else if (!strcmp(s
,"scsiioctl")) {
446 } else if (!strcmp(s
,"nvmeioctl")) {
455 case opt_smart
: // --smart
456 if (!strcmp(optarg
,"on")) {
457 ataopts
.smart_enable
= scsiopts
.smart_enable
= true;
458 ataopts
.smart_disable
= scsiopts
.smart_disable
= false;
459 } else if (!strcmp(optarg
,"off")) {
460 ataopts
.smart_disable
= scsiopts
.smart_disable
= true;
461 ataopts
.smart_enable
= scsiopts
.smart_enable
= false;
462 } else if (optchar
== 's') {
463 goto case_s_continued
; // --set, see below
470 if (!strcmp(optarg
,"on")) {
471 ataopts
.smart_auto_offl_enable
= true;
472 ataopts
.smart_auto_offl_disable
= false;
473 } else if (!strcmp(optarg
,"off")) {
474 ataopts
.smart_auto_offl_disable
= true;
475 ataopts
.smart_auto_offl_enable
= false;
481 if (!strcmp(optarg
,"on")) {
482 ataopts
.smart_auto_save_enable
= scsiopts
.smart_auto_save_enable
= true;
483 ataopts
.smart_auto_save_disable
= scsiopts
.smart_auto_save_disable
= false;
484 } else if (!strcmp(optarg
,"off")) {
485 ataopts
.smart_auto_save_disable
= scsiopts
.smart_auto_save_disable
= true;
486 ataopts
.smart_auto_save_enable
= scsiopts
.smart_auto_save_enable
= false;
492 ataopts
.smart_check_status
= scsiopts
.smart_check_status
= nvmeopts
.smart_check_status
= true;
493 scsiopts
.smart_ss_media_log
= true;
496 if (!strcmp(optarg
, "swapid"))
497 ataopts
.fix_swapped_id
= true;
498 else if (!parse_firmwarebug_def(optarg
, ataopts
.firmwarebugs
))
502 ataopts
.smart_general_values
= nvmeopts
.drive_capabilities
= true;
505 ataopts
.smart_vendor_attrib
= scsiopts
.smart_vendor_attrib
= nvmeopts
.smart_vendor_attrib
= true;
508 if (str_starts_with(optarg
, "error")) {
509 int n1
= -1, n2
= -1, len
= strlen(optarg
);
511 sscanf(optarg
, "error%n,%u%n", &n1
, &val
, &n2
);
512 ataopts
.smart_error_log
= scsiopts
.smart_error_log
= true;
514 nvmeopts
.error_log_entries
= 16;
515 else if (n2
== len
&& val
> 0)
516 nvmeopts
.error_log_entries
= val
;
519 } else if (!strcmp(optarg
,"selftest")) {
520 ataopts
.smart_selftest_log
= scsiopts
.smart_selftest_log
= true;
521 } else if (!strcmp(optarg
, "selective")) {
522 ataopts
.smart_selective_selftest_log
= true;
523 } else if (!strcmp(optarg
,"directory")) {
524 ataopts
.smart_logdir
= ataopts
.gp_logdir
= true; // SMART+GPL
525 } else if (!strcmp(optarg
,"directory,s")) {
526 ataopts
.smart_logdir
= true; // SMART
527 } else if (!strcmp(optarg
,"directory,g")) {
528 ataopts
.gp_logdir
= true; // GPL
529 } else if (!strcmp(optarg
,"sasphy")) {
530 scsiopts
.sasphy
= true;
531 } else if (!strcmp(optarg
,"sasphy,reset")) {
532 scsiopts
.sasphy
= scsiopts
.sasphy_reset
= true;
533 } else if (!strcmp(optarg
,"sataphy")) {
534 ataopts
.sataphy
= true;
535 } else if (!strcmp(optarg
,"sataphy,reset")) {
536 ataopts
.sataphy
= ataopts
.sataphy_reset
= true;
537 } else if (!strcmp(optarg
,"background")) {
538 scsiopts
.smart_background_log
= true;
539 } else if (!strcmp(optarg
,"ssd")) {
540 ataopts
.devstat_ssd_page
= true;
541 scsiopts
.smart_ss_media_log
= true;
542 } else if (!strcmp(optarg
,"scterc")) {
543 ataopts
.sct_erc_get
= true;
544 } else if (!strcmp(optarg
,"scttemp")) {
545 ataopts
.sct_temp_sts
= ataopts
.sct_temp_hist
= true;
546 } else if (!strcmp(optarg
,"scttempsts")) {
547 ataopts
.sct_temp_sts
= true;
548 } else if (!strcmp(optarg
,"scttemphist")) {
549 ataopts
.sct_temp_hist
= true;
551 } else if (!strncmp(optarg
, "scttempint,", sizeof("scstempint,")-1)) {
552 unsigned interval
= 0; int n1
= -1, n2
= -1, len
= strlen(optarg
);
553 if (!( sscanf(optarg
,"scttempint,%u%n,p%n", &interval
, &n1
, &n2
) == 1
554 && 0 < interval
&& interval
<= 0xffff && (n1
== len
|| n2
== len
))) {
555 snprintf(extraerror
, sizeof(extraerror
), "Option -l scttempint,N[,p] must have positive integer N\n");
558 ataopts
.sct_temp_int
= interval
;
559 ataopts
.sct_temp_int_pers
= (n2
== len
);
561 } else if (!strncmp(optarg
, "devstat", sizeof("devstat")-1)) {
562 int n1
= -1, n2
= -1, len
= strlen(optarg
);
564 sscanf(optarg
, "devstat%n,%u%n", &n1
, &val
, &n2
);
566 ataopts
.devstat_all_pages
= true;
568 if (n2
!= len
) // retry with hex
569 sscanf(optarg
, "devstat,0x%x%n", &val
, &n2
);
570 if (n2
== len
&& val
<= 0xff)
571 ataopts
.devstat_pages
.push_back(val
);
576 } else if (str_starts_with(optarg
, "defects")) {
577 int n1
= -1, n2
= -1, len
= strlen(optarg
);
579 sscanf(optarg
, "defects%n,%u%n", &n1
, &val
, &n2
);
581 ataopts
.pending_defects_log
= 31; // Entries of first page
582 else if (n2
== len
&& val
<= 0xffff * 32 - 1)
583 ataopts
.pending_defects_log
= val
;
587 } else if (!strncmp(optarg
, "xerror", sizeof("xerror")-1)) {
588 int n1
= -1, n2
= -1, len
= strlen(optarg
);
590 sscanf(optarg
, "xerror%n,error%n", &n1
, &n2
);
591 if (!(n1
== len
|| n2
== len
)) {
593 sscanf(optarg
, "xerror,%u%n,error%n", &val
, &n1
, &n2
);
595 if ((n1
== len
|| n2
== len
) && val
> 0) {
596 ataopts
.smart_ext_error_log
= val
;
597 ataopts
.retry_error_log
= (n2
== len
);
602 } else if (!strncmp(optarg
, "xselftest", sizeof("xselftest")-1)) {
603 int n1
= -1, n2
= -1, len
= strlen(optarg
);
605 sscanf(optarg
, "xselftest%n,selftest%n", &n1
, &n2
);
606 if (!(n1
== len
|| n2
== len
)) {
608 sscanf(optarg
, "xselftest,%u%n,selftest%n", &val
, &n1
, &n2
);
610 if ((n1
== len
|| n2
== len
) && val
> 0) {
611 ataopts
.smart_ext_selftest_log
= val
;
612 ataopts
.retry_selftest_log
= (n2
== len
);
617 } else if (!strncmp(optarg
, "scterc,", sizeof("scterc,")-1)) {
618 unsigned rt
= ~0, wt
= ~0; int n
= -1;
619 sscanf(optarg
,"scterc,%u,%u%n", &rt
, &wt
, &n
);
620 if (n
== (int)strlen(optarg
) && rt
<= 999 && wt
<= 999) {
621 ataopts
.sct_erc_set
= true;
622 ataopts
.sct_erc_readtime
= rt
;
623 ataopts
.sct_erc_writetime
= wt
;
626 snprintf(extraerror
, sizeof(extraerror
), "Option -l scterc,[READTIME,WRITETIME] syntax error\n");
629 } else if ( !strncmp(optarg
, "gplog," , sizeof("gplog," )-1)
630 || !strncmp(optarg
, "smartlog,", sizeof("smartlog,")-1)) {
631 unsigned logaddr
= ~0U; unsigned page
= 0, nsectors
= 1; char sign
= 0;
632 int n1
= -1, n2
= -1, n3
= -1, len
= strlen(optarg
);
633 sscanf(optarg
, "%*[a-z],0x%x%n,%u%n%c%u%n",
634 &logaddr
, &n1
, &page
, &n2
, &sign
, &nsectors
, &n3
);
635 if (len
> n2
&& n3
== -1 && !strcmp(optarg
+n2
, "-max")) {
636 nsectors
= ~0U; sign
= '+'; n3
= len
;
638 bool gpl
= (optarg
[0] == 'g');
639 const char * erropt
= (gpl
? "gplog" : "smartlog");
640 if (!( n1
== len
|| n2
== len
641 || (n3
== len
&& (sign
== '+' || sign
== '-')))) {
642 snprintf(extraerror
, sizeof(extraerror
), "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] syntax error\n", erropt
);
645 else if (!( logaddr
<= 0xff && page
<= (gpl
? 0xffffU
: 0x00ffU
)
647 && (nsectors
<= (gpl
? 0xffffU
: 0xffU
) || nsectors
== ~0U)
648 && (sign
!= '-' || page
<= nsectors
) )) {
649 snprintf(extraerror
, sizeof(extraerror
), "Option -l %s,ADDR[,FIRST[-LAST|+SIZE]] parameter out of range\n", erropt
);
654 req
.gpl
= gpl
; req
.logaddr
= logaddr
; req
.page
= page
;
655 req
.nsectors
= (sign
== '-' ? nsectors
-page
+1 : nsectors
);
656 ataopts
.log_requests
.push_back(req
);
660 else if (str_starts_with(optarg
, "nvmelog,")) {
661 int n
= -1, len
= strlen(optarg
);
662 unsigned page
= 0, size
= 0;
663 sscanf(optarg
, "nvmelog,0x%x,0x%x%n", &page
, &size
, &n
);
664 if (n
== len
&& page
<= 0xff && 0 < size
&& size
<= 0x4000) {
665 nvmeopts
.log_page
= page
; nvmeopts
.log_page_size
= size
;
676 ataopts
.drive_info
= scsiopts
.drive_info
= nvmeopts
.drive_info
= true;
680 ataopts
.identify_word_level
= ataopts
.identify_bit_level
= 0;
682 for (int i
= 0; optarg
[i
]; i
++) {
684 case 'w': ataopts
.identify_word_level
= 1; break;
685 case 'n': ataopts
.identify_bit_level
= -1; break;
686 case 'v': ataopts
.identify_bit_level
= 1; break;
687 case 'b': ataopts
.identify_bit_level
= 2; break;
688 default: badarg
= true;
695 ataopts
.drive_info
= scsiopts
.drive_info
= nvmeopts
.drive_info
= true;
696 ataopts
.smart_check_status
= scsiopts
.smart_check_status
= nvmeopts
.smart_check_status
= true;
697 ataopts
.smart_general_values
= nvmeopts
.drive_capabilities
= true;
698 ataopts
.smart_vendor_attrib
= scsiopts
.smart_vendor_attrib
= nvmeopts
.smart_vendor_attrib
= true;
699 ataopts
.smart_error_log
= scsiopts
.smart_error_log
= true;
700 nvmeopts
.error_log_entries
= 16;
701 ataopts
.smart_selftest_log
= scsiopts
.smart_selftest_log
= true;
702 ataopts
.smart_selective_selftest_log
= true;
703 /* scsiopts.smart_background_log = true; */
704 scsiopts
.smart_ss_media_log
= true;
707 ataopts
.drive_info
= scsiopts
.drive_info
= nvmeopts
.drive_info
= true;
708 ataopts
.smart_check_status
= scsiopts
.smart_check_status
= nvmeopts
.smart_check_status
= true;
709 ataopts
.smart_general_values
= nvmeopts
.drive_capabilities
= true;
710 ataopts
.smart_vendor_attrib
= scsiopts
.smart_vendor_attrib
= nvmeopts
.smart_vendor_attrib
= true;
711 ataopts
.smart_ext_error_log
= 8;
712 ataopts
.retry_error_log
= true;
713 nvmeopts
.error_log_entries
= 16;
714 ataopts
.smart_ext_selftest_log
= 25;
715 ataopts
.retry_selftest_log
= true;
716 scsiopts
.smart_error_log
= scsiopts
.smart_selftest_log
= true;
717 ataopts
.smart_selective_selftest_log
= true;
718 ataopts
.smart_logdir
= ataopts
.gp_logdir
= true;
719 ataopts
.sct_temp_sts
= ataopts
.sct_temp_hist
= true;
720 ataopts
.sct_erc_get
= true;
721 ataopts
.sct_wcache_reorder_get
= true;
722 ataopts
.devstat_all_pages
= true;
723 ataopts
.pending_defects_log
= 31;
724 ataopts
.sataphy
= true;
725 ataopts
.get_set_used
= true;
726 ataopts
.get_aam
= ataopts
.get_apm
= true;
727 ataopts
.get_security
= true;
728 ataopts
.get_lookahead
= ataopts
.get_wcache
= true;
729 ataopts
.get_dsn
= true;
730 scsiopts
.get_rcd
= scsiopts
.get_wce
= true;
731 scsiopts
.smart_background_log
= true;
732 scsiopts
.smart_ss_media_log
= true;
733 scsiopts
.sasphy
= true;
734 if (!output_format_set
)
735 ataopts
.output_format
|= ata_print_options::FMT_BRIEF
;
738 // parse vendor-specific definitions of attributes
739 if (!strcmp(optarg
,"help")) {
740 printing_is_off
= false;
742 pout("The valid arguments to -v are:\n\thelp\n%s\n",
743 create_vendor_attribute_arg_list().c_str());
746 if (!parse_attribute_def(optarg
, ataopts
.attribute_defs
, PRIOR_USER
))
750 if (!strcmp(optarg
, "use")) {
751 ataopts
.ignore_presets
= false;
752 } else if (!strcmp(optarg
, "ignore")) {
753 ataopts
.ignore_presets
= true;
754 } else if (!strcmp(optarg
, "show")) {
755 ataopts
.show_presets
= true;
756 } else if (!strcmp(optarg
, "showall")) {
757 if (!init_drive_database(use_default_db
))
759 if (optind
< argc
) { // -P showall MODEL [FIRMWARE]
760 int cnt
= showmatchingpresets(argv
[optind
], (optind
+1<argc
? argv
[optind
+1] : NULL
));
761 return (cnt
>= 0 ? cnt
: 0);
763 if (showallpresets())
764 return FAILCMD
; // report regexp syntax error
771 if (!strcmp(optarg
,"offline")) {
773 ataopts
.smart_selftest_type
= OFFLINE_FULL_SCAN
;
774 scsiopts
.smart_default_selftest
= true;
775 } else if (!strcmp(optarg
,"short")) {
777 ataopts
.smart_selftest_type
= SHORT_SELF_TEST
;
778 scsiopts
.smart_short_selftest
= true;
779 } else if (!strcmp(optarg
,"long")) {
781 ataopts
.smart_selftest_type
= EXTEND_SELF_TEST
;
782 scsiopts
.smart_extend_selftest
= true;
783 } else if (!strcmp(optarg
,"conveyance")) {
785 ataopts
.smart_selftest_type
= CONVEYANCE_SELF_TEST
;
786 } else if (!strcmp(optarg
,"force")) {
787 ataopts
.smart_selftest_force
= true;
788 scsiopts
.smart_selftest_force
= true;
789 } else if (!strcmp(optarg
,"afterselect,on")) {
790 // scan remainder of disk after doing selected segment
791 ataopts
.smart_selective_args
.scan_after_select
= 2;
792 } else if (!strcmp(optarg
,"afterselect,off")) {
793 // don't scan remainder of disk after doing selected segments
794 ataopts
.smart_selective_args
.scan_after_select
= 1;
795 } else if (!strncmp(optarg
,"pending,",strlen("pending,"))) {
796 // parse number of minutes that test should be pending
800 i
=(int)strtol(optarg
+strlen("pending,"), &tailptr
, 10);
801 if (errno
|| *tailptr
!= '\0') {
802 snprintf(extraerror
, sizeof(extraerror
), "Option -t pending,N requires N to be a non-negative integer\n");
804 } else if (i
<0 || i
>65535) {
805 snprintf(extraerror
, sizeof(extraerror
), "Option -t pending,N (N=%d) must have 0 <= N <= 65535\n", i
);
808 ataopts
.smart_selective_args
.pending_time
= i
+1;
810 } else if (!strncmp(optarg
,"select",strlen("select"))) {
811 if (ataopts
.smart_selective_args
.num_spans
== 0)
813 // parse range of LBAs to test
814 uint64_t start
, stop
; int mode
;
815 if (split_selective_arg(optarg
, &start
, &stop
, &mode
)) {
816 snprintf(extraerror
, sizeof(extraerror
), "Option -t select,M-N must have non-negative integer M and N\n");
819 if (ataopts
.smart_selective_args
.num_spans
>= 5 || start
> stop
) {
821 snprintf(extraerror
, sizeof(extraerror
), "ERROR: Start LBA (%" PRIu64
") > ending LBA (%" PRId64
") in argument \"%s\"\n",
822 start
, stop
, optarg
);
824 snprintf(extraerror
, sizeof(extraerror
),"ERROR: No more than five selective self-test spans may be"
829 ataopts
.smart_selective_args
.span
[ataopts
.smart_selective_args
.num_spans
].start
= start
;
830 ataopts
.smart_selective_args
.span
[ataopts
.smart_selective_args
.num_spans
].end
= stop
;
831 ataopts
.smart_selective_args
.span
[ataopts
.smart_selective_args
.num_spans
].mode
= mode
;
832 ataopts
.smart_selective_args
.num_spans
++;
833 ataopts
.smart_selftest_type
= SELECTIVE_SELF_TEST
;
835 } else if (!strncmp(optarg
, "scttempint", sizeof("scstempint")-1)) {
836 snprintf(extraerror
, sizeof(extraerror
), "-t scttempint is no longer supported, use -l scttempint instead\n");
838 } else if (!strncmp(optarg
, "vendor,", sizeof("vendor,")-1)) {
839 unsigned subcmd
= ~0U; int n
= -1;
840 if (!( sscanf(optarg
, "%*[a-z],0x%x%n", &subcmd
, &n
) == 1
841 && subcmd
<= 0xff && n
== (int)strlen(optarg
))) {
842 snprintf(extraerror
, sizeof(extraerror
), "Option -t vendor,0xNN syntax error\n");
846 ataopts
.smart_selftest_type
= subcmd
;
856 scsiopts
.smart_selftest_abort
= true;
857 ataopts
.smart_selftest_type
= ABORT_SELF_TEST
;
860 // skip disk check if in low-power mode
861 if (!strcmp(optarg
, "never")) {
862 ataopts
.powermode
= 1; // do not skip, but print mode
865 int n1
= -1, n2
= -1, len
= strlen(optarg
);
866 char s
[7+1]; unsigned i
= FAILPOWER
;
867 sscanf(optarg
, "%9[a-z]%n,%u%n", s
, &n1
, &i
, &n2
);
868 if (!((n1
== len
|| n2
== len
) && i
<= 255))
870 else if (!strcmp(s
, "sleep"))
871 ataopts
.powermode
= 2;
872 else if (!strcmp(s
, "standby"))
873 ataopts
.powermode
= 3;
874 else if (!strcmp(s
, "idle"))
875 ataopts
.powermode
= 4;
878 ataopts
.powerexit
= i
;
882 if (!strcmp(optarg
, "old")) {
883 ataopts
.output_format
&= ~ata_print_options::FMT_BRIEF
;
884 output_format_set
= true;
886 else if (!strcmp(optarg
, "brief")) {
887 ataopts
.output_format
|= ata_print_options::FMT_BRIEF
;
888 output_format_set
= true;
890 else if (!strcmp(optarg
, "hex"))
891 ataopts
.output_format
|= ata_print_options::FMT_HEX_ID
892 | ata_print_options::FMT_HEX_VAL
;
893 else if (!strcmp(optarg
, "hex,id"))
894 ataopts
.output_format
|= ata_print_options::FMT_HEX_ID
;
895 else if (!strcmp(optarg
, "hex,val"))
896 ataopts
.output_format
|= ata_print_options::FMT_HEX_VAL
;
902 const char * path
= optarg
;
903 if (*path
== '+' && path
[1])
906 use_default_db
= false;
907 if (!read_drive_database(path
))
912 printing_is_off
= false;
918 case_s_continued
: // -s, see above
919 case opt_set
: // --set
921 ataopts
.get_set_used
= true;
922 bool get
= (optchar
== 'g');
923 char name
[16+1]; unsigned val
;
924 int n1
= -1, n2
= -1, n3
= -1, len
= strlen(optarg
);
925 if (sscanf(optarg
, "%16[^,=]%n%*[,=]%n%u%n", name
, &n1
, &n2
, &val
, &n3
) >= 1
926 && (n1
== len
|| (!get
&& n2
> 0))) {
930 bool persistent
= false;
933 int len2
= strlen(optarg
+ n2
);
934 char * tmp
= strstr(optarg
+n2
, ",p");
935 // handle ",p" in persistent options like: wcache-sct,[ata|on|off],p
936 if (tmp
&& (strlen(tmp
) == 2)) {
938 len2
= strlen(optarg
+n2
) - 2;
940 // the ,p option only works for set of SCT Feature Control command
941 if (strcmp(name
, "wcache-sct") != 0 &&
942 strcmp(name
, "wcreorder") != 0)
945 on
= !strncmp(optarg
+n2
, "on", len2
);
946 off
= !strncmp(optarg
+n2
, "off", len2
);
947 ata
= !strncmp(optarg
+n2
, "ata", len2
);
952 if (get
&& !strcmp(name
, "all")) {
953 ataopts
.get_aam
= ataopts
.get_apm
= true;
954 ataopts
.get_security
= true;
955 ataopts
.get_lookahead
= ataopts
.get_wcache
= true;
956 ataopts
.get_dsn
= true;
957 scsiopts
.get_rcd
= scsiopts
.get_wce
= true;
959 else if (!strcmp(name
, "aam")) {
961 ataopts
.get_aam
= true;
963 ataopts
.set_aam
= -1;
965 ataopts
.set_aam
= val
+ 1;
967 snprintf(extraerror
, sizeof(extraerror
), "Option -s aam,N must have 0 <= N <= 254\n");
971 else if (!strcmp(name
, "apm")) {
973 ataopts
.get_apm
= true;
975 ataopts
.set_apm
= -1;
976 else if (1 <= val
&& val
<= 254)
977 ataopts
.set_apm
= val
+ 1;
979 snprintf(extraerror
, sizeof(extraerror
), "Option -s apm,N must have 1 <= N <= 254\n");
983 else if (!strcmp(name
, "lookahead")) {
985 ataopts
.get_lookahead
= true;
988 ataopts
.set_lookahead
= -1;
990 ataopts
.set_lookahead
= 1;
994 else if (!strcmp(name
, "wcreorder")) {
995 ataopts
.sct_wcache_reorder_set_pers
= persistent
;
997 ataopts
.sct_wcache_reorder_get
= true;
1000 ataopts
.sct_wcache_reorder_set
= -1;
1002 ataopts
.sct_wcache_reorder_set
= 1;
1006 else if (!strcmp(name
, "wcache-sct")) {
1007 ataopts
.sct_wcache_sct_set_pers
= persistent
;
1009 ataopts
.sct_wcache_sct_get
= true;
1012 ataopts
.sct_wcache_sct_set
= 3;
1014 ataopts
.sct_wcache_sct_set
= 2;
1016 ataopts
.sct_wcache_sct_set
= 1;
1020 else if (!strcmp(name
, "rcache")) {
1022 scsiopts
.get_rcd
= true;
1024 scsiopts
.set_rcd
= -1;
1026 scsiopts
.set_rcd
= 1;
1030 else if (get
&& !strcmp(name
, "security")) {
1031 ataopts
.get_security
= true;
1033 else if (!get
&& !strcmp(optarg
, "security-freeze")) {
1034 ataopts
.set_security_freeze
= true;
1036 else if (!get
&& !strcmp(optarg
, "standby,now")) {
1037 ataopts
.set_standby_now
= true;
1039 else if (!get
&& !strcmp(name
, "standby")) {
1041 ataopts
.set_standby
= 0 + 1;
1042 else if (val
<= 255)
1043 ataopts
.set_standby
= val
+ 1;
1045 snprintf(extraerror
, sizeof(extraerror
), "Option -s standby,N must have 0 <= N <= 255\n");
1049 else if (!strcmp(name
, "wcache")) {
1051 ataopts
.get_wcache
= true;
1052 scsiopts
.get_wce
= true;
1055 ataopts
.set_wcache
= -1;
1056 scsiopts
.set_wce
= -1;
1059 ataopts
.set_wcache
= 1;
1060 scsiopts
.set_wce
= 1;
1065 else if (!strcmp(name
, "dsn")) {
1067 ataopts
.get_dsn
= true;
1070 ataopts
.set_dsn
= -1;
1073 ataopts
.set_dsn
= 1;
1093 print_as_json
= true;
1094 print_as_json_options
.pretty
= true;
1095 print_as_json_options
.sorted
= false;
1096 print_as_json_options
.flat
= false;
1097 print_as_json_output
= false;
1098 print_as_json_impl
= print_as_json_unimpl
= false;
1099 bool json_verbose
= false;
1100 if (optarg_is_set
) {
1101 for (int i
= 0; optarg
[i
]; i
++) {
1102 switch (optarg
[i
]) {
1103 case 'c': print_as_json_options
.pretty
= false; break;
1104 case 'g': print_as_json_options
.flat
= true; break;
1105 case 'i': print_as_json_impl
= true; break;
1106 case 'o': print_as_json_output
= true; break;
1107 case 's': print_as_json_options
.sorted
= true; break;
1108 case 'u': print_as_json_unimpl
= true; break;
1109 case 'v': json_verbose
= true; break;
1110 default: badarg
= true;
1114 js_initialize(argc
, argv
, json_verbose
);
1120 printing_is_off
= false;
1122 // Point arg to the argument in which this option was found.
1123 arg
= argv
[optind
-1];
1124 // Check whether the option is a long option that doesn't map to -h.
1125 if (arg
[1] == '-' && optchar
!= 'h') {
1126 // Iff optopt holds a valid option then argument must be missing.
1127 if (optopt
&& (optopt
>= opt_scan
|| strchr(shortopts
, optopt
))) {
1128 jerr("=======> ARGUMENT REQUIRED FOR OPTION: %s\n", arg
+2);
1129 printvalidarglistmessage(optopt
);
1131 jerr("=======> UNRECOGNIZED OPTION: %s\n",arg
+2);
1133 pout("=======> %s", extraerror
);
1137 if (0 < optopt
&& optopt
< '~') {
1138 // Iff optopt holds a valid option then argument must be
1139 // missing. Note (BA) this logic seems to fail using Solaris
1141 if (strchr(shortopts
, optopt
) != NULL
) {
1142 jerr("=======> ARGUMENT REQUIRED FOR OPTION: %c\n", optopt
);
1143 printvalidarglistmessage(optopt
);
1145 jerr("=======> UNRECOGNIZED OPTION: %c\n",optopt
);
1147 pout("=======> %s", extraerror
);
1153 } // closes switch statement to process command-line options
1155 // Check to see if option had an unrecognized or incorrect argument.
1158 // It would be nice to print the actual option name given by the user
1159 // here, but we just print the short form. Please fix this if you know
1160 // a clean way to do it.
1161 char optstr
[] = { (char)optchar
, 0 };
1162 jerr("=======> INVALID ARGUMENT TO -%s: %s\n",
1163 (optchar
== opt_identify
? "-identify" :
1164 optchar
== opt_set
? "-set" :
1165 optchar
== opt_smart
? "-smart" :
1166 optchar
== 'j' ? "-json" : optstr
), optarg
);
1167 printvalidarglistmessage(optchar
);
1169 pout("=======> %s", extraerror
);
1175 // Special handling of --scan, --scanopen
1177 // Read or init drive database to allow USB ID check.
1178 if (!init_drive_database(use_default_db
))
1180 scan_devices(scan_types
, (scan
== opt_scan_open
), argv
+ optind
);
1184 // At this point we have processed all command-line options. If the
1185 // print output is switchable, then start with the print output
1187 if (printing_is_switchable
)
1188 printing_is_off
= true;
1190 // Check for multiple -d TYPE options
1191 if (scan_types
.size() > 1) {
1192 printing_is_off
= false;
1194 jerr("ERROR: multiple -d TYPE options are only allowed with --scan\n");
1199 // error message if user has asked for more than one test
1201 printing_is_off
= false;
1203 jerr("\nERROR: smartctl can only run a single test type (or abort) at a time.\n");
1208 // error message if user has set selective self-test options without
1209 // asking for a selective self-test
1210 if ( (ataopts
.smart_selective_args
.pending_time
|| ataopts
.smart_selective_args
.scan_after_select
)
1211 && !ataopts
.smart_selective_args
.num_spans
) {
1212 printing_is_off
= false;
1214 if (ataopts
.smart_selective_args
.pending_time
)
1215 jerr("\nERROR: smartctl -t pending,N must be used with -t select,N-M.\n");
1217 jerr("\nERROR: smartctl -t afterselect,(on|off) must be used with -t select,N-M.\n");
1222 // If captive option was used, change test type if appropriate.
1224 switch (ataopts
.smart_selftest_type
) {
1225 case SHORT_SELF_TEST
:
1226 ataopts
.smart_selftest_type
= SHORT_CAPTIVE_SELF_TEST
;
1227 scsiopts
.smart_short_selftest
= false;
1228 scsiopts
.smart_short_cap_selftest
= true;
1230 case EXTEND_SELF_TEST
:
1231 ataopts
.smart_selftest_type
= EXTEND_CAPTIVE_SELF_TEST
;
1232 scsiopts
.smart_extend_selftest
= false;
1233 scsiopts
.smart_extend_cap_selftest
= true;
1235 case CONVEYANCE_SELF_TEST
:
1236 ataopts
.smart_selftest_type
= CONVEYANCE_CAPTIVE_SELF_TEST
;
1238 case SELECTIVE_SELF_TEST
:
1239 ataopts
.smart_selftest_type
= SELECTIVE_CAPTIVE_SELF_TEST
;
1243 // From here on, normal operations...
1246 // Warn if the user has provided no device name
1248 jerr("ERROR: smartctl requires a device name as the final command-line argument.\n\n");
1253 // Warn if the user has provided more than one device name
1256 jerr("ERROR: smartctl takes ONE device name as the final command-line argument.\n");
1257 pout("You have provided %d device names:\n",argc
-optind
);
1258 for (i
=0; i
<argc
-optind
; i
++)
1259 pout("%s\n",argv
[optind
+i
]);
1264 // Read or init drive database
1265 if (!init_drive_database(use_default_db
))
1268 // No error, continue in main_worker()
1272 // Printing functions
1274 __attribute_format_printf(3, 0)
1275 static void vjpout(bool is_js_impl
, const char * msg_severity
,
1276 const char *fmt
, va_list ap
)
1278 if (!print_as_json
) {
1279 // Print out directly
1284 // Add lines to JSON output
1285 static char buf
[1024];
1286 static char * bufnext
= buf
;
1287 vsnprintf(bufnext
, sizeof(buf
) - (bufnext
- buf
), fmt
, ap
);
1288 for (char * p
= buf
, *q
; ; p
= q
) {
1289 if (!(q
= strchr(p
, '\n'))) {
1290 // Keep remaining line for next call
1291 for (bufnext
= buf
; *p
; bufnext
++, p
++)
1295 *q
++ = 0; // '\n' -> '\0'
1297 static int lineno
= 0;
1299 if (print_as_json_output
) {
1300 // Collect full output in array
1301 static int outindex
= 0;
1302 jglb
["smartctl"]["output"][outindex
++] = p
;
1305 continue; // Skip empty line
1308 // Collect non-empty messages in array
1309 static int errindex
= 0;
1310 json::ref jref
= jglb
["smartctl"]["messages"][errindex
++];
1312 jref
["severity"] = msg_severity
;
1315 if ( ( is_js_impl
&& print_as_json_impl
)
1316 || (!is_js_impl
&& print_as_json_unimpl
)) {
1317 // Add (un)implemented non-empty lines to global object
1318 jglb
[strprintf("smartctl_%04d_%c", lineno
,
1319 (is_js_impl
? 'i' : 'u')).c_str()] = p
;
1325 // Default: print to stdout
1327 // --json=o: append to "output" array
1328 // --json=u: add "smartctl_NNNN_u" element(s)
1329 void pout(const char *fmt
, ...)
1331 if (printing_is_off
)
1333 if (print_as_json
&& !(print_as_json_output
1334 || print_as_json_impl
|| print_as_json_unimpl
))
1339 vjpout(false, 0, fmt
, ap
);
1343 // Default: Print to stdout
1345 // --json=o: append to "output" array
1346 // --json=i: add "smartctl_NNNN_i" element(s)
1347 void jout(const char *fmt
, ...)
1349 if (printing_is_off
)
1351 if (print_as_json
&& !(print_as_json_output
1352 || print_as_json_impl
|| print_as_json_unimpl
))
1357 vjpout(true, 0, fmt
, ap
);
1361 // Default: print to stdout
1362 // --json: append to "messages"
1363 // --json=o: append to "output" array
1364 // --json=i: add "smartctl_NNNN_i" element(s)
1365 void jinf(const char *fmt
, ...)
1367 if (printing_is_off
)
1372 vjpout(true, "information", fmt
, ap
);
1376 void jwrn(const char *fmt
, ...)
1378 if (printing_is_off
)
1383 vjpout(true, "warning", fmt
, ap
);
1387 void jerr(const char *fmt
, ...)
1389 if (printing_is_off
)
1394 vjpout(true, "error", fmt
, ap
);
1398 // Globals to set failuretest() policy
1399 bool failuretest_conservative
= false;
1400 unsigned char failuretest_permissive
= 0;
1402 // Compares failure type to policy in effect, and either exits or
1403 // simply returns to the calling routine.
1404 // Used in ataprint.cpp and scsiprint.cpp.
1405 void failuretest(failure_type type
, int returnvalue
)
1407 // If this is an error in an "optional" SMART command
1408 if (type
== OPTIONAL_CMD
) {
1409 if (!failuretest_conservative
)
1411 pout("An optional SMART command failed: exiting. Remove '-T conservative' option to continue.\n");
1412 throw int(returnvalue
);
1415 // If this is an error in a "mandatory" SMART command
1416 if (type
== MANDATORY_CMD
) {
1417 if (failuretest_permissive
--)
1419 pout("A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.\n");
1420 throw int(returnvalue
);
1423 throw std::logic_error("failuretest: Unknown type");
1426 // Used to warn users about invalid checksums. Called from atacmds.cpp.
1427 // Action to be taken may be altered by the user.
1428 void checksumwarning(const char * string
)
1430 // user has asked us to ignore checksum errors
1431 if (checksum_err_mode
== CHECKSUM_ERR_IGNORE
)
1434 pout("Warning! %s error: invalid SMART checksum.\n", string
);
1436 // user has asked us to fail on checksum errors
1437 if (checksum_err_mode
== CHECKSUM_ERR_EXIT
)
1438 throw int(FAILSMART
);
1441 // Return info string about device protocol
1442 static const char * get_protocol_info(const smart_device
* dev
)
1444 switch ( (int)dev
->is_ata()
1445 | ((int)dev
->is_scsi() << 1)
1446 | ((int)dev
->is_nvme() << 2)) {
1447 case 0x1: return "ATA";
1448 case 0x2: return "SCSI";
1449 case 0x3: return "ATA+SCSI";
1450 case 0x4: return "NVMe";
1451 default: return "Unknown";
1455 // Add JSON device info
1456 static void js_device_info(const json::ref
& jref
, const smart_device
* dev
)
1458 jref
["name"] = dev
->get_dev_name();
1459 jref
["info_name"] = dev
->get_info_name();
1460 jref
["type"] = dev
->get_dev_type();
1461 jref
["protocol"] = get_protocol_info(dev
);
1465 // smartctl [-d type] --scan[-open] -- [PATTERN] [smartd directive ...]
1466 void scan_devices(const smart_devtype_list
& types
, bool with_open
, char ** argv
)
1468 bool dont_print
= !(ata_debugmode
|| scsi_debugmode
|| nvme_debugmode
);
1470 const char * pattern
= 0;
1472 if (argv
[ai
] && argv
[ai
][0] != '-')
1473 pattern
= argv
[ai
++];
1475 smart_device_list devlist
;
1476 printing_is_off
= dont_print
;
1477 bool ok
= smi()->scan_smart_devices(devlist
, types
, pattern
);
1478 printing_is_off
= false;
1481 pout("# scan_smart_devices: %s\n", smi()->get_errmsg());
1485 for (unsigned i
= 0; i
< devlist
.size(); i
++) {
1486 smart_device_auto_ptr
dev( devlist
.release(i
) );
1487 json::ref jref
= jglb
["devices"][i
];
1490 printing_is_off
= dont_print
;
1491 dev
.replace ( dev
->autodetect_open() );
1492 printing_is_off
= false;
1495 js_device_info(jref
, dev
.get());
1497 if (with_open
&& !dev
->is_open()) {
1498 jout("# %s -d %s # %s, %s device open failed: %s\n", dev
->get_dev_name(),
1499 dev
->get_dev_type(), dev
->get_info_name(),
1500 get_protocol_info(dev
.get()), dev
->get_errmsg());
1501 jref
["open_error"] = dev
->get_errmsg();
1505 jout("%s -d %s", dev
->get_dev_name(), dev
->get_dev_type());
1507 jout(" # %s, %s device\n", dev
->get_info_name(), get_protocol_info(dev
.get()));
1509 for (int j
= ai
; argv
[j
]; j
++)
1510 jout(" %s", argv
[j
]);
1519 // Main program without exception handling
1520 static int main_worker(int argc
, char **argv
)
1522 // Throw if runtime environment does not match compile time test.
1525 // Initialize interface
1526 smart_interface::init();
1530 // Parse input arguments
1531 const char * type
= 0;
1532 ata_print_options ataopts
;
1533 scsi_print_options scsiopts
;
1534 nvme_print_options nvmeopts
;
1535 bool print_type_only
= false;
1537 int status
= parse_options(argc
, argv
, type
, ataopts
, scsiopts
, nvmeopts
, print_type_only
);
1542 const char * name
= argv
[argc
-1];
1544 smart_device_auto_ptr dev
;
1545 if (!strcmp(name
,"-")) {
1546 // Parse "smartctl -r ataioctl,2 ..." output from stdin
1547 if (type
|| print_type_only
) {
1548 pout("-d option is not allowed in conjunction with device name \"-\".\n");
1552 dev
= get_parsed_ata_device(smi(), name
);
1555 // get device of appropriate type
1556 dev
= smi()->get_smart_device(name
, type
);
1559 jerr("%s: %s\n", name
, smi()->get_errmsg());
1561 printvalidarglistmessage('d');
1563 pout("Please specify device type with the -d option.\n");
1568 if (print_type_only
)
1569 // Report result of first autodetection
1570 pout("%s: Device of type '%s' [%s] detected\n",
1571 dev
->get_info_name(), dev
->get_dev_type(), get_protocol_info(dev
.get()));
1573 if (dev
->is_ata() && ataopts
.powermode
>=2 && dev
->is_powered_down()) {
1574 jinf("Device is in STANDBY (OS) mode, exit(%d)\n", ataopts
.powerexit
);
1575 return ataopts
.powerexit
;
1581 smart_device::device_info oldinfo
= dev
->get_info();
1583 // Open with autodetect support, may return 'better' device
1584 dev
.replace( dev
->autodetect_open() );
1586 // Report if type has changed
1587 if ( (ata_debugmode
|| scsi_debugmode
|| nvme_debugmode
|| print_type_only
)
1588 && oldinfo
.dev_type
!= dev
->get_dev_type() )
1589 pout("%s: Device open changed type from '%s' to '%s'\n",
1590 dev
->get_info_name(), oldinfo
.dev_type
.c_str(), dev
->get_dev_type());
1592 if (!dev
->is_open()) {
1593 jerr("Smartctl open device: %s failed: %s\n", dev
->get_info_name(), dev
->get_errmsg());
1597 // Add JSON info similar to --scan output
1598 js_device_info(jglb
["device"], dev
.get());
1600 // now call appropriate ATA or SCSI routine
1602 if (print_type_only
)
1603 jout("%s: Device of type '%s' [%s] opened\n",
1604 dev
->get_info_name(), dev
->get_dev_type(), get_protocol_info(dev
.get()));
1605 else if (dev
->is_ata())
1606 retval
= ataPrintMain(dev
->to_ata(), ataopts
);
1607 else if (dev
->is_scsi())
1608 retval
= scsiPrintMain(dev
->to_scsi(), scsiopts
);
1609 else if (dev
->is_nvme())
1610 retval
= nvmePrintMain(dev
->to_nvme(), nvmeopts
);
1612 // we should never fall into this branch!
1613 pout("%s: Neither ATA, SCSI nor NVMe device\n", dev
->get_info_name());
1621 int main(int argc
, char **argv
)
1624 bool badcode
= false;
1628 // Do the real work ...
1629 status
= main_worker(argc
, argv
);
1632 // Exit status from checksumwarning() and failuretest() arrives here
1635 // Print JSON if enabled
1636 if (jglb
.has_uint128_output())
1637 jglb
["smartctl"]["uint128_precision_bits"] = uint128_to_str_precision_bits();
1638 jglb
["smartctl"]["exit_status"] = status
;
1639 jglb
.print(stdout
, print_as_json_options
);
1641 catch (const std::bad_alloc
& /*ex*/) {
1642 // Memory allocation failed (also thrown by std::operator new)
1643 printf("Smartctl: Out of memory\n");
1646 catch (const std::exception
& ex
) {
1647 // Other fatal errors
1648 printf("Smartctl: Exception: %s\n", ex
.what());
1653 // Check for remaining device objects
1654 if (smart_device::get_num_objects() != 0) {
1655 printf("Smartctl: Internal Error: %d device object(s) left at exit.\n",
1656 smart_device::get_num_objects());
1662 printf("Please inform " PACKAGE_BUGREPORT
", including output of smartctl -V.\n");