2 * Home page of code is: http://smartmontools.sourceforge.net
4 * Copyright (C) 2002-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
5 * Copyright (C) 2000 Michael Cornwell <cornwell@acm.org>
6 * Copyright (C) 2008 Oliver Bock <brevilo@users.sourceforge.net>
7 * Copyright (C) 2008-15 Christian Franke <smartmontools-support@lists.sourceforge.net>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2, or (at your option)
14 * You should have received a copy of the GNU General Public License
15 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
17 * This code was originally developed as a Senior Thesis by Michael Cornwell
18 * at the Concurrent Systems Laboratory (now part of the Storage Systems
19 * Research Center), Jack Baskin School of Engineering, University of
20 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
27 // unconditionally included files
29 #include <sys/types.h>
30 #include <sys/stat.h> // umask
45 #include <algorithm> // std::replace()
47 // conditionally included files
60 #pragma warning(disable:4761) // "conversion supplied"
61 typedef unsigned short mode_t
;
64 #include <io.h> // umask()
65 #include <process.h> // getpid()
69 #include <io.h> // setmode()
76 // locally included files
78 #include "dev_interface.h"
79 #include "knowndrives.h"
83 // This is for solaris, where signal() resets the handler to SIG_DFL
84 // after the first signal is caught.
86 #define SIGNALFN sigset
88 #define SIGNALFN signal
92 // fork()/signal()/initd simulation for native Windows
93 #include "daemon_win32.h" // daemon_main/detach/signal()
95 #define SIGNALFN daemon_signal
96 #define strsignal daemon_strsignal
97 #define sleep daemon_sleep
98 // SIGQUIT does not exist, CONTROL-Break signals SIGBREAK.
99 #define SIGQUIT SIGBREAK
100 #define SIGQUIT_KEYNAME "CONTROL-Break"
102 #define SIGQUIT_KEYNAME "CONTROL-\\"
105 #if defined (__SVR4) && defined (__sun)
106 extern "C" int getdomainname(char *, int); // no declaration in header files!
109 const char * smartd_cpp_cvsid
= "$Id: smartd.cpp 4059 2015-04-18 17:01:31Z chrfranke $"
113 #define EXIT_BADCMD 1 // command line did not parse
114 #define EXIT_BADCONF 2 // syntax error in config file
115 #define EXIT_STARTUP 3 // problem forking daemon
116 #define EXIT_PID 4 // problem creating pid file
117 #define EXIT_NOCONF 5 // config file does not exist
118 #define EXIT_READCONF 6 // config file exists but cannot be read
120 #define EXIT_NOMEM 8 // out of memory
121 #define EXIT_BADCODE 10 // internal error - should NEVER happen
123 #define EXIT_BADDEV 16 // we can't monitor this device
124 #define EXIT_NODEV 17 // no devices to monitor
126 #define EXIT_SIGNAL 254 // abort on signal
129 // command-line: 1=debug mode, 2=print presets
130 static unsigned char debugmode
= 0;
132 // command-line: how long to sleep between checks
133 #define CHECKTIME 1800
134 static int checktime
=CHECKTIME
;
136 // command-line: name of PID file (empty for no pid file)
137 static std::string pid_file
;
139 // command-line: path prefix of persistent state file, empty if no persistence.
140 static std::string state_path_prefix
141 #ifdef SMARTMONTOOLS_SAVESTATES
142 = SMARTMONTOOLS_SAVESTATES
146 // command-line: path prefix of attribute log file, empty if no logs.
147 static std::string attrlog_path_prefix
148 #ifdef SMARTMONTOOLS_ATTRIBUTELOG
149 = SMARTMONTOOLS_ATTRIBUTELOG
153 // configuration file name
154 static const char * configfile
;
155 // configuration file "name" if read from stdin
156 static const char * const configfile_stdin
= "<stdin>";
157 // path of alternate configuration file
158 static std::string configfile_alt
;
160 // warning script file
161 static std::string warning_script
;
163 // command-line: when should we exit?
166 // command-line; this is the default syslog(3) log facility to use.
167 static int facility
=LOG_DAEMON
;
170 // command-line: fork into background?
171 static bool do_fork
=true;
174 #ifdef HAVE_LIBCAP_NG
175 // command-line: enable capabilities?
176 static bool enable_capabilities
= false;
179 // TODO: This smartctl only variable is also used in os_win32.cpp
180 unsigned char failuretest_permissive
= 0;
182 // set to one if we catch a USR1 (check devices now)
183 static volatile int caughtsigUSR1
=0;
186 // set to one if we catch a USR2 (toggle debug mode)
187 static volatile int caughtsigUSR2
=0;
190 // set to one if we catch a HUP (reload config file). In debug mode,
191 // set to two, if we catch INT (also reload config file).
192 static volatile int caughtsigHUP
=0;
194 // set to signal value if we catch INT, QUIT, or TERM
195 static volatile int caughtsigEXIT
=0;
197 // This function prints either to stdout or to the syslog as needed.
198 static void PrintOut(int priority
, const char *fmt
, ...)
199 __attribute_format_printf(2, 3);
201 // Attribute monitoring flags.
202 // See monitor_attr_flags below.
204 MONITOR_IGN_FAILUSE
= 0x01,
205 MONITOR_IGNORE
= 0x02,
206 MONITOR_RAW_PRINT
= 0x04,
208 MONITOR_AS_CRIT
= 0x10,
209 MONITOR_RAW_AS_CRIT
= 0x20,
212 // Array of flags for each attribute.
213 class attribute_flags
217 { memset(m_flags
, 0, sizeof(m_flags
)); }
219 bool is_set(int id
, unsigned char flag
) const
220 { return (0 < id
&& id
< (int)sizeof(m_flags
) && (m_flags
[id
] & flag
)); }
222 void set(int id
, unsigned char flags
)
224 if (0 < id
&& id
< (int)sizeof(m_flags
))
225 m_flags
[id
] |= flags
;
229 unsigned char m_flags
[256];
233 /// Configuration data for a device. Read from smartd.conf.
234 /// Supports copy & assignment and is compatible with STL containers.
237 int lineno
; // Line number of entry in file
238 std::string name
; // Device name (with optional extra info)
239 std::string dev_name
; // Device name (plain, for SMARTD_DEVICE variable)
240 std::string dev_type
; // Device type argument from -d directive, empty if none
241 std::string dev_idinfo
; // Device identify info for warning emails
242 std::string state_file
; // Path of the persistent state file, empty if none
243 std::string attrlog_file
; // Path of the persistent attrlog file, empty if none
244 bool ignore
; // Ignore this entry
245 bool smartcheck
; // Check SMART status
246 bool usagefailed
; // Check for failed Usage Attributes
247 bool prefail
; // Track changes in Prefail Attributes
248 bool usage
; // Track changes in Usage Attributes
249 bool selftest
; // Monitor number of selftest errors
250 bool errorlog
; // Monitor number of ATA errors
251 bool xerrorlog
; // Monitor number of ATA errors (Extended Comprehensive error log)
252 bool offlinests
; // Monitor changes in offline data collection status
253 bool offlinests_ns
; // Disable auto standby if in progress
254 bool selfteststs
; // Monitor changes in self-test execution status
255 bool selfteststs_ns
; // Disable auto standby if in progress
256 bool permissive
; // Ignore failed SMART commands
257 char autosave
; // 1=disable, 2=enable Autosave Attributes
258 char autoofflinetest
; // 1=disable, 2=enable Auto Offline Test
259 firmwarebug_defs firmwarebugs
; // -F directives from drivedb or smartd.conf
260 bool ignorepresets
; // Ignore database of -v options
261 bool showpresets
; // Show database entry for this device
262 bool removable
; // Device may disappear (not be present)
263 char powermode
; // skip check, if disk in idle or standby mode
264 bool powerquiet
; // skip powermode 'skipping checks' message
265 int powerskipmax
; // how many times can be check skipped
266 unsigned char tempdiff
; // Track Temperature changes >= this limit
267 unsigned char tempinfo
, tempcrit
; // Track Temperatures >= these limits as LOG_INFO, LOG_CRIT+mail
268 regular_expression test_regex
; // Regex for scheduled testing
270 // Configuration of email warning messages
271 std::string emailcmdline
; // script to execute, empty if no messages
272 std::string emailaddress
; // email address, or empty
273 unsigned char emailfreq
; // Emails once (1) daily (2) diminishing (3)
274 bool emailtest
; // Send test email?
277 int dev_rpm
; // rotation rate, 0 = unknown, 1 = SSD, >1 = HDD
278 int set_aam
; // disable(-1), enable(1..255->0..254) Automatic Acoustic Management
279 int set_apm
; // disable(-1), enable(2..255->1..254) Advanced Power Management
280 int set_lookahead
; // disable(-1), enable(1) read look-ahead
281 int set_standby
; // set(1..255->0..254) standby timer
282 bool set_security_freeze
; // Freeze ATA security
283 int set_wcache
; // disable(-1), enable(1) write cache
285 bool sct_erc_set
; // set SCT ERC to:
286 unsigned short sct_erc_readtime
; // ERC read time (deciseconds)
287 unsigned short sct_erc_writetime
; // ERC write time (deciseconds)
289 unsigned char curr_pending_id
; // ID of current pending sector count, 0 if none
290 unsigned char offl_pending_id
; // ID of offline uncorrectable sector count, 0 if none
291 bool curr_pending_incr
, offl_pending_incr
; // True if current/offline pending values increase
292 bool curr_pending_set
, offl_pending_set
; // True if '-C', '-U' set in smartd.conf
294 attribute_flags monitor_attr_flags
; // MONITOR_* flags for each attribute
296 ata_vendor_attr_defs attribute_defs
; // -v options
301 dev_config::dev_config()
311 offlinests(false), offlinests_ns(false),
312 selfteststs(false), selfteststs_ns(false),
316 ignorepresets(false),
323 tempinfo(0), tempcrit(0),
327 set_aam(0), set_apm(0),
330 set_security_freeze(false),
333 sct_erc_readtime(0), sct_erc_writetime(0),
334 curr_pending_id(0), offl_pending_id(0),
335 curr_pending_incr(false), offl_pending_incr(false),
336 curr_pending_set(false), offl_pending_set(false)
341 // Number of allowed mail message types
342 static const int SMARTD_NMAIL
= 13;
343 // Type for '-M test' mails (state not persistent)
344 static const int MAILTYPE_TEST
= 0;
345 // TODO: Add const or enum for all mail types.
348 int logged
;// number of times an email has been sent
349 time_t firstsent
;// time first email was sent, as defined by time(2)
350 time_t lastsent
; // time last email was sent, as defined by time(2)
353 : logged(0), firstsent(0), lastsent(0) { }
356 /// Persistent state data for a device.
357 struct persistent_dev_state
359 unsigned char tempmin
, tempmax
; // Min/Max Temperatures
361 unsigned char selflogcount
; // total number of self-test errors
362 unsigned short selfloghour
; // lifetime hours of last self-test error
364 time_t scheduled_test_next_check
; // Time of next check for scheduled self-tests
366 uint64_t selective_test_last_start
; // Start LBA of last scheduled selective self-test
367 uint64_t selective_test_last_end
; // End LBA of last scheduled selective self-test
369 mailinfo maillog
[SMARTD_NMAIL
]; // log info on when mail sent
372 int ataerrorcount
; // Total number of ATA errors
374 // Persistent part of ata_smart_values:
375 struct ata_attribute
{
378 unsigned char worst
; // Byte needed for 'raw64' attribute only.
382 ata_attribute() : id(0), val(0), worst(0), raw(0), resvd(0) { }
384 ata_attribute ata_attributes
[NUMBER_ATA_SMART_ATTRIBUTES
];
388 struct scsi_error_counter
{
389 struct scsiErrorCounter errCounter
;
391 scsi_error_counter() : found(0) { }
393 scsi_error_counter scsi_error_counters
[3];
395 struct scsi_nonmedium_error
{
396 struct scsiNonMediumError nme
;
398 scsi_nonmedium_error() : found(0) { }
400 scsi_nonmedium_error scsi_nonmedium_error
;
402 persistent_dev_state();
405 persistent_dev_state::persistent_dev_state()
406 : tempmin(0), tempmax(0),
409 scheduled_test_next_check(0),
410 selective_test_last_start(0),
411 selective_test_last_end(0),
416 /// Non-persistent state data for a device.
417 struct temp_dev_state
419 bool must_write
; // true if persistent part should be written
421 bool not_cap_offline
; // true == not capable of offline testing
422 bool not_cap_conveyance
;
425 bool not_cap_selective
;
427 unsigned char temperature
; // last recorded Temperature (in Celsius)
428 time_t tempmin_delay
; // time where Min Temperature tracking will start
430 bool powermodefail
; // true if power mode check failed
431 int powerskipcnt
; // Number of checks skipped due to idle or standby mode
434 unsigned char SmartPageSupported
; // has log sense IE page (0x2f)
435 unsigned char TempPageSupported
; // has log sense temperature page (0xd)
436 unsigned char ReadECounterPageSupported
;
437 unsigned char WriteECounterPageSupported
;
438 unsigned char VerifyECounterPageSupported
;
439 unsigned char NonMediumErrorPageSupported
;
440 unsigned char SuppressReport
; // minimize nuisance reports
441 unsigned char modese_len
; // mode sense/select cmd len: 0 (don't
444 uint64_t num_sectors
; // Number of sectors
445 ata_smart_values smartval
; // SMART data
446 ata_smart_thresholds_pvt smartthres
; // SMART thresholds
447 bool offline_started
; // true if offline data collection was started
448 bool selftest_started
; // true if self-test was started
453 temp_dev_state::temp_dev_state()
455 not_cap_offline(false),
456 not_cap_conveyance(false),
457 not_cap_short(false),
459 not_cap_selective(false),
462 powermodefail(false),
464 SmartPageSupported(false),
465 TempPageSupported(false),
466 ReadECounterPageSupported(false),
467 WriteECounterPageSupported(false),
468 VerifyECounterPageSupported(false),
469 NonMediumErrorPageSupported(false),
470 SuppressReport(false),
473 offline_started(false),
474 selftest_started(false)
476 memset(&smartval
, 0, sizeof(smartval
));
477 memset(&smartthres
, 0, sizeof(smartthres
));
480 /// Runtime state data for a device.
482 : public persistent_dev_state
,
483 public temp_dev_state
485 void update_persistent_state();
486 void update_temp_state();
489 /// Container for configuration info for each device.
490 typedef std::vector
<dev_config
> dev_config_vector
;
492 /// Container for state info for each device.
493 typedef std::vector
<dev_state
> dev_state_vector
;
495 // Copy ATA attributes to persistent state.
496 void dev_state::update_persistent_state()
498 for (int i
= 0; i
< NUMBER_ATA_SMART_ATTRIBUTES
; i
++) {
499 const ata_smart_attribute
& ta
= smartval
.vendor_attributes
[i
];
500 ata_attribute
& pa
= ata_attributes
[i
];
503 pa
.val
= pa
.worst
= 0; pa
.raw
= 0;
511 | ((uint64_t)ta
.raw
[3] << 24)
512 | ((uint64_t)ta
.raw
[4] << 32)
513 | ((uint64_t)ta
.raw
[5] << 40);
514 pa
.resvd
= ta
.reserv
;
518 // Copy ATA from persistent to temp state.
519 void dev_state::update_temp_state()
521 for (int i
= 0; i
< NUMBER_ATA_SMART_ATTRIBUTES
; i
++) {
522 const ata_attribute
& pa
= ata_attributes
[i
];
523 ata_smart_attribute
& ta
= smartval
.vendor_attributes
[i
];
526 ta
.current
= ta
.worst
= 0;
527 memset(ta
.raw
, 0, sizeof(ta
.raw
));
532 ta
.raw
[0] = (unsigned char) pa
.raw
;
533 ta
.raw
[1] = (unsigned char)(pa
.raw
>> 8);
534 ta
.raw
[2] = (unsigned char)(pa
.raw
>> 16);
535 ta
.raw
[3] = (unsigned char)(pa
.raw
>> 24);
536 ta
.raw
[4] = (unsigned char)(pa
.raw
>> 32);
537 ta
.raw
[5] = (unsigned char)(pa
.raw
>> 40);
538 ta
.reserv
= pa
.resvd
;
542 // Parse a line from a state file.
543 static bool parse_dev_state_line(const char * line
, persistent_dev_state
& state
)
545 static const regular_expression
regex(
547 "((temperature-min)" // (1 (2)
548 "|(temperature-max)" // (3)
549 "|(self-test-errors)" // (4)
550 "|(self-test-last-err-hour)" // (5)
551 "|(scheduled-test-next-check)" // (6)
552 "|(selective-test-last-start)" // (7)
553 "|(selective-test-last-end)" // (8)
554 "|(ata-error-count)" // (9)
555 "|(mail\\.([0-9]+)\\." // (10 (11)
556 "((count)" // (12 (13)
557 "|(first-sent-time)" // (14)
558 "|(last-sent-time)" // (15)
561 "|(ata-smart-attribute\\.([0-9]+)\\." // (16 (17)
570 " *= *([0-9]+)[ \n]*$", // (24)
574 const int nmatch
= 1+24;
575 regmatch_t match
[nmatch
];
576 if (!regex
.execute(line
, nmatch
, match
))
578 if (match
[nmatch
-1].rm_so
< 0)
581 uint64_t val
= strtoull(line
+ match
[nmatch
-1].rm_so
, (char **)0, 10);
584 if (match
[++m
].rm_so
>= 0)
585 state
.tempmin
= (unsigned char)val
;
586 else if (match
[++m
].rm_so
>= 0)
587 state
.tempmax
= (unsigned char)val
;
588 else if (match
[++m
].rm_so
>= 0)
589 state
.selflogcount
= (unsigned char)val
;
590 else if (match
[++m
].rm_so
>= 0)
591 state
.selfloghour
= (unsigned short)val
;
592 else if (match
[++m
].rm_so
>= 0)
593 state
.scheduled_test_next_check
= (time_t)val
;
594 else if (match
[++m
].rm_so
>= 0)
595 state
.selective_test_last_start
= val
;
596 else if (match
[++m
].rm_so
>= 0)
597 state
.selective_test_last_end
= val
;
598 else if (match
[++m
].rm_so
>= 0)
599 state
.ataerrorcount
= (int)val
;
600 else if (match
[m
+=2].rm_so
>= 0) {
601 int i
= atoi(line
+match
[m
].rm_so
);
602 if (!(0 <= i
&& i
< SMARTD_NMAIL
))
604 if (i
== MAILTYPE_TEST
) // Don't suppress test mails
606 if (match
[m
+=2].rm_so
>= 0)
607 state
.maillog
[i
].logged
= (int)val
;
608 else if (match
[++m
].rm_so
>= 0)
609 state
.maillog
[i
].firstsent
= (time_t)val
;
610 else if (match
[++m
].rm_so
>= 0)
611 state
.maillog
[i
].lastsent
= (time_t)val
;
615 else if (match
[m
+=5+1].rm_so
>= 0) {
616 int i
= atoi(line
+match
[m
].rm_so
);
617 if (!(0 <= i
&& i
< NUMBER_ATA_SMART_ATTRIBUTES
))
619 if (match
[m
+=2].rm_so
>= 0)
620 state
.ata_attributes
[i
].id
= (unsigned char)val
;
621 else if (match
[++m
].rm_so
>= 0)
622 state
.ata_attributes
[i
].val
= (unsigned char)val
;
623 else if (match
[++m
].rm_so
>= 0)
624 state
.ata_attributes
[i
].worst
= (unsigned char)val
;
625 else if (match
[++m
].rm_so
>= 0)
626 state
.ata_attributes
[i
].raw
= val
;
627 else if (match
[++m
].rm_so
>= 0)
628 state
.ata_attributes
[i
].resvd
= (unsigned char)val
;
637 // Read a state file.
638 static bool read_dev_state(const char * path
, persistent_dev_state
& state
)
640 stdio_file
f(path
, "r");
643 pout("Cannot read state file \"%s\"\n", path
);
647 setmode(fileno(f
), O_TEXT
); // Allow files with \r\n
650 persistent_dev_state new_state
;
651 int good
= 0, bad
= 0;
653 while (fgets(line
, sizeof(line
), f
)) {
654 const char * s
= line
+ strspn(line
, " \t");
655 if (!*s
|| *s
== '#')
657 if (!parse_dev_state_line(line
, new_state
))
665 pout("%s: format error\n", path
);
668 pout("%s: %d invalid line(s) ignored\n", path
, bad
);
671 // This sets the values missing in the file to 0.
676 static void write_dev_state_line(FILE * f
, const char * name
, uint64_t val
)
679 fprintf(f
, "%s = %" PRIu64
"\n", name
, val
);
682 static void write_dev_state_line(FILE * f
, const char * name1
, int id
, const char * name2
, uint64_t val
)
685 fprintf(f
, "%s.%d.%s = %" PRIu64
"\n", name1
, id
, name2
, val
);
688 // Write a state file
689 static bool write_dev_state(const char * path
, const persistent_dev_state
& state
)
691 // Rename old "file" to "file~"
692 std::string pathbak
= path
; pathbak
+= '~';
693 unlink(pathbak
.c_str());
694 rename(path
, pathbak
.c_str());
696 stdio_file
f(path
, "w");
698 pout("Cannot create state file \"%s\"\n", path
);
702 fprintf(f
, "# smartd state file\n");
703 write_dev_state_line(f
, "temperature-min", state
.tempmin
);
704 write_dev_state_line(f
, "temperature-max", state
.tempmax
);
705 write_dev_state_line(f
, "self-test-errors", state
.selflogcount
);
706 write_dev_state_line(f
, "self-test-last-err-hour", state
.selfloghour
);
707 write_dev_state_line(f
, "scheduled-test-next-check", state
.scheduled_test_next_check
);
708 write_dev_state_line(f
, "selective-test-last-start", state
.selective_test_last_start
);
709 write_dev_state_line(f
, "selective-test-last-end", state
.selective_test_last_end
);
712 for (i
= 0; i
< SMARTD_NMAIL
; i
++) {
713 if (i
== MAILTYPE_TEST
) // Don't suppress test mails
715 const mailinfo
& mi
= state
.maillog
[i
];
718 write_dev_state_line(f
, "mail", i
, "count", mi
.logged
);
719 write_dev_state_line(f
, "mail", i
, "first-sent-time", mi
.firstsent
);
720 write_dev_state_line(f
, "mail", i
, "last-sent-time", mi
.lastsent
);
724 write_dev_state_line(f
, "ata-error-count", state
.ataerrorcount
);
726 for (i
= 0; i
< NUMBER_ATA_SMART_ATTRIBUTES
; i
++) {
727 const persistent_dev_state::ata_attribute
& pa
= state
.ata_attributes
[i
];
730 write_dev_state_line(f
, "ata-smart-attribute", i
, "id", pa
.id
);
731 write_dev_state_line(f
, "ata-smart-attribute", i
, "val", pa
.val
);
732 write_dev_state_line(f
, "ata-smart-attribute", i
, "worst", pa
.worst
);
733 write_dev_state_line(f
, "ata-smart-attribute", i
, "raw", pa
.raw
);
734 write_dev_state_line(f
, "ata-smart-attribute", i
, "resvd", pa
.resvd
);
740 // Write to the attrlog file
741 static bool write_dev_attrlog(const char * path
, const dev_state
& state
)
743 stdio_file
f(path
, "a");
745 pout("Cannot create attribute log file \"%s\"\n", path
);
750 time_t now
= time(0);
751 struct tm
* tms
= gmtime(&now
);
752 fprintf(f
, "%d-%02d-%02d %02d:%02d:%02d;",
753 1900+tms
->tm_year
, 1+tms
->tm_mon
, tms
->tm_mday
,
754 tms
->tm_hour
, tms
->tm_min
, tms
->tm_sec
);
756 for (int i
= 0; i
< NUMBER_ATA_SMART_ATTRIBUTES
; i
++) {
757 const persistent_dev_state::ata_attribute
& pa
= state
.ata_attributes
[i
];
760 fprintf(f
, "\t%d;%d;%" PRIu64
";", pa
.id
, pa
.val
, pa
.raw
);
763 const struct scsiErrorCounter
* ecp
;
764 const char * pageNames
[3] = {"read", "write", "verify"};
765 for (int k
= 0; k
< 3; ++k
) {
766 if ( !state
.scsi_error_counters
[k
].found
) continue;
767 ecp
= &state
.scsi_error_counters
[k
].errCounter
;
768 fprintf(f
, "\t%s-corr-by-ecc-fast;%" PRIu64
";"
769 "\t%s-corr-by-ecc-delayed;%" PRIu64
";"
770 "\t%s-corr-by-retry;%" PRIu64
";"
771 "\t%s-total-err-corrected;%" PRIu64
";"
772 "\t%s-corr-algorithm-invocations;%" PRIu64
";"
773 "\t%s-gb-processed;%.3f;"
774 "\t%s-total-unc-errors;%" PRIu64
";",
775 pageNames
[k
], ecp
->counter
[0],
776 pageNames
[k
], ecp
->counter
[1],
777 pageNames
[k
], ecp
->counter
[2],
778 pageNames
[k
], ecp
->counter
[3],
779 pageNames
[k
], ecp
->counter
[4],
780 pageNames
[k
], (ecp
->counter
[5] / 1000000000.0),
781 pageNames
[k
], ecp
->counter
[6]);
783 if(state
.scsi_nonmedium_error
.found
&& state
.scsi_nonmedium_error
.nme
.gotPC0
) {
784 fprintf(f
, "\tnon-medium-errors;%" PRIu64
";", state
.scsi_nonmedium_error
.nme
.counterPC0
);
786 // write SCSI current temperature if it is monitored
787 if(state
.TempPageSupported
&& state
.temperature
)
788 fprintf(f
, "\ttemperature;%d;", state
.temperature
);
794 // Write all state files. If write_always is false, don't write
795 // unless must_write is set.
796 static void write_all_dev_states(const dev_config_vector
& configs
,
797 dev_state_vector
& states
,
798 bool write_always
= true)
800 for (unsigned i
= 0; i
< states
.size(); i
++) {
801 const dev_config
& cfg
= configs
.at(i
);
802 if (cfg
.state_file
.empty())
804 dev_state
& state
= states
[i
];
805 if (!write_always
&& !state
.must_write
)
807 if (!write_dev_state(cfg
.state_file
.c_str(), state
))
809 state
.must_write
= false;
810 if (write_always
|| debugmode
)
811 PrintOut(LOG_INFO
, "Device: %s, state written to %s\n",
812 cfg
.name
.c_str(), cfg
.state_file
.c_str());
816 // Write to all attrlog files
817 static void write_all_dev_attrlogs(const dev_config_vector
& configs
,
818 dev_state_vector
& states
)
820 for (unsigned i
= 0; i
< states
.size(); i
++) {
821 const dev_config
& cfg
= configs
.at(i
);
822 if (cfg
.attrlog_file
.empty())
824 dev_state
& state
= states
[i
];
825 write_dev_attrlog(cfg
.attrlog_file
.c_str(), state
);
829 // remove the PID file
830 static void RemovePidFile()
832 if (!pid_file
.empty()) {
833 if (unlink(pid_file
.c_str()))
834 PrintOut(LOG_CRIT
,"Can't unlink PID file %s (%s).\n",
835 pid_file
.c_str(), strerror(errno
));
841 extern "C" { // signal handlers require C-linkage
843 // Note if we catch a SIGUSR1
844 static void USR1handler(int sig
)
852 // Note if we catch a SIGUSR2
853 static void USR2handler(int sig
)
861 // Note if we catch a HUP (or INT in debug mode)
862 static void HUPhandler(int sig
)
871 // signal handler for TERM, QUIT, and INT (if not in debug mode)
872 static void sighandler(int sig
)
881 // Cleanup, print Goodbye message and remove pidfile
882 static int Goodbye(int status
)
884 // delete PID file, if one was created
887 // if we are exiting because of a code bug, tell user
888 if (status
==EXIT_BADCODE
)
889 PrintOut(LOG_CRIT
, "Please inform " PACKAGE_BUGREPORT
", including output of smartd -V.\n");
891 // and this should be the final output from smartd before it exits
892 PrintOut(status
?LOG_CRIT
:LOG_INFO
, "smartd is exiting (exit status %d)\n", status
);
897 // a replacement for setenv() which is not available on all platforms.
898 // Note that the string passed to putenv must not be freed or made
899 // invalid, since a pointer to it is kept by putenv(). This means that
900 // it must either be a static buffer or allocated off the heap. The
901 // string can be freed if the environment variable is redefined via
902 // another call to putenv(). There is no portable way to unset a variable
903 // with putenv(). So we manage the buffer in a static object.
904 // Using setenv() if available is not considered because some
905 // implementations may produce memory leaks.
911 : m_buf((char *)0) { }
913 void set(const char * name
, const char * value
);
918 env_buffer(const env_buffer
&);
919 void operator=(const env_buffer
&);
922 void env_buffer::set(const char * name
, const char * value
)
924 int size
= strlen(name
) + 1 + strlen(value
) + 1;
925 char * newbuf
= new char[size
];
926 snprintf(newbuf
, size
, "%s=%s", name
, value
);
929 throw std::runtime_error("putenv() failed");
931 // This assumes that the same NAME is passed on each call
938 static void MailWarning(const dev_config
& cfg
, dev_state
& state
, int which
, const char *fmt
, ...)
939 __attribute_format_printf(4, 5);
941 // If either address or executable path is non-null then send and log
942 // a warning email, or execute executable
943 static void MailWarning(const dev_config
& cfg
, dev_state
& state
, int which
, const char *fmt
, ...)
945 static const char * const whichfail
[] = {
951 "FailedHealthCheck", // 5
952 "FailedReadSmartData", // 6
953 "FailedReadSmartErrorLog", // 7
954 "FailedReadSmartSelfTestLog", // 8
955 "FailedOpenDevice", // 9
956 "CurrentPendingSector", // 10
957 "OfflineUncorrectableSector", // 11
961 // See if user wants us to send mail
962 if (cfg
.emailaddress
.empty() && cfg
.emailcmdline
.empty())
965 std::string address
= cfg
.emailaddress
;
966 const char * executable
= cfg
.emailcmdline
.c_str();
968 // which type of mail are we sending?
969 mailinfo
* mail
=(state
.maillog
)+which
;
972 if (cfg
.emailfreq
<1 || cfg
.emailfreq
>3) {
973 PrintOut(LOG_CRIT
,"internal error in MailWarning(): cfg.mailwarn->emailfreq=%d\n",cfg
.emailfreq
);
976 if (which
<0 || which
>=SMARTD_NMAIL
|| sizeof(whichfail
)!=SMARTD_NMAIL
*sizeof(char *)) {
977 PrintOut(LOG_CRIT
,"Contact " PACKAGE_BUGREPORT
"; internal error in MailWarning(): which=%d, size=%d\n",
978 which
, (int)sizeof(whichfail
));
982 // Return if a single warning mail has been sent.
983 if ((cfg
.emailfreq
==1) && mail
->logged
)
986 // Return if this is an email test and one has already been sent.
987 if (which
== 0 && mail
->logged
)
990 // To decide if to send mail, we need to know what time it is.
991 time_t epoch
= time(0);
993 // Return if less than one day has gone by
994 const int day
= 24*3600;
995 if (cfg
.emailfreq
==2 && mail
->logged
&& epoch
<(mail
->lastsent
+day
))
998 // Return if less than 2^(logged-1) days have gone by
999 if (cfg
.emailfreq
==3 && mail
->logged
) {
1000 int days
= 0x01 << (mail
->logged
- 1);
1002 if (epoch
<(mail
->lastsent
+days
))
1006 #ifdef HAVE_LIBCAP_NG
1007 if (enable_capabilities
) {
1008 PrintOut(LOG_ERR
, "Sending a mail was supressed. "
1009 "Mails can't be send when capabilites are enabled\n");
1014 // record the time of this mail message, and the first mail message
1016 mail
->firstsent
=epoch
;
1017 mail
->lastsent
=epoch
;
1019 // print warning string into message
1023 vsnprintf(message
, sizeof(message
), fmt
, ap
);
1026 // replace commas by spaces to separate recipients
1027 std::replace(address
.begin(), address
.end(), ',', ' ');
1029 // Export information in environment variables that will be useful
1031 static env_buffer env
[12];
1032 env
[0].set("SMARTD_MAILER", executable
);
1033 env
[1].set("SMARTD_MESSAGE", message
);
1034 char dates
[DATEANDEPOCHLEN
];
1035 snprintf(dates
, sizeof(dates
), "%d", mail
->logged
);
1036 env
[2].set("SMARTD_PREVCNT", dates
);
1037 dateandtimezoneepoch(dates
, mail
->firstsent
);
1038 env
[3].set("SMARTD_TFIRST", dates
);
1039 snprintf(dates
, DATEANDEPOCHLEN
,"%d", (int)mail
->firstsent
);
1040 env
[4].set("SMARTD_TFIRSTEPOCH", dates
);
1041 env
[5].set("SMARTD_FAILTYPE", whichfail
[which
]);
1042 env
[6].set("SMARTD_ADDRESS", address
.c_str());
1043 env
[7].set("SMARTD_DEVICESTRING", cfg
.name
.c_str());
1045 // Allow 'smartctl ... -d $SMARTD_DEVICETYPE $SMARTD_DEVICE'
1046 env
[8].set("SMARTD_DEVICETYPE",
1047 (!cfg
.dev_type
.empty() ? cfg
.dev_type
.c_str() : "auto"));
1048 env
[9].set("SMARTD_DEVICE", cfg
.dev_name
.c_str());
1050 env
[10].set("SMARTD_DEVICEINFO", cfg
.dev_idinfo
.c_str());
1052 if (which
) switch (cfg
.emailfreq
) {
1053 case 2: dates
[0] = '1'; dates
[1] = 0; break;
1054 case 3: snprintf(dates
, sizeof(dates
), "%d", (0x01)<<mail
->logged
);
1056 env
[11].set("SMARTD_NEXTDAYS", dates
);
1058 // now construct a command to send this as EMAIL
1061 executable
= "<mail>";
1062 const char * newadd
= (!address
.empty()? address
.c_str() : "<nomailer>");
1063 const char * newwarn
= (which
? "Warning via" : "Test of");
1066 snprintf(command
, sizeof(command
), "%s 2>&1", warning_script
.c_str());
1068 // tell SYSLOG what we are about to do...
1069 PrintOut(LOG_INFO
,"%s %s to %s ...\n",
1070 which
?"Sending warning via":"Executing test of", executable
, newadd
);
1072 // issue the command to send mail or to run the user's executable
1075 if (!(pfp
=popen(command
, "r")))
1076 // failed to popen() mail process
1077 PrintOut(LOG_CRIT
,"%s %s to %s: failed (fork or pipe failed, or no memory) %s\n",
1078 newwarn
, executable
, newadd
, errno
?strerror(errno
):"");
1082 char buffer
[EBUFLEN
];
1084 // if unexpected output on stdout/stderr, null terminate, print, and flush
1085 if ((len
=fread(buffer
, 1, EBUFLEN
, pfp
))) {
1087 int newlen
= len
<EBUFLEN
? len
: EBUFLEN
-1;
1088 buffer
[newlen
]='\0';
1089 PrintOut(LOG_CRIT
,"%s %s to %s produced unexpected output (%s%d bytes) to STDOUT/STDERR: \n%s\n",
1090 newwarn
, executable
, newadd
, len
!=newlen
?"here truncated to ":"", newlen
, buffer
);
1092 // flush pipe if needed
1093 while (fread(buffer
, 1, EBUFLEN
, pfp
) && count
<EBUFLEN
)
1096 // tell user that pipe was flushed, or that something is really wrong
1097 if (count
&& count
<EBUFLEN
)
1098 PrintOut(LOG_CRIT
,"%s %s to %s: flushed remaining STDOUT/STDERR\n",
1099 newwarn
, executable
, newadd
);
1101 PrintOut(LOG_CRIT
,"%s %s to %s: more than 1 MB STDOUT/STDERR flushed, breaking pipe\n",
1102 newwarn
, executable
, newadd
);
1105 // if something went wrong with mail process, print warning
1107 if (-1==(status
=pclose(pfp
)))
1108 PrintOut(LOG_CRIT
,"%s %s to %s: pclose(3) failed %s\n", newwarn
, executable
, newadd
,
1109 errno
?strerror(errno
):"");
1111 // mail process apparently succeeded. Check and report exit status
1114 if (WIFEXITED(status
)) {
1115 // exited 'normally' (but perhaps with nonzero status)
1116 status8
=WEXITSTATUS(status
);
1119 PrintOut(LOG_CRIT
,"%s %s to %s: failed (32-bit/8-bit exit status: %d/%d) perhaps caught signal %d [%s]\n",
1120 newwarn
, executable
, newadd
, status
, status8
, status8
-128, strsignal(status8
-128));
1122 PrintOut(LOG_CRIT
,"%s %s to %s: failed (32-bit/8-bit exit status: %d/%d)\n",
1123 newwarn
, executable
, newadd
, status
, status8
);
1125 PrintOut(LOG_INFO
,"%s %s to %s: successful\n", newwarn
, executable
, newadd
);
1128 if (WIFSIGNALED(status
))
1129 PrintOut(LOG_INFO
,"%s %s to %s: exited because of uncaught signal %d [%s]\n",
1130 newwarn
, executable
, newadd
, WTERMSIG(status
), strsignal(WTERMSIG(status
)));
1132 // this branch is probably not possible. If subprocess is
1133 // stopped then pclose() should not return.
1134 if (WIFSTOPPED(status
))
1135 PrintOut(LOG_CRIT
,"%s %s to %s: process STOPPED because it caught signal %d [%s]\n",
1136 newwarn
, executable
, newadd
, WSTOPSIG(status
), strsignal(WSTOPSIG(status
)));
1143 snprintf(command
, sizeof(command
), "cmd /c \"%s\"", warning_script
.c_str());
1145 char stdoutbuf
[800]; // < buffer in syslog_win32::vsyslog()
1148 PrintOut(LOG_INFO
,"%s %s to %s ...\n",
1149 (which
?"Sending warning via":"Executing test of"), executable
, newadd
);
1150 rc
= daemon_spawn(command
, "", 0, stdoutbuf
, sizeof(stdoutbuf
));
1151 if (rc
>= 0 && stdoutbuf
[0])
1152 PrintOut(LOG_CRIT
,"%s %s to %s produced unexpected output (%d bytes) to STDOUT/STDERR:\n%s\n",
1153 newwarn
, executable
, newadd
, (int)strlen(stdoutbuf
), stdoutbuf
);
1155 PrintOut(LOG_CRIT
,"%s %s to %s: failed, exit status %d\n",
1156 newwarn
, executable
, newadd
, rc
);
1158 PrintOut(LOG_INFO
,"%s %s to %s: successful\n", newwarn
, executable
, newadd
);
1163 // increment mail sent counter
1167 static void reset_warning_mail(const dev_config
& cfg
, dev_state
& state
, int which
, const char *fmt
, ...)
1168 __attribute_format_printf(4, 5);
1170 static void reset_warning_mail(const dev_config
& cfg
, dev_state
& state
, int which
, const char *fmt
, ...)
1172 if (!(0 <= which
&& which
< SMARTD_NMAIL
))
1175 // Return if no mail sent yet
1176 mailinfo
& mi
= state
.maillog
[which
];
1180 // Format & print message
1184 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
1187 PrintOut(LOG_INFO
, "Device: %s, %s, warning condition reset after %d email%s\n", cfg
.name
.c_str(),
1188 msg
, mi
.logged
, (mi
.logged
==1 ? "" : "s"));
1190 // Clear mail counter and timestamps
1192 state
.must_write
= true;
1197 // Output multiple lines via separate syslog(3) calls.
1198 static void vsyslog_lines(int priority
, const char * fmt
, va_list ap
)
1200 char buf
[512+EBUFLEN
]; // enough space for exec cmd output in MailWarning()
1201 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1203 for (char * p
= buf
, * q
; p
&& *p
; p
= q
) {
1204 if ((q
= strchr(p
, '\n')))
1207 syslog(priority
, "%s\n", p
);
1212 // os_win32/syslog_win32.cpp supports multiple lines.
1213 #define vsyslog_lines vsyslog
1216 // Printing function for watching ataprint commands, or losing them
1217 // [From GLIBC Manual: Since the prototype doesn't specify types for
1218 // optional arguments, in a call to a variadic function the default
1219 // argument promotions are performed on the optional argument
1220 // values. This means the objects of type char or short int (whether
1221 // signed or not) are promoted to either int or unsigned int, as
1223 void pout(const char *fmt
, ...){
1226 // get the correct time in syslog()
1227 FixGlibcTimeZoneBug();
1228 // initialize variable argument list
1230 // in debugmode==1 mode we will print the output from the ataprint.o functions!
1231 if (debugmode
&& debugmode
!= 2) {
1234 if (facility
== LOG_LOCAL1
) // logging to stdout
1237 vfprintf(f
, fmt
, ap
);
1240 // in debugmode==2 mode we print output from knowndrives.o functions
1241 else if (debugmode
==2 || ata_debugmode
|| scsi_debugmode
) {
1242 openlog("smartd", LOG_PID
, facility
);
1243 vsyslog_lines(LOG_INFO
, fmt
, ap
);
1250 // This function prints either to stdout or to the syslog as needed.
1251 static void PrintOut(int priority
, const char *fmt
, ...){
1254 // get the correct time in syslog()
1255 FixGlibcTimeZoneBug();
1256 // initialize variable argument list
1261 if (facility
== LOG_LOCAL1
) // logging to stdout
1264 vfprintf(f
, fmt
, ap
);
1268 openlog("smartd", LOG_PID
, facility
);
1269 vsyslog_lines(priority
, fmt
, ap
);
1276 // Used to warn users about invalid checksums. Called from atacmds.cpp.
1277 void checksumwarning(const char * string
)
1279 pout("Warning! %s error: invalid SMART checksum.\n", string
);
1284 // Wait for the pid file to show up, this makes sure a calling program knows
1285 // that the daemon is really up and running and has a pid to kill it
1286 static bool WaitForPidFile()
1288 int waited
, max_wait
= 10;
1289 struct stat stat_buf
;
1291 if (pid_file
.empty() || debugmode
)
1294 for(waited
= 0; waited
< max_wait
; ++waited
) {
1295 if (!stat(pid_file
.c_str(), &stat_buf
)) {
1305 // Forks new process, closes ALL file descriptors, redirects stdin,
1306 // stdout, and stderr. Not quite daemon(). See
1307 // http://www.linuxjournal.com/article/2335
1308 // for a good description of why we do things this way.
1309 static void DaemonInit()
1315 // flush all buffered streams. Else we might get two copies of open
1316 // streams since both parent and child get copies of the buffers.
1320 if ((pid
=fork()) < 0) {
1322 PrintOut(LOG_CRIT
,"smartd unable to fork daemon process!\n");
1326 // we are the parent process, wait for pid file, then exit cleanly
1327 if(!WaitForPidFile()) {
1328 PrintOut(LOG_CRIT
,"PID file %s didn't show up!\n", pid_file
.c_str());
1334 // from here on, we are the child process.
1337 // Fork one more time to avoid any possibility of having terminals
1338 if ((pid
=fork()) < 0) {
1340 PrintOut(LOG_CRIT
,"smartd unable to fork daemon process!\n");
1344 // we are the parent process -- exit cleanly
1347 // Now we are the child's child...
1350 // close any open file descriptors
1351 for (i
=getdtablesize();i
>=0;--i
)
1354 #define NO_warn_unused_result(cmd) { if (cmd) {} ; }
1356 // redirect any IO attempts to /dev/null for stdin
1357 i
=open("/dev/null",O_RDWR
);
1360 NO_warn_unused_result(dup(i
));
1362 NO_warn_unused_result(dup(i
));
1365 NO_warn_unused_result(chdir("/"));
1368 PrintOut(LOG_INFO
, "smartd has fork()ed into background mode. New PID=%d.\n", (int)getpid());
1372 // No fork() on native Win32
1373 // Detach this process from console
1375 if (daemon_detach("smartd")) {
1376 PrintOut(LOG_CRIT
,"smartd unable to detach from console!\n");
1379 // stdin/out/err now closed if not redirected
1385 // create a PID file containing the current process id
1386 static void WritePidFile()
1388 if (!pid_file
.empty()) {
1389 pid_t pid
= getpid();
1392 old_umask
= umask(0077); // rwx------
1394 // Cygwin: smartd service runs on system account, ensure PID file can be read by admins
1395 old_umask
= umask(0033); // rwxr--r--
1398 stdio_file
f(pid_file
.c_str(), "w");
1400 if (!(f
&& fprintf(f
, "%d\n", (int)pid
) > 0 && f
.close())) {
1401 PrintOut(LOG_CRIT
, "unable to write PID file %s - exiting.\n", pid_file
.c_str());
1404 PrintOut(LOG_INFO
, "file %s written containing PID %d\n", pid_file
.c_str(), (int)pid
);
1408 // Prints header identifying version of code and home
1409 static void PrintHead()
1411 PrintOut(LOG_INFO
, "%s\n", format_version_info("smartd").c_str());
1414 // prints help info for configuration file Directives
1415 static void Directives()
1418 "Configuration file (%s) Directives (after device name):\n"
1419 " -d TYPE Set the device type: auto, ignore, removable,\n"
1421 " -T TYPE Set the tolerance to one of: normal, permissive\n"
1422 " -o VAL Enable/disable automatic offline tests (on/off)\n"
1423 " -S VAL Enable/disable attribute autosave (on/off)\n"
1424 " -n MODE No check if: never, sleep[,N][,q], standby[,N][,q], idle[,N][,q]\n"
1425 " -H Monitor SMART Health Status, report if failed\n"
1426 " -s REG Do Self-Test at time(s) given by regular expression REG\n"
1427 " -l TYPE Monitor SMART log or self-test status:\n"
1428 " error, selftest, xerror, offlinests[,ns], selfteststs[,ns]\n"
1429 " -l scterc,R,W Set SCT Error Recovery Control\n"
1430 " -e Change device setting: aam,[N|off], apm,[N|off], lookahead,[on|off],\n"
1431 " security-freeze, standby,[N|off], wcache,[on|off]\n"
1432 " -f Monitor 'Usage' Attributes, report failures\n"
1433 " -m ADD Send email warning to address ADD\n"
1434 " -M TYPE Modify email warning behavior (see man page)\n"
1435 " -p Report changes in 'Prefailure' Attributes\n"
1436 " -u Report changes in 'Usage' Attributes\n"
1437 " -t Equivalent to -p and -u Directives\n"
1438 " -r ID Also report Raw values of Attribute ID with -p, -u or -t\n"
1439 " -R ID Track changes in Attribute ID Raw value with -p, -u or -t\n"
1440 " -i ID Ignore Attribute ID for -f Directive\n"
1441 " -I ID Ignore Attribute ID for -p, -u or -t Directive\n"
1442 " -C ID[+] Monitor [increases of] Current Pending Sectors in Attribute ID\n"
1443 " -U ID[+] Monitor [increases of] Offline Uncorrectable Sectors in Attribute ID\n"
1444 " -W D,I,C Monitor Temperature D)ifference, I)nformal limit, C)ritical limit\n"
1445 " -v N,ST Modifies labeling of Attribute N (see man page) \n"
1446 " -P TYPE Drive-specific presets: use, ignore, show, showall\n"
1447 " -a Default: -H -f -t -l error -l selftest -l selfteststs -C 197 -U 198\n"
1448 " -F TYPE Use firmware bug workaround:\n"
1450 " # Comment: text after a hash sign is ignored\n"
1451 " \\ Line continuation character\n"
1452 "Attribute ID is a decimal integer 1 <= ID <= 255\n"
1453 "Use ID = 0 to turn off -C and/or -U Directives\n"
1454 "Example: /dev/sda -a\n",
1456 smi()->get_valid_dev_types_str().c_str(),
1457 get_valid_firmwarebug_args());
1460 /* Returns a pointer to a static string containing a formatted list of the valid
1461 arguments to the option opt or NULL on failure. */
1462 static const char *GetValidArgList(char opt
)
1467 return "<PATH_PREFIX>";
1469 return "<FILE_NAME>, -";
1471 return "daemon, local0, local1, local2, local3, local4, local5, local6, local7";
1473 return "nodev, errors, nodevstartup, never, onecheck, showtests";
1475 return "ioctl[,N], ataioctl[,N], scsiioctl[,N]";
1479 return "<FILE_NAME>";
1481 return "<INTEGER_SECONDS>";
1487 /* prints help information for command syntax */
1490 PrintOut(LOG_INFO
,"Usage: smartd [options]\n\n");
1491 PrintOut(LOG_INFO
," -A PREFIX, --attributelog=PREFIX\n");
1492 PrintOut(LOG_INFO
," Log ATA attribute information to {PREFIX}MODEL-SERIAL.ata.csv\n");
1493 #ifdef SMARTMONTOOLS_ATTRIBUTELOG
1494 PrintOut(LOG_INFO
," [default is " SMARTMONTOOLS_ATTRIBUTELOG
"MODEL-SERIAL.ata.csv]\n");
1496 PrintOut(LOG_INFO
,"\n");
1497 PrintOut(LOG_INFO
," -B [+]FILE, --drivedb=[+]FILE\n");
1498 PrintOut(LOG_INFO
," Read and replace [add] drive database from FILE\n");
1499 PrintOut(LOG_INFO
," [default is +%s", get_drivedb_path_add());
1500 #ifdef SMARTMONTOOLS_DRIVEDBDIR
1501 PrintOut(LOG_INFO
,"\n");
1502 PrintOut(LOG_INFO
," and then %s", get_drivedb_path_default());
1504 PrintOut(LOG_INFO
,"]\n\n");
1505 PrintOut(LOG_INFO
," -c NAME|-, --configfile=NAME|-\n");
1506 PrintOut(LOG_INFO
," Read configuration file NAME or stdin\n");
1507 PrintOut(LOG_INFO
," [default is %s]\n\n", configfile
);
1508 #ifdef HAVE_LIBCAP_NG
1509 PrintOut(LOG_INFO
," -C, --capabilities\n");
1510 PrintOut(LOG_INFO
," Drop unneeded Linux process capabilities.\n"
1511 " Warning: Mail notification does not work when used.\n\n");
1513 PrintOut(LOG_INFO
," -d, --debug\n");
1514 PrintOut(LOG_INFO
," Start smartd in debug mode\n\n");
1515 PrintOut(LOG_INFO
," -D, --showdirectives\n");
1516 PrintOut(LOG_INFO
," Print the configuration file Directives and exit\n\n");
1517 PrintOut(LOG_INFO
," -h, --help, --usage\n");
1518 PrintOut(LOG_INFO
," Display this help and exit\n\n");
1519 PrintOut(LOG_INFO
," -i N, --interval=N\n");
1520 PrintOut(LOG_INFO
," Set interval between disk checks to N seconds, where N >= 10\n\n");
1521 PrintOut(LOG_INFO
," -l local[0-7], --logfacility=local[0-7]\n");
1523 PrintOut(LOG_INFO
," Use syslog facility local0 - local7 or daemon [default]\n\n");
1525 PrintOut(LOG_INFO
," Log to \"./smartd.log\", stdout, stderr [default is event log]\n\n");
1528 PrintOut(LOG_INFO
," -n, --no-fork\n");
1529 PrintOut(LOG_INFO
," Do not fork into background\n\n");
1531 PrintOut(LOG_INFO
," -p NAME, --pidfile=NAME\n");
1532 PrintOut(LOG_INFO
," Write PID file NAME\n\n");
1533 PrintOut(LOG_INFO
," -q WHEN, --quit=WHEN\n");
1534 PrintOut(LOG_INFO
," Quit on one of: %s\n\n", GetValidArgList('q'));
1535 PrintOut(LOG_INFO
," -r, --report=TYPE\n");
1536 PrintOut(LOG_INFO
," Report transactions for one of: %s\n\n", GetValidArgList('r'));
1537 PrintOut(LOG_INFO
," -s PREFIX, --savestates=PREFIX\n");
1538 PrintOut(LOG_INFO
," Save disk states to {PREFIX}MODEL-SERIAL.TYPE.state\n");
1539 #ifdef SMARTMONTOOLS_SAVESTATES
1540 PrintOut(LOG_INFO
," [default is " SMARTMONTOOLS_SAVESTATES
"MODEL-SERIAL.TYPE.state]\n");
1542 PrintOut(LOG_INFO
,"\n");
1543 PrintOut(LOG_INFO
," -w NAME, --warnexec=NAME\n");
1544 PrintOut(LOG_INFO
," Run executable NAME on warnings\n");
1546 PrintOut(LOG_INFO
," [default is " SMARTMONTOOLS_SMARTDSCRIPTDIR
"/smartd_warning.sh]\n\n");
1548 PrintOut(LOG_INFO
," [default is %s/smartd_warning.cmd]\n\n", get_exe_dir().c_str());
1551 PrintOut(LOG_INFO
," --service\n");
1552 PrintOut(LOG_INFO
," Running as windows service (see man page), install with:\n");
1553 PrintOut(LOG_INFO
," smartd install [options]\n");
1554 PrintOut(LOG_INFO
," Remove service with:\n");
1555 PrintOut(LOG_INFO
," smartd remove\n\n");
1557 PrintOut(LOG_INFO
," -V, --version, --license, --copyright\n");
1558 PrintOut(LOG_INFO
," Print License, Copyright, and version information\n");
1561 static int CloseDevice(smart_device
* device
, const char * name
)
1563 if (!device
->close()){
1564 PrintOut(LOG_INFO
,"Device: %s, %s, close() failed\n", name
, device
->get_errmsg());
1567 // device sucessfully closed
1571 // return true if a char is not allowed in a state file name
1572 static bool not_allowed_in_filename(char c
)
1574 return !( ('0' <= c
&& c
<= '9')
1575 || ('A' <= c
&& c
<= 'Z')
1576 || ('a' <= c
&& c
<= 'z'));
1579 // Read error count from Summary or Extended Comprehensive SMART error log
1580 // Return -1 on error
1581 static int read_ata_error_count(ata_device
* device
, const char * name
,
1582 firmwarebug_defs firmwarebugs
, bool extended
)
1585 ata_smart_errorlog log
;
1586 if (ataReadErrorLog(device
, &log
, firmwarebugs
)){
1587 PrintOut(LOG_INFO
,"Device: %s, Read Summary SMART Error Log failed\n",name
);
1590 return (log
.error_log_pointer
? log
.ata_error_count
: 0);
1593 ata_smart_exterrlog logx
;
1594 if (!ataReadExtErrorLog(device
, &logx
, 0, 1 /*first sector only*/, firmwarebugs
)) {
1595 PrintOut(LOG_INFO
,"Device: %s, Read Extended Comprehensive SMART Error Log failed\n",name
);
1598 // Some disks use the reserved byte as index, see ataprint.cpp.
1599 return (logx
.error_log_index
|| logx
.reserved1
? logx
.device_error_count
: 0);
1603 // returns <0 if problem. Otherwise, bottom 8 bits are the self test
1604 // error count, and top bits are the power-on hours of the last error.
1605 static int SelfTestErrorCount(ata_device
* device
, const char * name
,
1606 firmwarebug_defs firmwarebugs
)
1608 struct ata_smart_selftestlog log
;
1610 if (ataReadSelfTestLog(device
, &log
, firmwarebugs
)){
1611 PrintOut(LOG_INFO
,"Device: %s, Read SMART Self Test Log Failed\n",name
);
1615 // return current number of self-test errors
1616 return ataPrintSmartSelfTestlog(&log
, false, firmwarebugs
);
1619 #define SELFTEST_ERRORCOUNT(x) (x & 0xff)
1620 #define SELFTEST_ERRORHOURS(x) ((x >> 8) & 0xffff)
1622 // Check offline data collection status
1623 static inline bool is_offl_coll_in_progress(unsigned char status
)
1625 return ((status
& 0x7f) == 0x03);
1628 // Check self-test execution status
1629 static inline bool is_self_test_in_progress(unsigned char status
)
1631 return ((status
>> 4) == 0xf);
1634 // Log offline data collection status
1635 static void log_offline_data_coll_status(const char * name
, unsigned char status
)
1638 switch (status
& 0x7f) {
1639 case 0x00: msg
= "was never started"; break;
1640 case 0x02: msg
= "was completed without error"; break;
1641 case 0x03: msg
= "is in progress"; break;
1642 case 0x04: msg
= "was suspended by an interrupting command from host"; break;
1643 case 0x05: msg
= "was aborted by an interrupting command from host"; break;
1644 case 0x06: msg
= "was aborted by the device with a fatal error"; break;
1649 PrintOut(((status
& 0x7f) == 0x06 ? LOG_CRIT
: LOG_INFO
),
1650 "Device: %s, offline data collection %s%s\n", name
, msg
,
1651 ((status
& 0x80) ? " (auto:on)" : ""));
1653 PrintOut(LOG_INFO
, "Device: %s, unknown offline data collection status 0x%02x\n",
1657 // Log self-test execution status
1658 static void log_self_test_exec_status(const char * name
, unsigned char status
)
1661 switch (status
>> 4) {
1662 case 0x0: msg
= "completed without error"; break;
1663 case 0x1: msg
= "was aborted by the host"; break;
1664 case 0x2: msg
= "was interrupted by the host with a reset"; break;
1665 case 0x3: msg
= "could not complete due to a fatal or unknown error"; break;
1666 case 0x4: msg
= "completed with error (unknown test element)"; break;
1667 case 0x5: msg
= "completed with error (electrical test element)"; break;
1668 case 0x6: msg
= "completed with error (servo/seek test element)"; break;
1669 case 0x7: msg
= "completed with error (read test element)"; break;
1670 case 0x8: msg
= "completed with error (handling damage?)"; break;
1675 PrintOut(((status
>> 4) >= 0x4 ? LOG_CRIT
: LOG_INFO
),
1676 "Device: %s, previous self-test %s\n", name
, msg
);
1677 else if ((status
>> 4) == 0xf)
1678 PrintOut(LOG_INFO
, "Device: %s, self-test in progress, %u0%% remaining\n",
1679 name
, status
& 0x0f);
1681 PrintOut(LOG_INFO
, "Device: %s, unknown self-test status 0x%02x\n",
1685 // Check pending sector count id (-C, -U directives).
1686 static bool check_pending_id(const dev_config
& cfg
, const dev_state
& state
,
1687 unsigned char id
, const char * msg
)
1689 // Check attribute index
1690 int i
= ata_find_attr_index(id
, state
.smartval
);
1692 PrintOut(LOG_INFO
, "Device: %s, can't monitor %s count - no Attribute %d\n",
1693 cfg
.name
.c_str(), msg
, id
);
1698 uint64_t rawval
= ata_get_attr_raw_value(state
.smartval
.vendor_attributes
[i
],
1699 cfg
.attribute_defs
);
1700 if (rawval
>= (state
.num_sectors
? state
.num_sectors
: 0xffffffffULL
)) {
1701 PrintOut(LOG_INFO
, "Device: %s, ignoring %s count - bogus Attribute %d value %" PRIu64
" (0x%" PRIx64
")\n",
1702 cfg
.name
.c_str(), msg
, id
, rawval
, rawval
);
1709 // Called by ATA/SCSIDeviceScan() after successful device check
1710 static void finish_device_scan(dev_config
& cfg
, dev_state
& state
)
1712 // Set cfg.emailfreq if user hasn't set it
1713 if ((!cfg
.emailaddress
.empty() || !cfg
.emailcmdline
.empty()) && !cfg
.emailfreq
) {
1714 // Avoid that emails are suppressed forever due to state persistence
1715 if (cfg
.state_file
.empty())
1716 cfg
.emailfreq
= 1; // '-M once'
1718 cfg
.emailfreq
= 2; // '-M daily'
1721 // Start self-test regex check now if time was not read from state file
1722 if (!cfg
.test_regex
.empty() && !state
.scheduled_test_next_check
)
1723 state
.scheduled_test_next_check
= time(0);
1726 // Common function to format result message for ATA setting
1727 static void format_set_result_msg(std::string
& msg
, const char * name
, bool ok
,
1728 int set_option
= 0, bool has_value
= false)
1735 else if (set_option
< 0)
1738 msg
+= strprintf(":%d", set_option
-1);
1739 else if (set_option
> 0)
1744 // TODO: Add '-F swapid' directive
1745 const bool fix_swapped_id
= false;
1747 // scan to see what ata devices there are, and if they support SMART
1748 static int ATADeviceScan(dev_config
& cfg
, dev_state
& state
, ata_device
* atadev
)
1751 struct ata_identify_device drive
;
1752 const char *name
= cfg
.name
.c_str();
1755 // Device must be open
1757 // Get drive identity structure
1758 if ((retid
= ata_read_identity(atadev
, &drive
, fix_swapped_id
))) {
1760 // Unable to read Identity structure
1761 PrintOut(LOG_INFO
,"Device: %s, not ATA, no IDENTIFY DEVICE Structure\n",name
);
1763 PrintOut(LOG_INFO
,"Device: %s, packet devices [this device %s] not SMART capable\n",
1764 name
, packetdevicetype(retid
-1));
1765 CloseDevice(atadev
, name
);
1769 // Get drive identity, size and rotation rate (HDD/SSD)
1770 char model
[40+1], serial
[20+1], firmware
[8+1];
1771 ata_format_id_string(model
, drive
.model
, sizeof(model
)-1);
1772 ata_format_id_string(serial
, drive
.serial_no
, sizeof(serial
)-1);
1773 ata_format_id_string(firmware
, drive
.fw_rev
, sizeof(firmware
)-1);
1775 ata_size_info sizes
;
1776 ata_get_size_info(&drive
, sizes
);
1777 state
.num_sectors
= sizes
.sectors
;
1778 cfg
.dev_rpm
= ata_get_rotation_rate(&drive
);
1780 char wwn
[30]; wwn
[0] = 0;
1781 unsigned oui
= 0; uint64_t unique_id
= 0;
1782 int naa
= ata_get_wwn(&drive
, oui
, unique_id
);
1784 snprintf(wwn
, sizeof(wwn
), "WWN:%x-%06x-%09" PRIx64
", ", naa
, oui
, unique_id
);
1786 // Format device id string for warning emails
1788 cfg
.dev_idinfo
= strprintf("%s, S/N:%s, %sFW:%s, %s", model
, serial
, wwn
, firmware
,
1789 format_capacity(cap
, sizeof(cap
), sizes
.capacity
, "."));
1791 PrintOut(LOG_INFO
, "Device: %s, %s\n", name
, cfg
.dev_idinfo
.c_str());
1793 // Show if device in database, and use preset vendor attribute
1794 // options unless user has requested otherwise.
1795 if (cfg
.ignorepresets
)
1796 PrintOut(LOG_INFO
, "Device: %s, smartd database not searched (Directive: -P ignore).\n", name
);
1798 // Apply vendor specific presets, print warning if present
1799 const drive_settings
* dbentry
= lookup_drive_apply_presets(
1800 &drive
, cfg
.attribute_defs
, cfg
.firmwarebugs
);
1802 PrintOut(LOG_INFO
, "Device: %s, not found in smartd database.\n", name
);
1804 PrintOut(LOG_INFO
, "Device: %s, found in smartd database%s%s\n",
1805 name
, (*dbentry
->modelfamily
? ": " : "."), (*dbentry
->modelfamily
? dbentry
->modelfamily
: ""));
1806 if (*dbentry
->warningmsg
)
1807 PrintOut(LOG_CRIT
, "Device: %s, WARNING: %s\n", name
, dbentry
->warningmsg
);
1811 // Set default '-C 197[+]' if no '-C ID' is specified.
1812 if (!cfg
.curr_pending_set
)
1813 cfg
.curr_pending_id
= get_unc_attr_id(false, cfg
.attribute_defs
, cfg
.curr_pending_incr
);
1814 // Set default '-U 198[+]' if no '-U ID' is specified.
1815 if (!cfg
.offl_pending_set
)
1816 cfg
.offl_pending_id
= get_unc_attr_id(true, cfg
.attribute_defs
, cfg
.offl_pending_incr
);
1818 // If requested, show which presets would be used for this drive
1819 if (cfg
.showpresets
) {
1820 int savedebugmode
=debugmode
;
1821 PrintOut(LOG_INFO
, "Device %s: presets are:\n", name
);
1824 show_presets(&drive
);
1825 debugmode
=savedebugmode
;
1828 // see if drive supports SMART
1829 supported
=ataSmartSupport(&drive
);
1832 // drive does NOT support SMART
1833 PrintOut(LOG_INFO
,"Device: %s, lacks SMART capability\n",name
);
1835 // can't tell if drive supports SMART
1836 PrintOut(LOG_INFO
,"Device: %s, ATA IDENTIFY DEVICE words 82-83 don't specify if SMART capable.\n",name
);
1838 // should we proceed anyway?
1839 if (cfg
.permissive
) {
1840 PrintOut(LOG_INFO
,"Device: %s, proceeding since '-T permissive' Directive given.\n",name
);
1843 PrintOut(LOG_INFO
,"Device: %s, to proceed anyway, use '-T permissive' Directive.\n",name
);
1844 CloseDevice(atadev
, name
);
1849 if (ataEnableSmart(atadev
)) {
1850 // Enable SMART command has failed
1851 PrintOut(LOG_INFO
,"Device: %s, could not enable SMART capability\n",name
);
1853 if (ataIsSmartEnabled(&drive
) <= 0) {
1854 CloseDevice(atadev
, name
);
1857 PrintOut(LOG_INFO
, "Device: %s, proceeding since SMART is already enabled\n", name
);
1860 // disable device attribute autosave...
1861 if (cfg
.autosave
==1) {
1862 if (ataDisableAutoSave(atadev
))
1863 PrintOut(LOG_INFO
,"Device: %s, could not disable SMART Attribute Autosave.\n",name
);
1865 PrintOut(LOG_INFO
,"Device: %s, disabled SMART Attribute Autosave.\n",name
);
1868 // or enable device attribute autosave
1869 if (cfg
.autosave
==2) {
1870 if (ataEnableAutoSave(atadev
))
1871 PrintOut(LOG_INFO
,"Device: %s, could not enable SMART Attribute Autosave.\n",name
);
1873 PrintOut(LOG_INFO
,"Device: %s, enabled SMART Attribute Autosave.\n",name
);
1876 // capability check: SMART status
1877 if (cfg
.smartcheck
&& ataSmartStatus2(atadev
) == -1) {
1878 PrintOut(LOG_INFO
,"Device: %s, not capable of SMART Health Status check\n",name
);
1879 cfg
.smartcheck
= false;
1882 // capability check: Read smart values and thresholds. Note that
1883 // smart values are ALSO needed even if we ONLY want to know if the
1884 // device is self-test log or error-log capable! After ATA-5, this
1885 // information was ALSO reproduced in the IDENTIFY DEVICE response,
1886 // but sadly not for ATA-5. Sigh.
1888 // do we need to get SMART data?
1889 bool smart_val_ok
= false;
1890 if ( cfg
.autoofflinetest
|| cfg
.selftest
1891 || cfg
.errorlog
|| cfg
.xerrorlog
1892 || cfg
.offlinests
|| cfg
.selfteststs
1893 || cfg
.usagefailed
|| cfg
.prefail
|| cfg
.usage
1894 || cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
1895 || cfg
.curr_pending_id
|| cfg
.offl_pending_id
) {
1897 if (ataReadSmartValues(atadev
, &state
.smartval
)) {
1898 PrintOut(LOG_INFO
, "Device: %s, Read SMART Values failed\n", name
);
1899 cfg
.usagefailed
= cfg
.prefail
= cfg
.usage
= false;
1900 cfg
.tempdiff
= cfg
.tempinfo
= cfg
.tempcrit
= 0;
1901 cfg
.curr_pending_id
= cfg
.offl_pending_id
= 0;
1904 smart_val_ok
= true;
1905 if (ataReadSmartThresholds(atadev
, &state
.smartthres
)) {
1906 PrintOut(LOG_INFO
, "Device: %s, Read SMART Thresholds failed%s\n",
1907 name
, (cfg
.usagefailed
? ", ignoring -f Directive" : ""));
1908 cfg
.usagefailed
= false;
1909 // Let ata_get_attr_state() return ATTRSTATE_NO_THRESHOLD:
1910 memset(&state
.smartthres
, 0, sizeof(state
.smartthres
));
1914 // see if the necessary Attribute is there to monitor offline or
1915 // current pending sectors or temperature
1916 if ( cfg
.curr_pending_id
1917 && !check_pending_id(cfg
, state
, cfg
.curr_pending_id
,
1918 "Current_Pending_Sector"))
1919 cfg
.curr_pending_id
= 0;
1921 if ( cfg
.offl_pending_id
1922 && !check_pending_id(cfg
, state
, cfg
.offl_pending_id
,
1923 "Offline_Uncorrectable"))
1924 cfg
.offl_pending_id
= 0;
1926 if ( (cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
)
1927 && !ata_return_temperature_value(&state
.smartval
, cfg
.attribute_defs
)) {
1928 PrintOut(LOG_INFO
, "Device: %s, can't monitor Temperature, ignoring -W %d,%d,%d\n",
1929 name
, cfg
.tempdiff
, cfg
.tempinfo
, cfg
.tempcrit
);
1930 cfg
.tempdiff
= cfg
.tempinfo
= cfg
.tempcrit
= 0;
1933 // Report ignored '-r' or '-R' directives
1934 for (int id
= 1; id
<= 255; id
++) {
1935 if (cfg
.monitor_attr_flags
.is_set(id
, MONITOR_RAW_PRINT
)) {
1936 char opt
= (!cfg
.monitor_attr_flags
.is_set(id
, MONITOR_RAW
) ? 'r' : 'R');
1937 const char * excl
= (cfg
.monitor_attr_flags
.is_set(id
,
1938 (opt
== 'r' ? MONITOR_AS_CRIT
: MONITOR_RAW_AS_CRIT
)) ? "!" : "");
1940 int idx
= ata_find_attr_index(id
, state
.smartval
);
1942 PrintOut(LOG_INFO
,"Device: %s, no Attribute %d, ignoring -%c %d%s\n", name
, id
, opt
, id
, excl
);
1944 bool prefail
= !!ATTRIBUTE_FLAGS_PREFAILURE(state
.smartval
.vendor_attributes
[idx
].flags
);
1945 if (!((prefail
&& cfg
.prefail
) || (!prefail
&& cfg
.usage
)))
1946 PrintOut(LOG_INFO
,"Device: %s, not monitoring %s Attributes, ignoring -%c %d%s\n", name
,
1947 (prefail
? "Prefailure" : "Usage"), opt
, id
, excl
);
1953 // enable/disable automatic on-line testing
1954 if (cfg
.autoofflinetest
) {
1955 // is this an enable or disable request?
1956 const char *what
=(cfg
.autoofflinetest
==1)?"disable":"enable";
1958 PrintOut(LOG_INFO
,"Device: %s, could not %s SMART Automatic Offline Testing.\n",name
, what
);
1960 // if command appears unsupported, issue a warning...
1961 if (!isSupportAutomaticTimer(&state
.smartval
))
1962 PrintOut(LOG_INFO
,"Device: %s, SMART Automatic Offline Testing unsupported...\n",name
);
1963 // ... but then try anyway
1964 if ((cfg
.autoofflinetest
==1)?ataDisableAutoOffline(atadev
):ataEnableAutoOffline(atadev
))
1965 PrintOut(LOG_INFO
,"Device: %s, %s SMART Automatic Offline Testing failed.\n", name
, what
);
1967 PrintOut(LOG_INFO
,"Device: %s, %sd SMART Automatic Offline Testing.\n", name
, what
);
1971 // Read log directories if required for capability check
1972 ata_smart_log_directory smart_logdir
, gp_logdir
;
1973 bool smart_logdir_ok
= false, gp_logdir_ok
= false;
1975 if ( isGeneralPurposeLoggingCapable(&drive
)
1976 && (cfg
.errorlog
|| cfg
.selftest
)
1977 && !cfg
.firmwarebugs
.is_set(BUG_NOLOGDIR
)) {
1978 if (!ataReadLogDirectory(atadev
, &smart_logdir
, false))
1979 smart_logdir_ok
= true;
1982 if (cfg
.xerrorlog
&& !cfg
.firmwarebugs
.is_set(BUG_NOLOGDIR
)) {
1983 if (!ataReadLogDirectory(atadev
, &gp_logdir
, true))
1984 gp_logdir_ok
= true;
1987 // capability check: self-test-log
1988 state
.selflogcount
= 0; state
.selfloghour
= 0;
1991 if (!( cfg
.permissive
1992 || ( smart_logdir_ok
&& smart_logdir
.entry
[0x06-1].numsectors
)
1993 || (!smart_logdir_ok
&& smart_val_ok
&& isSmartTestLogCapable(&state
.smartval
, &drive
)))) {
1994 PrintOut(LOG_INFO
, "Device: %s, no SMART Self-test Log, ignoring -l selftest (override with -T permissive)\n", name
);
1995 cfg
.selftest
= false;
1997 else if ((retval
= SelfTestErrorCount(atadev
, name
, cfg
.firmwarebugs
)) < 0) {
1998 PrintOut(LOG_INFO
, "Device: %s, no SMART Self-test Log, ignoring -l selftest\n", name
);
1999 cfg
.selftest
= false;
2002 state
.selflogcount
=SELFTEST_ERRORCOUNT(retval
);
2003 state
.selfloghour
=SELFTEST_ERRORHOURS(retval
);
2007 // capability check: ATA error log
2008 state
.ataerrorcount
= 0;
2011 if (!( cfg
.permissive
2012 || ( smart_logdir_ok
&& smart_logdir
.entry
[0x01-1].numsectors
)
2013 || (!smart_logdir_ok
&& smart_val_ok
&& isSmartErrorLogCapable(&state
.smartval
, &drive
)))) {
2014 PrintOut(LOG_INFO
, "Device: %s, no SMART Error Log, ignoring -l error (override with -T permissive)\n", name
);
2015 cfg
.errorlog
= false;
2017 else if ((errcnt1
= read_ata_error_count(atadev
, name
, cfg
.firmwarebugs
, false)) < 0) {
2018 PrintOut(LOG_INFO
, "Device: %s, no SMART Error Log, ignoring -l error\n", name
);
2019 cfg
.errorlog
= false;
2022 state
.ataerrorcount
= errcnt1
;
2025 if (cfg
.xerrorlog
) {
2027 if (!( cfg
.permissive
|| cfg
.firmwarebugs
.is_set(BUG_NOLOGDIR
)
2028 || (gp_logdir_ok
&& gp_logdir
.entry
[0x03-1].numsectors
) )) {
2029 PrintOut(LOG_INFO
, "Device: %s, no Extended Comprehensive SMART Error Log, ignoring -l xerror (override with -T permissive)\n",
2031 cfg
.xerrorlog
= false;
2033 else if ((errcnt2
= read_ata_error_count(atadev
, name
, cfg
.firmwarebugs
, true)) < 0) {
2034 PrintOut(LOG_INFO
, "Device: %s, no Extended Comprehensive SMART Error Log, ignoring -l xerror\n", name
);
2035 cfg
.xerrorlog
= false;
2037 else if (cfg
.errorlog
&& state
.ataerrorcount
!= errcnt2
) {
2038 PrintOut(LOG_INFO
, "Device: %s, SMART Error Logs report different error counts: %d != %d\n",
2039 name
, state
.ataerrorcount
, errcnt2
);
2040 // Record max error count
2041 if (errcnt2
> state
.ataerrorcount
)
2042 state
.ataerrorcount
= errcnt2
;
2045 state
.ataerrorcount
= errcnt2
;
2048 // capability check: self-test and offline data collection status
2049 if (cfg
.offlinests
|| cfg
.selfteststs
) {
2050 if (!(cfg
.permissive
|| (smart_val_ok
&& state
.smartval
.offline_data_collection_capability
))) {
2052 PrintOut(LOG_INFO
, "Device: %s, no SMART Offline Data Collection capability, ignoring -l offlinests (override with -T permissive)\n", name
);
2053 if (cfg
.selfteststs
)
2054 PrintOut(LOG_INFO
, "Device: %s, no SMART Self-test capability, ignoring -l selfteststs (override with -T permissive)\n", name
);
2055 cfg
.offlinests
= cfg
.selfteststs
= false;
2059 // capabilities check -- does it support powermode?
2060 if (cfg
.powermode
) {
2061 int powermode
= ataCheckPowerMode(atadev
);
2063 if (-1 == powermode
) {
2064 PrintOut(LOG_CRIT
, "Device: %s, no ATA CHECK POWER STATUS support, ignoring -n Directive\n", name
);
2067 else if (powermode
!=0 && powermode
!=0x80 && powermode
!=0xff) {
2068 PrintOut(LOG_CRIT
, "Device: %s, CHECK POWER STATUS returned %d, not ATA compliant, ignoring -n Directive\n",
2074 // Apply ATA settings
2078 format_set_result_msg(msg
, "AAM", (cfg
.set_aam
> 0 ?
2079 ata_set_features(atadev
, ATA_ENABLE_AAM
, cfg
.set_aam
-1) :
2080 ata_set_features(atadev
, ATA_DISABLE_AAM
)), cfg
.set_aam
, true);
2083 format_set_result_msg(msg
, "APM", (cfg
.set_apm
> 0 ?
2084 ata_set_features(atadev
, ATA_ENABLE_APM
, cfg
.set_apm
-1) :
2085 ata_set_features(atadev
, ATA_DISABLE_APM
)), cfg
.set_apm
, true);
2087 if (cfg
.set_lookahead
)
2088 format_set_result_msg(msg
, "Rd-ahead", ata_set_features(atadev
,
2089 (cfg
.set_lookahead
> 0 ? ATA_ENABLE_READ_LOOK_AHEAD
: ATA_DISABLE_READ_LOOK_AHEAD
)),
2093 format_set_result_msg(msg
, "Wr-cache", ata_set_features(atadev
,
2094 (cfg
.set_wcache
> 0? ATA_ENABLE_WRITE_CACHE
: ATA_DISABLE_WRITE_CACHE
)), cfg
.set_wcache
);
2096 if (cfg
.set_security_freeze
)
2097 format_set_result_msg(msg
, "Security freeze",
2098 ata_nodata_command(atadev
, ATA_SECURITY_FREEZE_LOCK
));
2100 if (cfg
.set_standby
)
2101 format_set_result_msg(msg
, "Standby",
2102 ata_nodata_command(atadev
, ATA_IDLE
, cfg
.set_standby
-1), cfg
.set_standby
, true);
2104 // Report as one log entry
2106 PrintOut(LOG_INFO
, "Device: %s, ATA settings applied: %s\n", name
, msg
.c_str());
2108 // set SCT Error Recovery Control if requested
2109 if (cfg
.sct_erc_set
) {
2110 if (!isSCTErrorRecoveryControlCapable(&drive
))
2111 PrintOut(LOG_INFO
, "Device: %s, no SCT Error Recovery Control support, ignoring -l scterc\n",
2113 else if ( ataSetSCTErrorRecoveryControltime(atadev
, 1, cfg
.sct_erc_readtime
)
2114 || ataSetSCTErrorRecoveryControltime(atadev
, 2, cfg
.sct_erc_writetime
))
2115 PrintOut(LOG_INFO
, "Device: %s, set of SCT Error Recovery Control failed\n", name
);
2117 PrintOut(LOG_INFO
, "Device: %s, SCT Error Recovery Control set to: Read: %u, Write: %u\n",
2118 name
, cfg
.sct_erc_readtime
, cfg
.sct_erc_writetime
);
2121 // If no tests available or selected, return
2122 if (!( cfg
.smartcheck
|| cfg
.selftest
2123 || cfg
.errorlog
|| cfg
.xerrorlog
2124 || cfg
.offlinests
|| cfg
.selfteststs
2125 || cfg
.usagefailed
|| cfg
.prefail
|| cfg
.usage
2126 || cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
)) {
2127 CloseDevice(atadev
, name
);
2131 // tell user we are registering device
2132 PrintOut(LOG_INFO
,"Device: %s, is SMART capable. Adding to \"monitor\" list.\n",name
);
2134 // close file descriptor
2135 CloseDevice(atadev
, name
);
2137 if (!state_path_prefix
.empty() || !attrlog_path_prefix
.empty()) {
2138 // Build file name for state file
2139 std::replace_if(model
, model
+strlen(model
), not_allowed_in_filename
, '_');
2140 std::replace_if(serial
, serial
+strlen(serial
), not_allowed_in_filename
, '_');
2141 if (!state_path_prefix
.empty()) {
2142 cfg
.state_file
= strprintf("%s%s-%s.ata.state", state_path_prefix
.c_str(), model
, serial
);
2143 // Read previous state
2144 if (read_dev_state(cfg
.state_file
.c_str(), state
)) {
2145 PrintOut(LOG_INFO
, "Device: %s, state read from %s\n", name
, cfg
.state_file
.c_str());
2146 // Copy ATA attribute values to temp state
2147 state
.update_temp_state();
2150 if (!attrlog_path_prefix
.empty())
2151 cfg
.attrlog_file
= strprintf("%s%s-%s.ata.csv", attrlog_path_prefix
.c_str(), model
, serial
);
2154 finish_device_scan(cfg
, state
);
2159 // on success, return 0. On failure, return >0. Never return <0,
2161 static int SCSIDeviceScan(dev_config
& cfg
, dev_state
& state
, scsi_device
* scsidev
)
2163 int k
, err
, req_len
, avail_len
, version
, len
;
2164 const char *device
= cfg
.name
.c_str();
2165 struct scsi_iec_mode_page iec
;
2169 char lu_id
[64], serial
[256], vendor
[40], model
[40];
2171 // Device must be open
2172 memset(inqBuf
, 0, 96);
2174 if ((err
= scsiStdInquiry(scsidev
, inqBuf
, req_len
))) {
2175 /* Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices */
2177 if ((err
= scsiStdInquiry(scsidev
, inqBuf
, req_len
))) {
2178 PrintOut(LOG_INFO
, "Device: %s, Both 36 and 64 byte INQUIRY failed; "
2179 "skip device\n", device
);
2183 version
= (inqBuf
[2] & 0x7f); /* Accept old ISO/IEC 9316:1995 variants */
2185 avail_len
= inqBuf
[4] + 5;
2186 len
= (avail_len
< req_len
) ? avail_len
: req_len
;
2188 PrintOut(LOG_INFO
, "Device: %s, INQUIRY response less than 36 bytes; "
2189 "skip device\n", device
);
2193 int pdt
= inqBuf
[0] & 0x1f;
2195 if (! ((0 == pdt
) || (4 == pdt
) || (5 == pdt
) || (7 == pdt
) ||
2197 PrintOut(LOG_INFO
, "Device: %s, not a disk like device [PDT=0x%x], "
2198 "skip\n", device
, pdt
);
2202 if (supported_vpd_pages_p
) {
2203 delete supported_vpd_pages_p
;
2204 supported_vpd_pages_p
= NULL
;
2206 supported_vpd_pages_p
= new supported_vpd_pages(scsidev
);
2209 if ((version
>= 0x3) && (version
< 0x8)) {
2211 if (0 == scsiInquiryVpd(scsidev
, SCSI_VPD_DEVICE_IDENTIFICATION
,
2212 vpdBuf
, sizeof(vpdBuf
))) {
2214 scsi_decode_lu_dev_id(vpdBuf
+ 4, len
, lu_id
, sizeof(lu_id
), NULL
);
2218 if (0 == scsiInquiryVpd(scsidev
, SCSI_VPD_UNIT_SERIAL_NUMBER
,
2219 vpdBuf
, sizeof(vpdBuf
))) {
2221 vpdBuf
[4 + len
] = '\0';
2222 scsi_format_id_string(serial
, (const unsigned char *)&vpdBuf
[4], len
);
2225 unsigned int lb_size
;
2227 uint64_t capacity
= scsiGetSize(scsidev
, &lb_size
, NULL
);
2230 format_capacity(si_str
, sizeof(si_str
), capacity
);
2234 // Format device id string for warning emails
2235 cfg
.dev_idinfo
= strprintf("[%.8s %.16s %.4s]%s%s%s%s%s%s",
2236 (char *)&inqBuf
[8], (char *)&inqBuf
[16], (char *)&inqBuf
[32],
2237 (lu_id
[0] ? ", lu id: " : ""), (lu_id
[0] ? lu_id
: ""),
2238 (serial
[0] ? ", S/N: " : ""), (serial
[0] ? serial
: ""),
2239 (si_str
[0] ? ", " : ""), (si_str
[0] ? si_str
: ""));
2241 // format "model" string
2242 scsi_format_id_string(vendor
, (const unsigned char *)&inqBuf
[8], 8);
2243 scsi_format_id_string(model
, (const unsigned char *)&inqBuf
[16], 16);
2244 PrintOut(LOG_INFO
, "Device: %s, %s\n", device
, cfg
.dev_idinfo
.c_str());
2246 // check that device is ready for commands. IE stores its stuff on
2248 if ((err
= scsiTestUnitReady(scsidev
))) {
2249 if (SIMPLE_ERR_NOT_READY
== err
)
2250 PrintOut(LOG_INFO
, "Device: %s, NOT READY (e.g. spun down); skip device\n", device
);
2251 else if (SIMPLE_ERR_NO_MEDIUM
== err
)
2252 PrintOut(LOG_INFO
, "Device: %s, NO MEDIUM present; skip device\n", device
);
2253 else if (SIMPLE_ERR_BECOMING_READY
== err
)
2254 PrintOut(LOG_INFO
, "Device: %s, BECOMING (but not yet) READY; skip device\n", device
);
2256 PrintOut(LOG_CRIT
, "Device: %s, failed Test Unit Ready [err=%d]\n", device
, err
);
2257 CloseDevice(scsidev
, device
);
2261 // Badly-conforming USB storage devices may fail this check.
2262 // The response to the following IE mode page fetch (current and
2263 // changeable values) is carefully examined. It has been found
2264 // that various USB devices that malform the response will lock up
2265 // if asked for a log page (e.g. temperature) so it is best to
2267 if (!(err
= scsiFetchIECmpage(scsidev
, &iec
, state
.modese_len
)))
2268 state
.modese_len
= iec
.modese_len
;
2269 else if (SIMPLE_ERR_BAD_FIELD
== err
)
2270 ; /* continue since it is reasonable not to support IE mpage */
2271 else { /* any other error (including malformed response) unreasonable */
2273 "Device: %s, Bad IEC (SMART) mode page, err=%d, skip device\n",
2275 CloseDevice(scsidev
, device
);
2279 // N.B. The following is passive (i.e. it doesn't attempt to turn on
2280 // smart if it is off). This may change to be the same as the ATA side.
2281 if (!scsi_IsExceptionControlEnabled(&iec
)) {
2282 PrintOut(LOG_INFO
, "Device: %s, IE (SMART) not enabled, skip device\n"
2283 "Try 'smartctl -s on %s' to turn on SMART features\n",
2285 CloseDevice(scsidev
, device
);
2289 // Flag that certain log pages are supported (information may be
2290 // available from other sources).
2291 if (0 == scsiLogSense(scsidev
, SUPPORTED_LPAGES
, 0, tBuf
, sizeof(tBuf
), 0)) {
2292 for (k
= 4; k
< tBuf
[3] + LOGPAGEHDRSIZE
; ++k
) {
2294 case TEMPERATURE_LPAGE
:
2295 state
.TempPageSupported
= 1;
2298 state
.SmartPageSupported
= 1;
2300 case READ_ERROR_COUNTER_LPAGE
:
2301 state
.ReadECounterPageSupported
= 1;
2303 case WRITE_ERROR_COUNTER_LPAGE
:
2304 state
.WriteECounterPageSupported
= 1;
2306 case VERIFY_ERROR_COUNTER_LPAGE
:
2307 state
.VerifyECounterPageSupported
= 1;
2309 case NON_MEDIUM_ERROR_LPAGE
:
2310 state
.NonMediumErrorPageSupported
= 1;
2318 // Check if scsiCheckIE() is going to work
2322 UINT8 currenttemp
= 0;
2325 if (scsiCheckIE(scsidev
, state
.SmartPageSupported
, state
.TempPageSupported
,
2326 &asc
, &ascq
, ¤ttemp
, &triptemp
)) {
2327 PrintOut(LOG_INFO
, "Device: %s, unexpectedly failed to read SMART values\n", device
);
2328 state
.SuppressReport
= 1;
2329 if (cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
) {
2330 PrintOut(LOG_INFO
, "Device: %s, can't monitor Temperature, ignoring -W %d,%d,%d\n",
2331 device
, cfg
.tempdiff
, cfg
.tempinfo
, cfg
.tempcrit
);
2332 cfg
.tempdiff
= cfg
.tempinfo
= cfg
.tempcrit
= 0;
2337 // capability check: self-test-log
2339 int retval
= scsiCountFailedSelfTests(scsidev
, 0);
2341 // no self-test log, turn off monitoring
2342 PrintOut(LOG_INFO
, "Device: %s, does not support SMART Self-Test Log.\n", device
);
2343 cfg
.selftest
= false;
2344 state
.selflogcount
= 0;
2345 state
.selfloghour
= 0;
2348 // register starting values to watch for changes
2349 state
.selflogcount
=SELFTEST_ERRORCOUNT(retval
);
2350 state
.selfloghour
=SELFTEST_ERRORHOURS(retval
);
2354 // disable autosave (set GLTSD bit)
2355 if (cfg
.autosave
==1){
2356 if (scsiSetControlGLTSD(scsidev
, 1, state
.modese_len
))
2357 PrintOut(LOG_INFO
,"Device: %s, could not disable autosave (set GLTSD bit).\n",device
);
2359 PrintOut(LOG_INFO
,"Device: %s, disabled autosave (set GLTSD bit).\n",device
);
2362 // or enable autosave (clear GLTSD bit)
2363 if (cfg
.autosave
==2){
2364 if (scsiSetControlGLTSD(scsidev
, 0, state
.modese_len
))
2365 PrintOut(LOG_INFO
,"Device: %s, could not enable autosave (clear GLTSD bit).\n",device
);
2367 PrintOut(LOG_INFO
,"Device: %s, enabled autosave (cleared GLTSD bit).\n",device
);
2370 // tell user we are registering device
2371 PrintOut(LOG_INFO
, "Device: %s, is SMART capable. Adding to \"monitor\" list.\n", device
);
2373 // Make sure that init_standby_check() ignores SCSI devices
2374 cfg
.offlinests_ns
= cfg
.selfteststs_ns
= false;
2376 // close file descriptor
2377 CloseDevice(scsidev
, device
);
2379 if (!state_path_prefix
.empty() || !attrlog_path_prefix
.empty()) {
2380 // Build file name for state file
2381 std::replace_if(model
, model
+strlen(model
), not_allowed_in_filename
, '_');
2382 std::replace_if(serial
, serial
+strlen(serial
), not_allowed_in_filename
, '_');
2383 if (!state_path_prefix
.empty()) {
2384 cfg
.state_file
= strprintf("%s%s-%s-%s.scsi.state", state_path_prefix
.c_str(), vendor
, model
, serial
);
2385 // Read previous state
2386 if (read_dev_state(cfg
.state_file
.c_str(), state
)) {
2387 PrintOut(LOG_INFO
, "Device: %s, state read from %s\n", device
, cfg
.state_file
.c_str());
2388 // Copy ATA attribute values to temp state
2389 state
.update_temp_state();
2392 if (!attrlog_path_prefix
.empty())
2393 cfg
.attrlog_file
= strprintf("%s%s-%s-%s.scsi.csv", attrlog_path_prefix
.c_str(), vendor
, model
, serial
);
2396 finish_device_scan(cfg
, state
);
2401 // If the self-test log has got more self-test errors (or more recent
2402 // self-test errors) recorded, then notify user.
2403 static void CheckSelfTestLogs(const dev_config
& cfg
, dev_state
& state
, int newi
)
2405 const char * name
= cfg
.name
.c_str();
2409 MailWarning(cfg
, state
, 8, "Device: %s, Read SMART Self-Test Log Failed", name
);
2411 reset_warning_mail(cfg
, state
, 8, "Read SMART Self-Test Log worked again");
2413 // old and new error counts
2414 int oldc
=state
.selflogcount
;
2415 int newc
=SELFTEST_ERRORCOUNT(newi
);
2417 // old and new error timestamps in hours
2418 int oldh
=state
.selfloghour
;
2419 int newh
=SELFTEST_ERRORHOURS(newi
);
2422 // increase in error count
2423 PrintOut(LOG_CRIT
, "Device: %s, Self-Test Log error count increased from %d to %d\n",
2425 MailWarning(cfg
, state
, 3, "Device: %s, Self-Test Log error count increased from %d to %d",
2427 state
.must_write
= true;
2429 else if (newc
> 0 && oldh
!= newh
) {
2430 // more recent error
2431 // a 'more recent' error might actually be a smaller hour number,
2432 // if the hour number has wrapped.
2433 // There's still a bug here. You might just happen to run a new test
2434 // exactly 32768 hours after the previous failure, and have run exactly
2435 // 20 tests between the two, in which case smartd will miss the
2437 PrintOut(LOG_CRIT
, "Device: %s, new Self-Test Log error at hour timestamp %d\n",
2439 MailWarning(cfg
, state
, 3, "Device: %s, new Self-Test Log error at hour timestamp %d",
2441 state
.must_write
= true;
2444 // Print info if error entries have disappeared
2445 // or newer successful successful extended self-test exits
2447 PrintOut(LOG_INFO
, "Device: %s, Self-Test Log error count decreased from %d to %d\n",
2450 reset_warning_mail(cfg
, state
, 3, "Self-Test Log does no longer report errors");
2453 // Needed since self-test error count may DECREASE. Hour might
2454 // also have changed.
2455 state
.selflogcount
= newc
;
2456 state
.selfloghour
= newh
;
2461 // Test types, ordered by priority.
2462 static const char test_type_chars
[] = "LncrSCO";
2463 static const unsigned num_test_types
= sizeof(test_type_chars
)-1;
2465 // returns test type if time to do test of type testtype,
2466 // 0 if not time to do test.
2467 static char next_scheduled_test(const dev_config
& cfg
, dev_state
& state
, bool scsi
, time_t usetime
= 0)
2469 // check that self-testing has been requested
2470 if (cfg
.test_regex
.empty())
2473 // Exit if drive not capable of any test
2474 if ( state
.not_cap_long
&& state
.not_cap_short
&&
2475 (scsi
|| (state
.not_cap_conveyance
&& state
.not_cap_offline
)))
2478 // since we are about to call localtime(), be sure glibc is informed
2479 // of any timezone changes we make.
2481 FixGlibcTimeZoneBug();
2483 // Is it time for next check?
2484 time_t now
= (!usetime
? time(0) : usetime
);
2485 if (now
< state
.scheduled_test_next_check
)
2488 // Limit time check interval to 90 days
2489 if (state
.scheduled_test_next_check
+ (3600L*24*90) < now
)
2490 state
.scheduled_test_next_check
= now
- (3600L*24*90);
2492 // Check interval [state.scheduled_test_next_check, now] for scheduled tests
2494 time_t testtime
= 0; int testhour
= 0;
2495 int maxtest
= num_test_types
-1;
2497 for (time_t t
= state
.scheduled_test_next_check
; ; ) {
2498 struct tm
* tms
= localtime(&t
);
2499 // tm_wday is 0 (Sunday) to 6 (Saturday). We use 1 (Monday) to 7 (Sunday).
2500 int weekday
= (tms
->tm_wday
? tms
->tm_wday
: 7);
2501 for (int i
= 0; i
<= maxtest
; i
++) {
2502 // Skip if drive not capable of this test
2503 switch (test_type_chars
[i
]) {
2504 case 'L': if (state
.not_cap_long
) continue; break;
2505 case 'S': if (state
.not_cap_short
) continue; break;
2506 case 'C': if (scsi
|| state
.not_cap_conveyance
) continue; break;
2507 case 'O': if (scsi
|| state
.not_cap_offline
) continue; break;
2509 case 'r': if (scsi
|| state
.not_cap_selective
) continue; break;
2512 // Try match of "T/MM/DD/d/HH"
2514 snprintf(pattern
, sizeof(pattern
), "%c/%02d/%02d/%1d/%02d",
2515 test_type_chars
[i
], tms
->tm_mon
+1, tms
->tm_mday
, weekday
, tms
->tm_hour
);
2516 if (cfg
.test_regex
.full_match(pattern
)) {
2518 testtype
= pattern
[0];
2519 testtime
= t
; testhour
= tms
->tm_hour
;
2520 // Limit further matches to higher priority self-tests
2525 // Exit if no tests left or current time reached
2531 if ((t
+= 3600) > now
)
2535 // Do next check not before next hour.
2536 struct tm
* tmnow
= localtime(&now
);
2537 state
.scheduled_test_next_check
= now
+ (3600 - tmnow
->tm_min
*60 - tmnow
->tm_sec
);
2540 state
.must_write
= true;
2541 // Tell user if an old test was found.
2542 if (!usetime
&& !(testhour
== tmnow
->tm_hour
&& testtime
+ 3600 > now
)) {
2543 char datebuf
[DATEANDEPOCHLEN
]; dateandtimezoneepoch(datebuf
, testtime
);
2544 PrintOut(LOG_INFO
, "Device: %s, old test of type %c not run at %s, starting now.\n",
2545 cfg
.name
.c_str(), testtype
, datebuf
);
2552 // Print a list of future tests.
2553 static void PrintTestSchedule(const dev_config_vector
& configs
, dev_state_vector
& states
, const smart_device_list
& devices
)
2555 unsigned numdev
= configs
.size();
2558 std::vector
<int> testcnts(numdev
* num_test_types
, 0);
2560 PrintOut(LOG_INFO
, "\nNext scheduled self tests (at most 5 of each type per device):\n");
2562 // FixGlibcTimeZoneBug(); // done in PrintOut()
2563 time_t now
= time(0);
2564 char datenow
[DATEANDEPOCHLEN
], date
[DATEANDEPOCHLEN
];
2565 dateandtimezoneepoch(datenow
, now
);
2568 for (seconds
=checktime
; seconds
<3600L*24*90; seconds
+=checktime
) {
2569 // Check for each device whether a test will be run
2570 time_t testtime
= now
+ seconds
;
2571 for (unsigned i
= 0; i
< numdev
; i
++) {
2572 const dev_config
& cfg
= configs
.at(i
);
2573 dev_state
& state
= states
.at(i
);
2575 char testtype
= next_scheduled_test(cfg
, state
, devices
.at(i
)->is_scsi(), testtime
);
2576 if (testtype
&& (p
= strchr(test_type_chars
, testtype
))) {
2577 unsigned t
= (p
- test_type_chars
);
2578 // Report at most 5 tests of each type
2579 if (++testcnts
[i
*num_test_types
+ t
] <= 5) {
2580 dateandtimezoneepoch(date
, testtime
);
2581 PrintOut(LOG_INFO
, "Device: %s, will do test %d of type %c at %s\n", cfg
.name
.c_str(),
2582 testcnts
[i
*num_test_types
+ t
], testtype
, date
);
2589 dateandtimezoneepoch(date
, now
+seconds
);
2590 PrintOut(LOG_INFO
, "\nTotals [%s - %s]:\n", datenow
, date
);
2591 for (unsigned i
= 0; i
< numdev
; i
++) {
2592 const dev_config
& cfg
= configs
.at(i
);
2593 bool scsi
= devices
.at(i
)->is_scsi();
2594 for (unsigned t
= 0; t
< num_test_types
; t
++) {
2595 int cnt
= testcnts
[i
*num_test_types
+ t
];
2596 if (cnt
== 0 && !strchr((scsi
? "LS" : "LSCO"), test_type_chars
[t
]))
2598 PrintOut(LOG_INFO
, "Device: %s, will do %3d test%s of type %c\n", cfg
.name
.c_str(),
2599 cnt
, (cnt
==1?"":"s"), test_type_chars
[t
]);
2605 // Return zero on success, nonzero on failure. Perform offline (background)
2606 // short or long (extended) self test on given scsi device.
2607 static int DoSCSISelfTest(const dev_config
& cfg
, dev_state
& state
, scsi_device
* device
, char testtype
)
2610 const char *testname
= 0;
2611 const char *name
= cfg
.name
.c_str();
2614 if (scsiSelfTestInProgress(device
, &inProgress
)) {
2615 PrintOut(LOG_CRIT
, "Device: %s, does not support Self-Tests\n", name
);
2616 state
.not_cap_short
= state
.not_cap_long
= true;
2620 if (1 == inProgress
) {
2621 PrintOut(LOG_INFO
, "Device: %s, skip since Self-Test already in "
2622 "progress.\n", name
);
2628 testname
= "Short Self";
2629 retval
= scsiSmartShortSelfTest(device
);
2632 testname
= "Long Self";
2633 retval
= scsiSmartExtendSelfTest(device
);
2636 // If we can't do the test, exit
2637 if (NULL
== testname
) {
2638 PrintOut(LOG_CRIT
, "Device: %s, not capable of %c Self-Test\n", name
,
2643 if ((SIMPLE_ERR_BAD_OPCODE
== retval
) ||
2644 (SIMPLE_ERR_BAD_FIELD
== retval
)) {
2645 PrintOut(LOG_CRIT
, "Device: %s, not capable of %s-Test\n", name
,
2648 state
.not_cap_long
= true;
2650 state
.not_cap_short
= true;
2654 PrintOut(LOG_CRIT
, "Device: %s, execute %s-Test failed (err: %d)\n", name
,
2659 PrintOut(LOG_INFO
, "Device: %s, starting scheduled %s-Test.\n", name
, testname
);
2664 // Do an offline immediate or self-test. Return zero on success,
2665 // nonzero on failure.
2666 static int DoATASelfTest(const dev_config
& cfg
, dev_state
& state
, ata_device
* device
, char testtype
)
2668 const char *name
= cfg
.name
.c_str();
2670 // Read current smart data and check status/capability
2671 struct ata_smart_values data
;
2672 if (ataReadSmartValues(device
, &data
) || !(data
.offline_data_collection_capability
)) {
2673 PrintOut(LOG_CRIT
, "Device: %s, not capable of Offline or Self-Testing.\n", name
);
2677 // Check for capability to do the test
2678 int dotest
= -1, mode
= 0;
2679 const char *testname
= 0;
2682 testname
="Offline Immediate ";
2683 if (isSupportExecuteOfflineImmediate(&data
))
2684 dotest
=OFFLINE_FULL_SCAN
;
2686 state
.not_cap_offline
= true;
2689 testname
="Conveyance Self-";
2690 if (isSupportConveyanceSelfTest(&data
))
2691 dotest
=CONVEYANCE_SELF_TEST
;
2693 state
.not_cap_conveyance
= true;
2696 testname
="Short Self-";
2697 if (isSupportSelfTest(&data
))
2698 dotest
=SHORT_SELF_TEST
;
2700 state
.not_cap_short
= true;
2703 testname
="Long Self-";
2704 if (isSupportSelfTest(&data
))
2705 dotest
=EXTEND_SELF_TEST
;
2707 state
.not_cap_long
= true;
2710 case 'c': case 'n': case 'r':
2711 testname
= "Selective Self-";
2712 if (isSupportSelectiveSelfTest(&data
)) {
2713 dotest
= SELECTIVE_SELF_TEST
;
2715 case 'c': mode
= SEL_CONT
; break;
2716 case 'n': mode
= SEL_NEXT
; break;
2717 case 'r': mode
= SEL_REDO
; break;
2721 state
.not_cap_selective
= true;
2725 // If we can't do the test, exit
2727 PrintOut(LOG_CRIT
, "Device: %s, not capable of %sTest\n", name
, testname
);
2731 // If currently running a self-test, do not interrupt it to start another.
2732 if (15==(data
.self_test_exec_status
>> 4)) {
2733 if (cfg
.firmwarebugs
.is_set(BUG_SAMSUNG3
) && data
.self_test_exec_status
== 0xf0) {
2734 PrintOut(LOG_INFO
, "Device: %s, will not skip scheduled %sTest "
2735 "despite unclear Self-Test byte (SAMSUNG Firmware bug).\n", name
, testname
);
2737 PrintOut(LOG_INFO
, "Device: %s, skip scheduled %sTest; %1d0%% remaining of current Self-Test.\n",
2738 name
, testname
, (int)(data
.self_test_exec_status
& 0x0f));
2743 if (dotest
== SELECTIVE_SELF_TEST
) {
2745 ata_selective_selftest_args selargs
, prev_args
;
2746 selargs
.num_spans
= 1;
2747 selargs
.span
[0].mode
= mode
;
2748 prev_args
.num_spans
= 1;
2749 prev_args
.span
[0].start
= state
.selective_test_last_start
;
2750 prev_args
.span
[0].end
= state
.selective_test_last_end
;
2751 if (ataWriteSelectiveSelfTestLog(device
, selargs
, &data
, state
.num_sectors
, &prev_args
)) {
2752 PrintOut(LOG_CRIT
, "Device: %s, prepare %sTest failed\n", name
, testname
);
2755 uint64_t start
= selargs
.span
[0].start
, end
= selargs
.span
[0].end
;
2756 PrintOut(LOG_INFO
, "Device: %s, %s test span at LBA %" PRIu64
" - %" PRIu64
" (%" PRIu64
" sectors, %u%% - %u%% of disk).\n",
2757 name
, (selargs
.span
[0].mode
== SEL_NEXT
? "next" : "redo"),
2758 start
, end
, end
- start
+ 1,
2759 (unsigned)((100 * start
+ state
.num_sectors
/2) / state
.num_sectors
),
2760 (unsigned)((100 * end
+ state
.num_sectors
/2) / state
.num_sectors
));
2761 state
.selective_test_last_start
= start
;
2762 state
.selective_test_last_end
= end
;
2765 // execute the test, and return status
2766 int retval
= smartcommandhandler(device
, IMMEDIATE_OFFLINE
, dotest
, NULL
);
2768 PrintOut(LOG_CRIT
, "Device: %s, execute %sTest failed.\n", name
, testname
);
2772 // Report recent test start to do_disable_standby_check()
2773 // and force log of next test status
2774 if (testtype
== 'O')
2775 state
.offline_started
= true;
2777 state
.selftest_started
= true;
2779 PrintOut(LOG_INFO
, "Device: %s, starting scheduled %sTest.\n", name
, testname
);
2783 // Check pending sector count attribute values (-C, -U directives).
2784 static void check_pending(const dev_config
& cfg
, dev_state
& state
,
2785 unsigned char id
, bool increase_only
,
2786 const ata_smart_values
& smartval
,
2787 int mailtype
, const char * msg
)
2789 // Find attribute index
2790 int i
= ata_find_attr_index(id
, smartval
);
2791 if (!(i
>= 0 && ata_find_attr_index(id
, state
.smartval
) == i
))
2794 // No report if no sectors pending.
2795 uint64_t rawval
= ata_get_attr_raw_value(smartval
.vendor_attributes
[i
], cfg
.attribute_defs
);
2797 reset_warning_mail(cfg
, state
, mailtype
, "No more %s", msg
);
2801 // If attribute is not reset, report only sector count increases.
2802 uint64_t prev_rawval
= ata_get_attr_raw_value(state
.smartval
.vendor_attributes
[i
], cfg
.attribute_defs
);
2803 if (!(!increase_only
|| prev_rawval
< rawval
))
2807 std::string s
= strprintf("Device: %s, %" PRId64
" %s", cfg
.name
.c_str(), rawval
, msg
);
2808 if (prev_rawval
> 0 && rawval
!= prev_rawval
)
2809 s
+= strprintf(" (changed %+" PRId64
")", rawval
- prev_rawval
);
2811 PrintOut(LOG_CRIT
, "%s\n", s
.c_str());
2812 MailWarning(cfg
, state
, mailtype
, "%s", s
.c_str());
2813 state
.must_write
= true;
2816 // Format Temperature value
2817 static const char * fmt_temp(unsigned char x
, char (& buf
)[20])
2821 snprintf(buf
, sizeof(buf
), "%u", x
);
2825 // Check Temperature limits
2826 static void CheckTemperature(const dev_config
& cfg
, dev_state
& state
, unsigned char currtemp
, unsigned char triptemp
)
2828 if (!(0 < currtemp
&& currtemp
< 255)) {
2829 PrintOut(LOG_INFO
, "Device: %s, failed to read Temperature\n", cfg
.name
.c_str());
2833 // Update Max Temperature
2834 const char * minchg
= "", * maxchg
= "";
2835 if (currtemp
> state
.tempmax
) {
2838 state
.tempmax
= currtemp
;
2839 state
.must_write
= true;
2843 if (!state
.temperature
) {
2845 if (!state
.tempmin
|| currtemp
< state
.tempmin
)
2846 // Delay Min Temperature update by ~ 30 minutes.
2847 state
.tempmin_delay
= time(0) + CHECKTIME
- 60;
2848 PrintOut(LOG_INFO
, "Device: %s, initial Temperature is %d Celsius (Min/Max %s/%u%s)\n",
2849 cfg
.name
.c_str(), (int)currtemp
, fmt_temp(state
.tempmin
, buf
), state
.tempmax
, maxchg
);
2851 PrintOut(LOG_INFO
, " [trip Temperature is %d Celsius]\n", (int)triptemp
);
2852 state
.temperature
= currtemp
;
2855 if (state
.tempmin_delay
) {
2856 // End Min Temperature update delay if ...
2857 if ( (state
.tempmin
&& currtemp
> state
.tempmin
) // current temp exceeds recorded min,
2858 || (state
.tempmin_delay
<= time(0))) { // or delay time is over.
2859 state
.tempmin_delay
= 0;
2861 state
.tempmin
= 255;
2865 // Update Min Temperature
2866 if (!state
.tempmin_delay
&& currtemp
< state
.tempmin
) {
2867 state
.tempmin
= currtemp
;
2868 state
.must_write
= true;
2869 if (currtemp
!= state
.temperature
)
2874 if (cfg
.tempdiff
&& (*minchg
|| *maxchg
|| abs((int)currtemp
- (int)state
.temperature
) >= cfg
.tempdiff
)) {
2875 PrintOut(LOG_INFO
, "Device: %s, Temperature changed %+d Celsius to %u Celsius (Min/Max %s%s/%u%s)\n",
2876 cfg
.name
.c_str(), (int)currtemp
-(int)state
.temperature
, currtemp
, fmt_temp(state
.tempmin
, buf
), minchg
, state
.tempmax
, maxchg
);
2877 state
.temperature
= currtemp
;
2882 if (cfg
.tempcrit
&& currtemp
>= cfg
.tempcrit
) {
2883 PrintOut(LOG_CRIT
, "Device: %s, Temperature %u Celsius reached critical limit of %u Celsius (Min/Max %s%s/%u%s)\n",
2884 cfg
.name
.c_str(), currtemp
, cfg
.tempcrit
, fmt_temp(state
.tempmin
, buf
), minchg
, state
.tempmax
, maxchg
);
2885 MailWarning(cfg
, state
, 12, "Device: %s, Temperature %d Celsius reached critical limit of %u Celsius (Min/Max %s%s/%u%s)",
2886 cfg
.name
.c_str(), currtemp
, cfg
.tempcrit
, fmt_temp(state
.tempmin
, buf
), minchg
, state
.tempmax
, maxchg
);
2888 else if (cfg
.tempinfo
&& currtemp
>= cfg
.tempinfo
) {
2889 PrintOut(LOG_INFO
, "Device: %s, Temperature %u Celsius reached limit of %u Celsius (Min/Max %s%s/%u%s)\n",
2890 cfg
.name
.c_str(), currtemp
, cfg
.tempinfo
, fmt_temp(state
.tempmin
, buf
), minchg
, state
.tempmax
, maxchg
);
2892 else if (cfg
.tempcrit
) {
2893 unsigned char limit
= (cfg
.tempinfo
? cfg
.tempinfo
: cfg
.tempcrit
-5);
2894 if (currtemp
< limit
)
2895 reset_warning_mail(cfg
, state
, 12, "Temperature %u Celsius dropped below %u Celsius", currtemp
, limit
);
2899 // Check normalized and raw attribute values.
2900 static void check_attribute(const dev_config
& cfg
, dev_state
& state
,
2901 const ata_smart_attribute
& attr
,
2902 const ata_smart_attribute
& prev
,
2904 const ata_smart_threshold_entry
* thresholds
)
2906 // Check attribute and threshold
2907 ata_attr_state attrstate
= ata_get_attr_state(attr
, attridx
, thresholds
, cfg
.attribute_defs
);
2908 if (attrstate
== ATTRSTATE_NON_EXISTING
)
2911 // If requested, check for usage attributes that have failed.
2912 if ( cfg
.usagefailed
&& attrstate
== ATTRSTATE_FAILED_NOW
2913 && !cfg
.monitor_attr_flags
.is_set(attr
.id
, MONITOR_IGN_FAILUSE
)) {
2914 std::string attrname
= ata_get_smart_attr_name(attr
.id
, cfg
.attribute_defs
, cfg
.dev_rpm
);
2915 PrintOut(LOG_CRIT
, "Device: %s, Failed SMART usage Attribute: %d %s.\n", cfg
.name
.c_str(), attr
.id
, attrname
.c_str());
2916 MailWarning(cfg
, state
, 2, "Device: %s, Failed SMART usage Attribute: %d %s.", cfg
.name
.c_str(), attr
.id
, attrname
.c_str());
2917 state
.must_write
= true;
2920 // Return if we're not tracking this type of attribute
2921 bool prefail
= !!ATTRIBUTE_FLAGS_PREFAILURE(attr
.flags
);
2922 if (!( ( prefail
&& cfg
.prefail
)
2923 || (!prefail
&& cfg
.usage
)))
2926 // Return if '-I ID' was specified
2927 if (cfg
.monitor_attr_flags
.is_set(attr
.id
, MONITOR_IGNORE
))
2930 // Issue warning if they don't have the same ID in all structures.
2931 if (attr
.id
!= prev
.id
) {
2932 PrintOut(LOG_INFO
,"Device: %s, same Attribute has different ID numbers: %d = %d\n",
2933 cfg
.name
.c_str(), attr
.id
, prev
.id
);
2937 // Compare normalized values if valid.
2938 bool valchanged
= false;
2939 if (attrstate
> ATTRSTATE_NO_NORMVAL
) {
2940 if (attr
.current
!= prev
.current
)
2944 // Compare raw values if requested.
2945 bool rawchanged
= false;
2946 if (cfg
.monitor_attr_flags
.is_set(attr
.id
, MONITOR_RAW
)) {
2947 if ( ata_get_attr_raw_value(attr
, cfg
.attribute_defs
)
2948 != ata_get_attr_raw_value(prev
, cfg
.attribute_defs
))
2952 // Return if no change
2953 if (!(valchanged
|| rawchanged
))
2956 // Format value strings
2957 std::string currstr
, prevstr
;
2958 if (attrstate
== ATTRSTATE_NO_NORMVAL
) {
2959 // Print raw values only
2960 currstr
= strprintf("%s (Raw)",
2961 ata_format_attr_raw_value(attr
, cfg
.attribute_defs
).c_str());
2962 prevstr
= strprintf("%s (Raw)",
2963 ata_format_attr_raw_value(prev
, cfg
.attribute_defs
).c_str());
2965 else if (cfg
.monitor_attr_flags
.is_set(attr
.id
, MONITOR_RAW_PRINT
)) {
2966 // Print normalized and raw values
2967 currstr
= strprintf("%d [Raw %s]", attr
.current
,
2968 ata_format_attr_raw_value(attr
, cfg
.attribute_defs
).c_str());
2969 prevstr
= strprintf("%d [Raw %s]", prev
.current
,
2970 ata_format_attr_raw_value(prev
, cfg
.attribute_defs
).c_str());
2973 // Print normalized values only
2974 currstr
= strprintf("%d", attr
.current
);
2975 prevstr
= strprintf("%d", prev
.current
);
2979 std::string msg
= strprintf("Device: %s, SMART %s Attribute: %d %s changed from %s to %s",
2980 cfg
.name
.c_str(), (prefail
? "Prefailure" : "Usage"), attr
.id
,
2981 ata_get_smart_attr_name(attr
.id
, cfg
.attribute_defs
, cfg
.dev_rpm
).c_str(),
2982 prevstr
.c_str(), currstr
.c_str());
2984 // Report this change as critical ?
2985 if ( (valchanged
&& cfg
.monitor_attr_flags
.is_set(attr
.id
, MONITOR_AS_CRIT
))
2986 || (rawchanged
&& cfg
.monitor_attr_flags
.is_set(attr
.id
, MONITOR_RAW_AS_CRIT
))) {
2987 PrintOut(LOG_CRIT
, "%s\n", msg
.c_str());
2988 MailWarning(cfg
, state
, 2, "%s", msg
.c_str());
2991 PrintOut(LOG_INFO
, "%s\n", msg
.c_str());
2993 state
.must_write
= true;
2997 static int ATACheckDevice(const dev_config
& cfg
, dev_state
& state
, ata_device
* atadev
,
2998 bool firstpass
, bool allow_selftests
)
3000 const char * name
= cfg
.name
.c_str();
3002 // If user has asked, test the email warning system
3004 MailWarning(cfg
, state
, 0, "TEST EMAIL from smartd for device: %s", name
);
3006 // if we can't open device, fail gracefully rather than hard --
3007 // perhaps the next time around we'll be able to open it. ATAPI
3008 // cd/dvd devices will hang awaiting media if O_NONBLOCK is not
3009 // given (see linux cdrom driver).
3010 if (!atadev
->open()) {
3011 PrintOut(LOG_INFO
, "Device: %s, open() failed: %s\n", name
, atadev
->get_errmsg());
3012 MailWarning(cfg
, state
, 9, "Device: %s, unable to open device", name
);
3016 PrintOut(LOG_INFO
,"Device: %s, opened ATA device\n", name
);
3017 reset_warning_mail(cfg
, state
, 9, "open device worked again");
3019 // user may have requested (with the -n Directive) to leave the disk
3020 // alone if it is in idle or sleeping mode. In this case check the
3021 // power mode and exit without check if needed
3022 if (cfg
.powermode
&& !state
.powermodefail
) {
3023 int dontcheck
=0, powermode
=ataCheckPowerMode(atadev
);
3024 const char * mode
= 0;
3025 if (0 <= powermode
&& powermode
< 0xff) {
3026 // wait for possible spin up and check again
3029 powermode2
= ataCheckPowerMode(atadev
);
3030 if (powermode2
> powermode
)
3031 PrintOut(LOG_INFO
, "Device: %s, CHECK POWER STATUS spins up disk (0x%02x -> 0x%02x)\n", name
, powermode
, powermode2
);
3032 powermode
= powermode2
;
3039 if (cfg
.powermode
>=1)
3045 if (cfg
.powermode
>=2)
3051 if (cfg
.powermode
>=3)
3056 mode
="ACTIVE or IDLE";
3060 PrintOut(LOG_CRIT
, "Device: %s, CHECK POWER STATUS returned %d, not ATA compliant, ignoring -n Directive\n",
3062 state
.powermodefail
= true;
3066 // if we are going to skip a check, return now
3068 // skip at most powerskipmax checks
3069 if (!cfg
.powerskipmax
|| state
.powerskipcnt
<cfg
.powerskipmax
) {
3070 CloseDevice(atadev
, name
);
3071 if (!state
.powerskipcnt
&& !cfg
.powerquiet
) // report first only and avoid waking up system disk
3072 PrintOut(LOG_INFO
, "Device: %s, is in %s mode, suspending checks\n", name
, mode
);
3073 state
.powerskipcnt
++;
3077 PrintOut(LOG_INFO
, "Device: %s, %s mode ignored due to reached limit of skipped checks (%d check%s skipped)\n",
3078 name
, mode
, state
.powerskipcnt
, (state
.powerskipcnt
==1?"":"s"));
3080 state
.powerskipcnt
= 0;
3081 state
.tempmin_delay
= time(0) + CHECKTIME
- 60; // Delay Min Temperature update
3083 else if (state
.powerskipcnt
) {
3084 PrintOut(LOG_INFO
, "Device: %s, is back in %s mode, resuming checks (%d check%s skipped)\n",
3085 name
, mode
, state
.powerskipcnt
, (state
.powerskipcnt
==1?"":"s"));
3086 state
.powerskipcnt
= 0;
3087 state
.tempmin_delay
= time(0) + CHECKTIME
- 60; // Delay Min Temperature update
3091 // check smart status
3092 if (cfg
.smartcheck
) {
3093 int status
=ataSmartStatus2(atadev
);
3095 PrintOut(LOG_INFO
,"Device: %s, not capable of SMART self-check\n",name
);
3096 MailWarning(cfg
, state
, 5, "Device: %s, not capable of SMART self-check", name
);
3097 state
.must_write
= true;
3099 else if (status
==1){
3100 PrintOut(LOG_CRIT
, "Device: %s, FAILED SMART self-check. BACK UP DATA NOW!\n", name
);
3101 MailWarning(cfg
, state
, 1, "Device: %s, FAILED SMART self-check. BACK UP DATA NOW!", name
);
3102 state
.must_write
= true;
3106 // Check everything that depends upon SMART Data (eg, Attribute values)
3107 if ( cfg
.usagefailed
|| cfg
.prefail
|| cfg
.usage
3108 || cfg
.curr_pending_id
|| cfg
.offl_pending_id
3109 || cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
3110 || cfg
.selftest
|| cfg
.offlinests
|| cfg
.selfteststs
) {
3112 // Read current attribute values.
3113 ata_smart_values curval
;
3114 if (ataReadSmartValues(atadev
, &curval
)){
3115 PrintOut(LOG_CRIT
, "Device: %s, failed to read SMART Attribute Data\n", name
);
3116 MailWarning(cfg
, state
, 6, "Device: %s, failed to read SMART Attribute Data", name
);
3117 state
.must_write
= true;
3120 reset_warning_mail(cfg
, state
, 6, "read SMART Attribute Data worked again");
3122 // look for current or offline pending sectors
3123 if (cfg
.curr_pending_id
)
3124 check_pending(cfg
, state
, cfg
.curr_pending_id
, cfg
.curr_pending_incr
, curval
, 10,
3125 (!cfg
.curr_pending_incr
? "Currently unreadable (pending) sectors"
3126 : "Total unreadable (pending) sectors" ));
3128 if (cfg
.offl_pending_id
)
3129 check_pending(cfg
, state
, cfg
.offl_pending_id
, cfg
.offl_pending_incr
, curval
, 11,
3130 (!cfg
.offl_pending_incr
? "Offline uncorrectable sectors"
3131 : "Total offline uncorrectable sectors"));
3133 // check temperature limits
3134 if (cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
)
3135 CheckTemperature(cfg
, state
, ata_return_temperature_value(&curval
, cfg
.attribute_defs
), 0);
3137 // look for failed usage attributes, or track usage or prefail attributes
3138 if (cfg
.usagefailed
|| cfg
.prefail
|| cfg
.usage
) {
3139 for (int i
= 0; i
< NUMBER_ATA_SMART_ATTRIBUTES
; i
++) {
3140 check_attribute(cfg
, state
,
3141 curval
.vendor_attributes
[i
],
3142 state
.smartval
.vendor_attributes
[i
],
3143 i
, state
.smartthres
.thres_entries
);
3147 // Log changes of offline data collection status
3148 if (cfg
.offlinests
) {
3149 if ( curval
.offline_data_collection_status
3150 != state
.smartval
.offline_data_collection_status
3151 || state
.offline_started
// test was started in previous call
3152 || (firstpass
&& (debugmode
|| (curval
.offline_data_collection_status
& 0x7d))))
3153 log_offline_data_coll_status(name
, curval
.offline_data_collection_status
);
3156 // Log changes of self-test execution status
3157 if (cfg
.selfteststs
) {
3158 if ( curval
.self_test_exec_status
!= state
.smartval
.self_test_exec_status
3159 || state
.selftest_started
// test was started in previous call
3160 || (firstpass
&& (debugmode
|| curval
.self_test_exec_status
!= 0x00)))
3161 log_self_test_exec_status(name
, curval
.self_test_exec_status
);
3164 // Save the new values for the next time around
3165 state
.smartval
= curval
;
3168 state
.offline_started
= state
.selftest_started
= false;
3170 // check if number of selftest errors has increased (note: may also DECREASE)
3172 CheckSelfTestLogs(cfg
, state
, SelfTestErrorCount(atadev
, name
, cfg
.firmwarebugs
));
3174 // check if number of ATA errors has increased
3175 if (cfg
.errorlog
|| cfg
.xerrorlog
) {
3177 int errcnt1
= -1, errcnt2
= -1;
3179 errcnt1
= read_ata_error_count(atadev
, name
, cfg
.firmwarebugs
, false);
3181 errcnt2
= read_ata_error_count(atadev
, name
, cfg
.firmwarebugs
, true);
3183 // new number of errors is max of both logs
3184 int newc
= (errcnt1
>= errcnt2
? errcnt1
: errcnt2
);
3186 // did command fail?
3188 // lack of PrintOut here is INTENTIONAL
3189 MailWarning(cfg
, state
, 7, "Device: %s, Read SMART Error Log Failed", name
);
3191 // has error count increased?
3192 int oldc
= state
.ataerrorcount
;
3194 PrintOut(LOG_CRIT
, "Device: %s, ATA error count increased from %d to %d\n",
3196 MailWarning(cfg
, state
, 4, "Device: %s, ATA error count increased from %d to %d",
3198 state
.must_write
= true;
3202 state
.ataerrorcount
=newc
;
3205 // if the user has asked, and device is capable (or we're not yet
3206 // sure) check whether a self test should be done now.
3207 if (allow_selftests
&& !cfg
.test_regex
.empty()) {
3208 char testtype
= next_scheduled_test(cfg
, state
, false/*!scsi*/);
3210 DoATASelfTest(cfg
, state
, atadev
, testtype
);
3213 // Don't leave device open -- the OS/user may want to access it
3214 // before the next smartd cycle!
3215 CloseDevice(atadev
, name
);
3217 // Copy ATA attribute values to persistent state
3218 state
.update_persistent_state();
3223 static int SCSICheckDevice(const dev_config
& cfg
, dev_state
& state
, scsi_device
* scsidev
, bool allow_selftests
)
3229 const char * name
= cfg
.name
.c_str();
3232 // If the user has asked for it, test the email warning system
3234 MailWarning(cfg
, state
, 0, "TEST EMAIL from smartd for device: %s", name
);
3236 // if we can't open device, fail gracefully rather than hard --
3237 // perhaps the next time around we'll be able to open it
3238 if (!scsidev
->open()) {
3239 PrintOut(LOG_INFO
, "Device: %s, open() failed: %s\n", name
, scsidev
->get_errmsg());
3240 MailWarning(cfg
, state
, 9, "Device: %s, unable to open device", name
);
3242 } else if (debugmode
)
3243 PrintOut(LOG_INFO
,"Device: %s, opened SCSI device\n", name
);
3244 reset_warning_mail(cfg
, state
, 9, "open device worked again");
3248 if (!state
.SuppressReport
) {
3249 if (scsiCheckIE(scsidev
, state
.SmartPageSupported
, state
.TempPageSupported
,
3250 &asc
, &ascq
, ¤ttemp
, &triptemp
)) {
3251 PrintOut(LOG_INFO
, "Device: %s, failed to read SMART values\n",
3253 MailWarning(cfg
, state
, 6, "Device: %s, failed to read SMART values", name
);
3254 state
.SuppressReport
= 1;
3258 cp
= scsiGetIEString(asc
, ascq
);
3260 PrintOut(LOG_CRIT
, "Device: %s, SMART Failure: %s\n", name
, cp
);
3261 MailWarning(cfg
, state
, 1,"Device: %s, SMART Failure: %s", name
, cp
);
3262 } else if (asc
== 4 && ascq
== 9) {
3263 PrintOut(LOG_INFO
,"Device: %s, self-test in progress\n", name
);
3264 } else if (debugmode
)
3265 PrintOut(LOG_INFO
,"Device: %s, non-SMART asc,ascq: %d,%d\n",
3266 name
, (int)asc
, (int)ascq
);
3267 } else if (debugmode
)
3268 PrintOut(LOG_INFO
,"Device: %s, SMART health: passed\n", name
);
3270 // check temperature limits
3271 if (cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
|| !cfg
.attrlog_file
.empty())
3272 CheckTemperature(cfg
, state
, currenttemp
, triptemp
);
3274 // check if number of selftest errors has increased (note: may also DECREASE)
3276 CheckSelfTestLogs(cfg
, state
, scsiCountFailedSelfTests(scsidev
, 0));
3278 if (allow_selftests
&& !cfg
.test_regex
.empty()) {
3279 char testtype
= next_scheduled_test(cfg
, state
, true/*scsi*/);
3281 DoSCSISelfTest(cfg
, state
, scsidev
, testtype
);
3283 if (!cfg
.attrlog_file
.empty()){
3284 // saving error counters to state
3285 if (state
.ReadECounterPageSupported
&& (0 == scsiLogSense(scsidev
,
3286 READ_ERROR_COUNTER_LPAGE
, 0, tBuf
, sizeof(tBuf
), 0))) {
3287 scsiDecodeErrCounterPage(tBuf
, &state
.scsi_error_counters
[0].errCounter
);
3288 state
.scsi_error_counters
[0].found
=1;
3290 if (state
.WriteECounterPageSupported
&& (0 == scsiLogSense(scsidev
,
3291 WRITE_ERROR_COUNTER_LPAGE
, 0, tBuf
, sizeof(tBuf
), 0))) {
3292 scsiDecodeErrCounterPage(tBuf
, &state
.scsi_error_counters
[1].errCounter
);
3293 state
.scsi_error_counters
[1].found
=1;
3295 if (state
.VerifyECounterPageSupported
&& (0 == scsiLogSense(scsidev
,
3296 VERIFY_ERROR_COUNTER_LPAGE
, 0, tBuf
, sizeof(tBuf
), 0))) {
3297 scsiDecodeErrCounterPage(tBuf
, &state
.scsi_error_counters
[2].errCounter
);
3298 state
.scsi_error_counters
[2].found
=1;
3300 if (state
.NonMediumErrorPageSupported
&& (0 == scsiLogSense(scsidev
,
3301 NON_MEDIUM_ERROR_LPAGE
, 0, tBuf
, sizeof(tBuf
), 0))) {
3302 scsiDecodeNonMediumErrPage(tBuf
, &state
.scsi_nonmedium_error
.nme
);
3303 state
.scsi_nonmedium_error
.found
=1;
3306 CloseDevice(scsidev
, name
);
3310 // 0=not used, 1=not disabled, 2=disable rejected by OS, 3=disabled
3311 static int standby_disable_state
= 0;
3313 static void init_disable_standby_check(dev_config_vector
& configs
)
3315 // Check for '-l offlinests,ns' or '-l selfteststs,ns' directives
3316 bool sts1
= false, sts2
= false;
3317 for (unsigned i
= 0; i
< configs
.size() && !(sts1
|| sts2
); i
++) {
3318 const dev_config
& cfg
= configs
.at(i
);
3319 if (cfg
.offlinests_ns
)
3321 if (cfg
.selfteststs_ns
)
3325 // Check for support of disable auto standby
3326 // Reenable standby if smartd.conf was reread
3327 if (sts1
|| sts2
|| standby_disable_state
== 3) {
3328 if (!smi()->disable_system_auto_standby(false)) {
3329 if (standby_disable_state
== 3)
3330 PrintOut(LOG_CRIT
, "System auto standby enable failed: %s\n", smi()->get_errmsg());
3332 PrintOut(LOG_INFO
, "Disable auto standby not supported, ignoring ',ns' from %s%s%s\n",
3333 (sts1
? "-l offlinests,ns" : ""), (sts1
&& sts2
? " and " : ""), (sts2
? "-l selfteststs,ns" : ""));
3334 sts1
= sts2
= false;
3339 standby_disable_state
= (sts1
|| sts2
? 1 : 0);
3342 static void do_disable_standby_check(const dev_config_vector
& configs
, const dev_state_vector
& states
)
3344 if (!standby_disable_state
)
3347 // Check for just started or still running self-tests
3348 bool running
= false;
3349 for (unsigned i
= 0; i
< configs
.size() && !running
; i
++) {
3350 const dev_config
& cfg
= configs
.at(i
); const dev_state
& state
= states
.at(i
);
3352 if ( ( cfg
.offlinests_ns
3353 && (state
.offline_started
||
3354 is_offl_coll_in_progress(state
.smartval
.offline_data_collection_status
)))
3355 || ( cfg
.selfteststs_ns
3356 && (state
.selftest_started
||
3357 is_self_test_in_progress(state
.smartval
.self_test_exec_status
))) )
3359 // state.offline/selftest_started will be reset after next logging of test status
3362 // Disable/enable auto standby and log state changes
3364 if (standby_disable_state
!= 1) {
3365 if (!smi()->disable_system_auto_standby(false))
3366 PrintOut(LOG_CRIT
, "Self-test(s) completed, system auto standby enable failed: %s\n",
3367 smi()->get_errmsg());
3369 PrintOut(LOG_INFO
, "Self-test(s) completed, system auto standby enabled\n");
3370 standby_disable_state
= 1;
3373 else if (!smi()->disable_system_auto_standby(true)) {
3374 if (standby_disable_state
!= 2) {
3375 PrintOut(LOG_INFO
, "Self-test(s) in progress, system auto standby disable rejected: %s\n",
3376 smi()->get_errmsg());
3377 standby_disable_state
= 2;
3381 if (standby_disable_state
!= 3) {
3382 PrintOut(LOG_INFO
, "Self-test(s) in progress, system auto standby disabled\n");
3383 standby_disable_state
= 3;
3388 // Checks the SMART status of all ATA and SCSI devices
3389 static void CheckDevicesOnce(const dev_config_vector
& configs
, dev_state_vector
& states
,
3390 smart_device_list
& devices
, bool firstpass
, bool allow_selftests
)
3392 for (unsigned i
= 0; i
< configs
.size(); i
++) {
3393 const dev_config
& cfg
= configs
.at(i
);
3394 dev_state
& state
= states
.at(i
);
3395 smart_device
* dev
= devices
.at(i
);
3397 ATACheckDevice(cfg
, state
, dev
->to_ata(), firstpass
, allow_selftests
);
3398 else if (dev
->is_scsi())
3399 SCSICheckDevice(cfg
, state
, dev
->to_scsi(), allow_selftests
);
3402 do_disable_standby_check(configs
, states
);
3405 // Set if Initialize() was called
3406 static bool is_initialized
= false;
3408 // Does initialization right after fork to daemon mode
3409 static void Initialize(time_t *wakeuptime
)
3411 // Call Goodbye() on exit
3412 is_initialized
= true;
3418 // install signal handlers. On Solaris, can't use signal() because
3419 // it resets the handler to SIG_DFL after each call. So use sigset()
3420 // instead. So SIGNALFN()==signal() or SIGNALFN()==sigset().
3422 // normal and abnormal exit
3423 if (SIGNALFN(SIGTERM
, sighandler
)==SIG_IGN
)
3424 SIGNALFN(SIGTERM
, SIG_IGN
);
3425 if (SIGNALFN(SIGQUIT
, sighandler
)==SIG_IGN
)
3426 SIGNALFN(SIGQUIT
, SIG_IGN
);
3428 // in debug mode, <CONTROL-C> ==> HUP
3429 if (SIGNALFN(SIGINT
, debugmode
?HUPhandler
:sighandler
)==SIG_IGN
)
3430 SIGNALFN(SIGINT
, SIG_IGN
);
3432 // Catch HUP and USR1
3433 if (SIGNALFN(SIGHUP
, HUPhandler
)==SIG_IGN
)
3434 SIGNALFN(SIGHUP
, SIG_IGN
);
3435 if (SIGNALFN(SIGUSR1
, USR1handler
)==SIG_IGN
)
3436 SIGNALFN(SIGUSR1
, SIG_IGN
);
3438 if (SIGNALFN(SIGUSR2
, USR2handler
)==SIG_IGN
)
3439 SIGNALFN(SIGUSR2
, SIG_IGN
);
3442 // initialize wakeup time to CURRENT time
3443 *wakeuptime
=time(NULL
);
3449 // Toggle debug mode implemented for native windows only
3450 // (there is no easy way to reopen tty on *nix)
3451 static void ToggleDebugMode()
3454 PrintOut(LOG_INFO
,"Signal USR2 - enabling debug mode\n");
3455 if (!daemon_enable_console("smartd [Debug]")) {
3457 daemon_signal(SIGINT
, HUPhandler
);
3458 PrintOut(LOG_INFO
,"smartd debug mode enabled, PID=%d\n", getpid());
3461 PrintOut(LOG_INFO
,"enable console failed\n");
3463 else if (debugmode
== 1) {
3464 daemon_disable_console();
3466 daemon_signal(SIGINT
, sighandler
);
3467 PrintOut(LOG_INFO
,"Signal USR2 - debug mode disabled\n");
3470 PrintOut(LOG_INFO
,"Signal USR2 - debug mode %d not changed\n", debugmode
);
3474 static time_t dosleep(time_t wakeuptime
, bool & sigwakeup
)
3476 // If past wake-up-time, compute next wake-up-time
3477 time_t timenow
=time(NULL
);
3478 while (wakeuptime
<=timenow
){
3479 int intervals
=1+(timenow
-wakeuptime
)/checktime
;
3480 wakeuptime
+=intervals
*checktime
;
3483 // sleep until we catch SIGUSR1 or have completed sleeping
3485 while (timenow
< wakeuptime
+addtime
&& !caughtsigUSR1
&& !caughtsigHUP
&& !caughtsigEXIT
) {
3487 // protect user again system clock being adjusted backwards
3488 if (wakeuptime
>timenow
+checktime
){
3489 PrintOut(LOG_CRIT
, "System clock time adjusted to the past. Resetting next wakeup time.\n");
3490 wakeuptime
=timenow
+checktime
;
3493 // Exit sleep when time interval has expired or a signal is received
3494 sleep(wakeuptime
+addtime
-timenow
);
3497 // toggle debug mode?
3498 if (caughtsigUSR2
) {
3506 // Actual sleep time too long?
3507 if (!addtime
&& timenow
> wakeuptime
+60) {
3509 PrintOut(LOG_INFO
, "Sleep time was %d seconds too long, assuming wakeup from standby mode.\n",
3510 (int)(timenow
-wakeuptime
));
3511 // Wait another 20 seconds to avoid I/O errors during disk spin-up
3512 addtime
= timenow
-wakeuptime
+20;
3513 // Use next wake-up-time if close
3514 int nextcheck
= checktime
- addtime
% checktime
;
3515 if (nextcheck
<= 20)
3516 addtime
+= nextcheck
;
3520 // if we caught a SIGUSR1 then print message and clear signal
3522 PrintOut(LOG_INFO
,"Signal USR1 - checking devices now rather than in %d seconds.\n",
3523 wakeuptime
-timenow
>0?(int)(wakeuptime
-timenow
):0);
3528 // return adjusted wakeuptime
3532 // Print out a list of valid arguments for the Directive d
3533 static void printoutvaliddirectiveargs(int priority
, char d
)
3537 PrintOut(priority
, "never[,N][,q], sleep[,N][,q], standby[,N][,q], idle[,N][,q]");
3540 PrintOut(priority
, "valid_regular_expression");
3543 PrintOut(priority
, "%s", smi()->get_valid_dev_types_str().c_str());
3546 PrintOut(priority
, "normal, permissive");
3550 PrintOut(priority
, "on, off");
3553 PrintOut(priority
, "error, selftest");
3556 PrintOut(priority
, "\"once\", \"daily\", \"diminishing\", \"test\", \"exec\"");
3559 PrintOut(priority
, "\n%s\n", create_vendor_attribute_arg_list().c_str());
3562 PrintOut(priority
, "use, ignore, show, showall");
3565 PrintOut(priority
, "%s", get_valid_firmwarebug_args());
3568 PrintOut(priority
, "aam,[N|off], apm,[N|off], lookahead,[on|off], "
3569 "security-freeze, standby,[N|off], wcache,[on|off]");
3574 // exits with an error message, or returns integer value of token
3575 static int GetInteger(const char *arg
, const char *name
, const char *token
, int lineno
, const char *cfgfile
,
3576 int min
, int max
, char * suffix
= 0)
3578 // make sure argument is there
3580 PrintOut(LOG_CRIT
,"File %s line %d (drive %s): Directive: %s takes integer argument from %d to %d.\n",
3581 cfgfile
, lineno
, name
, token
, min
, max
);
3585 // get argument value (base 10), check that it's integer, and in-range
3587 int val
= strtol(arg
,&endptr
,10);
3589 // optional suffix present?
3591 if (!strcmp(endptr
, suffix
))
3592 endptr
+= strlen(suffix
);
3597 if (!(!*endptr
&& min
<= val
&& val
<= max
)) {
3598 PrintOut(LOG_CRIT
,"File %s line %d (drive %s): Directive: %s has argument: %s; needs integer from %d to %d.\n",
3599 cfgfile
, lineno
, name
, token
, arg
, min
, max
);
3603 // all is well; return value
3608 // Get 1-3 small integer(s) for '-W' directive
3609 static int Get3Integers(const char *arg
, const char *name
, const char *token
, int lineno
, const char *cfgfile
,
3610 unsigned char *val1
, unsigned char *val2
, unsigned char *val3
)
3612 unsigned v1
= 0, v2
= 0, v3
= 0;
3613 int n1
= -1, n2
= -1, n3
= -1, len
;
3615 PrintOut(LOG_CRIT
,"File %s line %d (drive %s): Directive: %s takes 1-3 integer argument(s) from 0 to 255.\n",
3616 cfgfile
, lineno
, name
, token
);
3621 if (!( sscanf(arg
, "%u%n,%u%n,%u%n", &v1
, &n1
, &v2
, &n2
, &v3
, &n3
) >= 1
3622 && (n1
== len
|| n2
== len
|| n3
== len
) && v1
<= 255 && v2
<= 255 && v3
<= 255)) {
3623 PrintOut(LOG_CRIT
,"File %s line %d (drive %s): Directive: %s has argument: %s; needs 1-3 integer(s) from 0 to 255.\n",
3624 cfgfile
, lineno
, name
, token
, arg
);
3627 *val1
= (unsigned char)v1
; *val2
= (unsigned char)v2
; *val3
= (unsigned char)v3
;
3634 // Concatenate strtok() results if quoted with "..."
3635 static const char * strtok_dequote(const char * delimiters
)
3637 const char * t
= strtok(0, delimiters
);
3638 if (!t
|| t
[0] != '"')
3641 static std::string token
;
3644 t
= strtok(0, delimiters
);
3648 int len
= strlen(t
);
3649 if (t
[len
-1] == '"') {
3650 token
+= std::string(t
, len
-1);
3655 return token
.c_str();
3661 // This function returns 1 if it has correctly parsed one token (and
3662 // any arguments), else zero if no tokens remain. It returns -1 if an
3663 // error was encountered.
3664 static int ParseToken(char * token
, dev_config
& cfg
)
3667 const char * name
= cfg
.name
.c_str();
3668 int lineno
=cfg
.lineno
;
3669 const char *delim
= " \n\t";
3672 const char *arg
= 0;
3674 // is the rest of the line a comment
3678 // is the token not recognized?
3679 if (*token
!='-' || strlen(token
)!=2) {
3680 PrintOut(LOG_CRIT
,"File %s line %d (drive %s): unknown Directive: %s\n",
3681 configfile
, lineno
, name
, token
);
3682 PrintOut(LOG_CRIT
, "Run smartd -D to print a list of valid Directives.\n");
3686 // token we will be parsing:
3689 // parse the token and swallow its argument
3691 char plus
[] = "+", excl
[] = "!";
3695 // monitor current pending sector count (default 197)
3696 if ((val
= GetInteger(arg
=strtok(NULL
,delim
), name
, token
, lineno
, configfile
, 0, 255, plus
)) < 0)
3698 cfg
.curr_pending_id
= (unsigned char)val
;
3699 cfg
.curr_pending_incr
= (*plus
== '+');
3700 cfg
.curr_pending_set
= true;
3703 // monitor offline uncorrectable sectors (default 198)
3704 if ((val
= GetInteger(arg
=strtok(NULL
,delim
), name
, token
, lineno
, configfile
, 0, 255, plus
)) < 0)
3706 cfg
.offl_pending_id
= (unsigned char)val
;
3707 cfg
.offl_pending_incr
= (*plus
== '+');
3708 cfg
.offl_pending_set
= true;
3711 // Set tolerance level for SMART command failures
3712 if ((arg
= strtok(NULL
, delim
)) == NULL
) {
3714 } else if (!strcmp(arg
, "normal")) {
3715 // Normal mode: exit on failure of a mandatory S.M.A.R.T. command, but
3716 // not on failure of an optional S.M.A.R.T. command.
3717 // This is the default so we don't need to actually do anything here.
3718 cfg
.permissive
= false;
3719 } else if (!strcmp(arg
, "permissive")) {
3720 // Permissive mode; ignore errors from Mandatory SMART commands
3721 cfg
.permissive
= true;
3727 // specify the device type
3728 if ((arg
= strtok(NULL
, delim
)) == NULL
) {
3730 } else if (!strcmp(arg
, "ignore")) {
3732 } else if (!strcmp(arg
, "removable")) {
3733 cfg
.removable
= true;
3734 } else if (!strcmp(arg
, "auto")) {
3742 if (!(arg
= strtok(0, delim
)))
3744 else if (!parse_firmwarebug_def(arg
, cfg
.firmwarebugs
))
3748 // check SMART status
3749 cfg
.smartcheck
= true;
3752 // check for failure of usage attributes
3753 cfg
.usagefailed
= true;
3756 // track changes in all vendor attributes
3761 // track changes in prefail vendor attributes
3765 // track changes in usage vendor attributes
3769 // track changes in SMART logs
3770 if ((arg
= strtok(NULL
, delim
)) == NULL
) {
3772 } else if (!strcmp(arg
, "selftest")) {
3773 // track changes in self-test log
3774 cfg
.selftest
= true;
3775 } else if (!strcmp(arg
, "error")) {
3776 // track changes in ATA error log
3777 cfg
.errorlog
= true;
3778 } else if (!strcmp(arg
, "xerror")) {
3779 // track changes in Extended Comprehensive SMART error log
3780 cfg
.xerrorlog
= true;
3781 } else if (!strcmp(arg
, "offlinests")) {
3782 // track changes in offline data collection status
3783 cfg
.offlinests
= true;
3784 } else if (!strcmp(arg
, "offlinests,ns")) {
3785 // track changes in offline data collection status, disable auto standby
3786 cfg
.offlinests
= cfg
.offlinests_ns
= true;
3787 } else if (!strcmp(arg
, "selfteststs")) {
3788 // track changes in self-test execution status
3789 cfg
.selfteststs
= true;
3790 } else if (!strcmp(arg
, "selfteststs,ns")) {
3791 // track changes in self-test execution status, disable auto standby
3792 cfg
.selfteststs
= cfg
.selfteststs_ns
= true;
3793 } else if (!strncmp(arg
, "scterc,", sizeof("scterc,")-1)) {
3794 // set SCT Error Recovery Control
3795 unsigned rt
= ~0, wt
= ~0; int nc
= -1;
3796 sscanf(arg
,"scterc,%u,%u%n", &rt
, &wt
, &nc
);
3797 if (nc
== (int)strlen(arg
) && rt
<= 999 && wt
<= 999) {
3798 cfg
.sct_erc_set
= true;
3799 cfg
.sct_erc_readtime
= rt
;
3800 cfg
.sct_erc_writetime
= wt
;
3809 // monitor everything
3810 cfg
.smartcheck
= true;
3812 cfg
.usagefailed
= true;
3814 cfg
.selftest
= true;
3815 cfg
.errorlog
= true;
3816 cfg
.selfteststs
= true;
3819 // automatic offline testing enable/disable
3820 if ((arg
= strtok(NULL
, delim
)) == NULL
) {
3822 } else if (!strcmp(arg
, "on")) {
3823 cfg
.autoofflinetest
= 2;
3824 } else if (!strcmp(arg
, "off")) {
3825 cfg
.autoofflinetest
= 1;
3831 // skip disk check if in idle or standby mode
3832 if (!(arg
= strtok(NULL
, delim
)))
3835 char *endptr
= NULL
;
3836 char *next
= strchr(const_cast<char*>(arg
), ',');
3838 cfg
.powerquiet
= false;
3839 cfg
.powerskipmax
= 0;
3841 if (next
!=NULL
) *next
='\0';
3842 if (!strcmp(arg
, "never"))
3844 else if (!strcmp(arg
, "sleep"))
3846 else if (!strcmp(arg
, "standby"))
3848 else if (!strcmp(arg
, "idle"))
3853 // if optional arguments are present
3854 if (!badarg
&& next
!=NULL
) {
3856 cfg
.powerskipmax
= strtol(next
, &endptr
, 10);
3858 cfg
.powerskipmax
= 0;
3860 next
= endptr
+ (*endptr
!= '\0');
3861 if (cfg
.powerskipmax
<= 0)
3864 if (*next
!= '\0') {
3865 if (!strcmp("q", next
))
3866 cfg
.powerquiet
= true;
3875 // automatic attribute autosave enable/disable
3876 if ((arg
= strtok(NULL
, delim
)) == NULL
) {
3878 } else if (!strcmp(arg
, "on")) {
3880 } else if (!strcmp(arg
, "off")) {
3887 // warn user, and delete any previously given -s REGEXP Directives
3888 if (!cfg
.test_regex
.empty()){
3889 PrintOut(LOG_INFO
, "File %s line %d (drive %s): ignoring previous Test Directive -s %s\n",
3890 configfile
, lineno
, name
, cfg
.test_regex
.get_pattern());
3891 cfg
.test_regex
= regular_expression();
3893 // check for missing argument
3894 if (!(arg
= strtok(NULL
, delim
))) {
3899 if (!cfg
.test_regex
.compile(arg
, REG_EXTENDED
)) {
3900 // not a valid regular expression!
3901 PrintOut(LOG_CRIT
, "File %s line %d (drive %s): -s argument \"%s\" is INVALID extended regular expression. %s.\n",
3902 configfile
, lineno
, name
, arg
, cfg
.test_regex
.get_errmsg());
3906 // Do a bit of sanity checking and warn user if we think that
3907 // their regexp is "strange". User probably confused about shell
3908 // glob(3) syntax versus regular expression syntax regexp(7).
3909 if (arg
[(val
= strspn(arg
, "0123456789/.-+*|()?^$[]SLCOcnr"))])
3910 PrintOut(LOG_INFO
, "File %s line %d (drive %s): warning, character %d (%c) looks odd in extended regular expression %s\n",
3911 configfile
, lineno
, name
, val
+1, arg
[val
], arg
);
3914 // send email to address that follows
3915 if (!(arg
= strtok(NULL
,delim
)))
3918 if (!cfg
.emailaddress
.empty())
3919 PrintOut(LOG_INFO
, "File %s line %d (drive %s): ignoring previous Address Directive -m %s\n",
3920 configfile
, lineno
, name
, cfg
.emailaddress
.c_str());
3922 if ( !strcmp(arg
, "msgbox") || !strcmp(arg
, "sysmsgbox")
3923 || str_starts_with(arg
, "msgbox,") || str_starts_with(arg
, "sysmsgbox,")) {
3924 cfg
.emailaddress
= "console";
3925 const char * arg2
= strchr(arg
, ',');
3927 cfg
.emailaddress
+= arg2
;
3928 PrintOut(LOG_INFO
, "File %s line %d (drive %s): Deprecated -m %s changed to -m %s\n",
3929 configfile
, lineno
, name
, arg
, cfg
.emailaddress
.c_str());
3933 cfg
.emailaddress
= arg
;
3937 // email warning options
3938 if (!(arg
= strtok(NULL
, delim
)))
3940 else if (!strcmp(arg
, "once"))
3942 else if (!strcmp(arg
, "daily"))
3944 else if (!strcmp(arg
, "diminishing"))
3946 else if (!strcmp(arg
, "test"))
3948 else if (!strcmp(arg
, "exec")) {
3949 // Get the next argument (the command line)
3951 // Allow "/path name/with spaces/..." on Windows
3952 arg
= strtok_dequote(delim
);
3953 if (arg
&& arg
[0] == '"') {
3954 PrintOut(LOG_CRIT
, "File %s line %d (drive %s): Directive %s 'exec' argument: missing closing quote\n",
3955 configfile
, lineno
, name
, token
);
3959 arg
= strtok(0, delim
);
3962 PrintOut(LOG_CRIT
, "File %s line %d (drive %s): Directive %s 'exec' argument must be followed by executable path.\n",
3963 configfile
, lineno
, name
, token
);
3966 // Free the last cmd line given if any, and copy new one
3967 if (!cfg
.emailcmdline
.empty())
3968 PrintOut(LOG_INFO
, "File %s line %d (drive %s): ignoring previous mail Directive -M exec %s\n",
3969 configfile
, lineno
, name
, cfg
.emailcmdline
.c_str());
3970 cfg
.emailcmdline
= arg
;
3976 // ignore failure of usage attribute
3977 if ((val
=GetInteger(arg
=strtok(NULL
,delim
), name
, token
, lineno
, configfile
, 1, 255))<0)
3979 cfg
.monitor_attr_flags
.set(val
, MONITOR_IGN_FAILUSE
);
3982 // ignore attribute for tracking purposes
3983 if ((val
=GetInteger(arg
=strtok(NULL
,delim
), name
, token
, lineno
, configfile
, 1, 255))<0)
3985 cfg
.monitor_attr_flags
.set(val
, MONITOR_IGNORE
);
3988 // print raw value when tracking
3989 if ((val
= GetInteger(arg
=strtok(NULL
,delim
), name
, token
, lineno
, configfile
, 1, 255, excl
)) < 0)
3991 cfg
.monitor_attr_flags
.set(val
, MONITOR_RAW_PRINT
);
3992 if (*excl
== '!') // attribute change is critical
3993 cfg
.monitor_attr_flags
.set(val
, MONITOR_AS_CRIT
);
3996 // track changes in raw value (forces printing of raw value)
3997 if ((val
= GetInteger(arg
=strtok(NULL
,delim
), name
, token
, lineno
, configfile
, 1, 255, excl
)) < 0)
3999 cfg
.monitor_attr_flags
.set(val
, MONITOR_RAW_PRINT
|MONITOR_RAW
);
4000 if (*excl
== '!') // raw value change is critical
4001 cfg
.monitor_attr_flags
.set(val
, MONITOR_RAW_AS_CRIT
);
4004 // track Temperature
4005 if ((val
=Get3Integers(arg
=strtok(NULL
,delim
), name
, token
, lineno
, configfile
,
4006 &cfg
.tempdiff
, &cfg
.tempinfo
, &cfg
.tempcrit
))<0)
4010 // non-default vendor-specific attribute meaning
4011 if (!(arg
=strtok(NULL
,delim
))) {
4013 } else if (!parse_attribute_def(arg
, cfg
.attribute_defs
, PRIOR_USER
)) {
4018 // Define use of drive-specific presets.
4019 if (!(arg
= strtok(NULL
, delim
))) {
4021 } else if (!strcmp(arg
, "use")) {
4022 cfg
.ignorepresets
= false;
4023 } else if (!strcmp(arg
, "ignore")) {
4024 cfg
.ignorepresets
= true;
4025 } else if (!strcmp(arg
, "show")) {
4026 cfg
.showpresets
= true;
4027 } else if (!strcmp(arg
, "showall")) {
4035 // Various ATA settings
4036 if (!(arg
= strtok(NULL
, delim
))) {
4040 char arg2
[16+1]; unsigned val
;
4041 int n1
= -1, n2
= -1, n3
= -1, len
= strlen(arg
);
4042 if (sscanf(arg
, "%16[^,=]%n%*[,=]%n%u%n", arg2
, &n1
, &n2
, &val
, &n3
) >= 1
4043 && (n1
== len
|| n2
> 0)) {
4044 bool on
= (n2
> 0 && !strcmp(arg
+n2
, "on"));
4045 bool off
= (n2
> 0 && !strcmp(arg
+n2
, "off"));
4049 if (!strcmp(arg2
, "aam")) {
4052 else if (val
<= 254)
4053 cfg
.set_aam
= val
+ 1;
4057 else if (!strcmp(arg2
, "apm")) {
4060 else if (1 <= val
&& val
<= 254)
4061 cfg
.set_apm
= val
+ 1;
4065 else if (!strcmp(arg2
, "lookahead")) {
4067 cfg
.set_lookahead
= -1;
4069 cfg
.set_lookahead
= 1;
4073 else if (!strcmp(arg
, "security-freeze")) {
4074 cfg
.set_security_freeze
= true;
4076 else if (!strcmp(arg2
, "standby")) {
4078 cfg
.set_standby
= 0 + 1;
4079 else if (val
<= 255)
4080 cfg
.set_standby
= val
+ 1;
4084 else if (!strcmp(arg2
, "wcache")) {
4086 cfg
.set_wcache
= -1;
4101 // Directive not recognized
4102 PrintOut(LOG_CRIT
,"File %s line %d (drive %s): unknown Directive: %s\n",
4103 configfile
, lineno
, name
, token
);
4108 PrintOut(LOG_CRIT
, "File %s line %d (drive %s): Missing argument to %s Directive\n",
4109 configfile
, lineno
, name
, token
);
4112 PrintOut(LOG_CRIT
, "File %s line %d (drive %s): Invalid argument to %s Directive: %s\n",
4113 configfile
, lineno
, name
, token
, arg
);
4115 if (missingarg
|| badarg
) {
4116 PrintOut(LOG_CRIT
, "Valid arguments to %s Directive are: ", token
);
4117 printoutvaliddirectiveargs(LOG_CRIT
, sym
);
4118 PrintOut(LOG_CRIT
, "\n");
4125 // Scan directive for configuration file
4126 #define SCANDIRECTIVE "DEVICESCAN"
4128 // This is the routine that adds things to the conf_entries list.
4130 // Return values are:
4131 // 1: parsed a normal line
4132 // 0: found DEFAULT setting or comment or blank line
4133 // -1: found SCANDIRECTIVE line
4134 // -2: found an error
4136 // Note: this routine modifies *line from the caller!
4137 static int ParseConfigLine(dev_config_vector
& conf_entries
, dev_config
& default_conf
, int lineno
, /*const*/ char * line
)
4139 const char *delim
= " \n\t";
4141 // get first token: device name. If a comment, skip line
4142 const char * name
= strtok(line
, delim
);
4143 if (!name
|| *name
== '#')
4146 // Check device name for DEFAULT or DEVICESCAN
4148 if (!strcmp("DEFAULT", name
)) {
4150 // Restart with empty defaults
4151 default_conf
= dev_config();
4154 retval
= (!strcmp(SCANDIRECTIVE
, name
) ? -1 : 1);
4155 // Init new entry with current defaults
4156 conf_entries
.push_back(default_conf
);
4158 dev_config
& cfg
= (retval
? conf_entries
.back() : default_conf
);
4160 cfg
.name
= name
; // Later replaced by dev->get_info().info_name
4161 cfg
.dev_name
= name
; // If DEVICESCAN later replaced by get->dev_info().dev_name
4162 cfg
.lineno
= lineno
;
4164 // parse tokens one at a time from the file.
4165 while (char * token
= strtok(0, delim
)) {
4166 int rc
= ParseToken(token
, cfg
);
4168 // error found on the line
4175 // PrintOut(LOG_INFO,"Parsed token %s\n",token);
4178 // Don't perform checks below for DEFAULT entries
4182 // If NO monitoring directives are set, then set all of them.
4183 if (!( cfg
.smartcheck
|| cfg
.selftest
4184 || cfg
.errorlog
|| cfg
.xerrorlog
4185 || cfg
.offlinests
|| cfg
.selfteststs
4186 || cfg
.usagefailed
|| cfg
.prefail
|| cfg
.usage
4187 || cfg
.tempdiff
|| cfg
.tempinfo
|| cfg
.tempcrit
)) {
4189 PrintOut(LOG_INFO
,"Drive: %s, implied '-a' Directive on line %d of file %s\n",
4190 cfg
.name
.c_str(), cfg
.lineno
, configfile
);
4192 cfg
.smartcheck
= true;
4193 cfg
.usagefailed
= true;
4196 cfg
.selftest
= true;
4197 cfg
.errorlog
= true;
4198 cfg
.selfteststs
= true;
4201 // additional sanity check. Has user set -M options without -m?
4202 if (cfg
.emailaddress
.empty() && (!cfg
.emailcmdline
.empty() || cfg
.emailfreq
|| cfg
.emailtest
)){
4203 PrintOut(LOG_CRIT
,"Drive: %s, -M Directive(s) on line %d of file %s need -m ADDRESS Directive\n",
4204 cfg
.name
.c_str(), cfg
.lineno
, configfile
);
4208 // has the user has set <nomailer>?
4209 if (cfg
.emailaddress
== "<nomailer>") {
4210 // check that -M exec is also set
4211 if (cfg
.emailcmdline
.empty()){
4212 PrintOut(LOG_CRIT
,"Drive: %s, -m <nomailer> Directive on line %d of file %s needs -M exec Directive\n",
4213 cfg
.name
.c_str(), cfg
.lineno
, configfile
);
4216 // From here on the sign of <nomailer> is cfg.emailaddress.empty() and !cfg.emailcmdline.empty()
4217 cfg
.emailaddress
.clear();
4223 // Parses a configuration file. Return values are:
4224 // N=>0: found N entries
4225 // -1: syntax error in config file
4226 // -2: config file does not exist
4227 // -3: config file exists but cannot be read
4229 // In the case where the return value is 0, there are three
4231 // Empty configuration file ==> conf_entries.empty()
4232 // No configuration file ==> conf_entries[0].lineno == 0
4233 // SCANDIRECTIVE found ==> conf_entries.back().lineno != 0 (size >= 1)
4234 static int ParseConfigFile(dev_config_vector
& conf_entries
)
4236 // maximum line length in configuration file
4237 const int MAXLINELEN
= 256;
4238 // maximum length of a continued line in configuration file
4239 const int MAXCONTLINE
= 1023;
4242 // Open config file, if it exists and is not <stdin>
4243 if (!(configfile
== configfile_stdin
)) { // pointer comparison ok here
4244 if (!f
.open(configfile
,"r") && (errno
!=ENOENT
|| !configfile_alt
.empty())) {
4245 // file exists but we can't read it or it should exist due to '-c' option
4246 int ret
= (errno
!=ENOENT
? -3 : -2);
4247 PrintOut(LOG_CRIT
,"%s: Unable to open configuration file %s\n",
4248 strerror(errno
),configfile
);
4252 else // read from stdin ('-c -' option)
4255 // Start with empty defaults
4256 dev_config default_conf
;
4258 // No configuration file found -- use fake one
4261 char fakeconfig
[] = SCANDIRECTIVE
" -a"; // TODO: Remove this hack, build cfg_entry.
4263 if (ParseConfigLine(conf_entries
, default_conf
, 0, fakeconfig
) != -1)
4264 throw std::logic_error("Internal error parsing " SCANDIRECTIVE
);
4269 setmode(fileno(f
), O_TEXT
); // Allow files with \r\n
4272 // configuration file exists
4273 PrintOut(LOG_INFO
,"Opened configuration file %s\n",configfile
);
4275 // parse config file line by line
4276 int lineno
= 1, cont
= 0, contlineno
= 0;
4277 char line
[MAXLINELEN
+2];
4278 char fullline
[MAXCONTLINE
+1];
4281 int len
=0,scandevice
;
4286 // make debugging simpler
4287 memset(line
,0,sizeof(line
));
4290 code
=fgets(line
, MAXLINELEN
+2, f
);
4292 // are we at the end of the file?
4295 scandevice
= ParseConfigLine(conf_entries
, default_conf
, contlineno
, fullline
);
4296 // See if we found a SCANDIRECTIVE directive
4299 // did we find a syntax error
4302 // the final line is part of a continuation line
4309 // input file line number
4312 // See if line is too long
4314 if (len
>MAXLINELEN
){
4316 if (line
[len
-1]=='\n')
4317 warn
="(including newline!) ";
4320 PrintOut(LOG_CRIT
,"Error: line %d of file %s %sis more than MAXLINELEN=%d characters.\n",
4321 (int)contlineno
,configfile
,warn
,(int)MAXLINELEN
);
4325 // Ignore anything after comment symbol
4326 if ((comment
=strchr(line
,'#'))){
4331 // is the total line (made of all continuation lines) too long?
4332 if (cont
+len
>MAXCONTLINE
){
4333 PrintOut(LOG_CRIT
,"Error: continued line %d (actual line %d) of file %s is more than MAXCONTLINE=%d characters.\n",
4334 lineno
, (int)contlineno
, configfile
, (int)MAXCONTLINE
);
4338 // copy string so far into fullline, and increment length
4339 snprintf(fullline
+cont
, sizeof(fullline
)-cont
, "%s" ,line
);
4342 // is this a continuation line. If so, replace \ by space and look at next line
4343 if ( (lastslash
=strrchr(line
,'\\')) && !strtok(lastslash
+1," \n\t")){
4344 *(fullline
+(cont
-len
)+(lastslash
-line
))=' ';
4348 // Not a continuation line. Parse it
4349 scandevice
= ParseConfigLine(conf_entries
, default_conf
, contlineno
, fullline
);
4351 // did we find a scandevice directive?
4354 // did we find a syntax error
4363 // note -- may be zero if syntax of file OK, but no valid entries!
4367 /* Prints the message "=======> VALID ARGUMENTS ARE: <LIST> <=======\n", where
4368 <LIST> is the list of valid arguments for option opt. */
4369 static void PrintValidArgs(char opt
)
4373 PrintOut(LOG_CRIT
, "=======> VALID ARGUMENTS ARE: ");
4374 if (!(s
= GetValidArgList(opt
)))
4375 PrintOut(LOG_CRIT
, "Error constructing argument list for option %c", opt
);
4377 PrintOut(LOG_CRIT
, "%s", (char *)s
);
4378 PrintOut(LOG_CRIT
, " <=======\n");
4382 // Report error and exit if specified path is not absolute.
4383 static void check_abs_path(char option
, const std::string
& path
)
4385 if (path
.empty() || path
[0] == '/')
4390 PrintOut(LOG_CRIT
, "=======> INVALID ARGUMENT TO -%c: %s <=======\n\n", option
, path
.c_str());
4391 PrintOut(LOG_CRIT
, "Error: relative path names are not allowed\n\n");
4396 // Parses input line, prints usage message and
4397 // version/license/copyright messages
4398 static void ParseOpts(int argc
, char **argv
)
4400 // Init default path names
4402 configfile
= SMARTMONTOOLS_SYSCONFDIR
"/smartd.conf";
4403 warning_script
= SMARTMONTOOLS_SMARTDSCRIPTDIR
"/smartd_warning.sh";
4405 std::string exedir
= get_exe_dir();
4406 static std::string configfile_str
= exedir
+ "/smartd.conf";
4407 configfile
= configfile_str
.c_str();
4408 warning_script
= exedir
+ "/smartd_warning.cmd";
4411 // Please update GetValidArgList() if you edit shortopts
4412 static const char shortopts
[] = "c:l:q:dDni:p:r:s:A:B:w:Vh?"
4413 #ifdef HAVE_LIBCAP_NG
4417 // Please update GetValidArgList() if you edit longopts
4418 struct option longopts
[] = {
4419 { "configfile", required_argument
, 0, 'c' },
4420 { "logfacility", required_argument
, 0, 'l' },
4421 { "quit", required_argument
, 0, 'q' },
4422 { "debug", no_argument
, 0, 'd' },
4423 { "showdirectives", no_argument
, 0, 'D' },
4424 { "interval", required_argument
, 0, 'i' },
4426 { "no-fork", no_argument
, 0, 'n' },
4428 { "service", no_argument
, 0, 'n' },
4430 { "pidfile", required_argument
, 0, 'p' },
4431 { "report", required_argument
, 0, 'r' },
4432 { "savestates", required_argument
, 0, 's' },
4433 { "attributelog", required_argument
, 0, 'A' },
4434 { "drivedb", required_argument
, 0, 'B' },
4435 { "warnexec", required_argument
, 0, 'w' },
4436 { "version", no_argument
, 0, 'V' },
4437 { "license", no_argument
, 0, 'V' },
4438 { "copyright", no_argument
, 0, 'V' },
4439 { "help", no_argument
, 0, 'h' },
4440 { "usage", no_argument
, 0, 'h' },
4441 #ifdef HAVE_LIBCAP_NG
4442 { "capabilities", no_argument
, 0, 'C' },
4448 bool badarg
= false;
4449 bool no_defaultdb
= false; // set true on '-B FILE'
4451 // Parse input options.
4453 while ((optchar
= getopt_long(argc
, argv
, shortopts
, longopts
, NULL
)) != -1) {
4461 if (!(strcmp(optarg
,"nodev"))) {
4463 } else if (!(strcmp(optarg
,"nodevstartup"))) {
4465 } else if (!(strcmp(optarg
,"never"))) {
4467 } else if (!(strcmp(optarg
,"onecheck"))) {
4470 } else if (!(strcmp(optarg
,"showtests"))) {
4473 } else if (!(strcmp(optarg
,"errors"))) {
4480 // set the log facility level
4481 if (!strcmp(optarg
, "daemon"))
4482 facility
=LOG_DAEMON
;
4483 else if (!strcmp(optarg
, "local0"))
4484 facility
=LOG_LOCAL0
;
4485 else if (!strcmp(optarg
, "local1"))
4486 facility
=LOG_LOCAL1
;
4487 else if (!strcmp(optarg
, "local2"))
4488 facility
=LOG_LOCAL2
;
4489 else if (!strcmp(optarg
, "local3"))
4490 facility
=LOG_LOCAL3
;
4491 else if (!strcmp(optarg
, "local4"))
4492 facility
=LOG_LOCAL4
;
4493 else if (!strcmp(optarg
, "local5"))
4494 facility
=LOG_LOCAL5
;
4495 else if (!strcmp(optarg
, "local6"))
4496 facility
=LOG_LOCAL6
;
4497 else if (!strcmp(optarg
, "local7"))
4498 facility
=LOG_LOCAL7
;
4503 // enable debug mode
4508 #ifndef _WIN32 // On Windows, --service is already handled by daemon_main()
4513 // print summary of all valid directives
4519 // Period (time interval) for checking
4520 // strtol will set errno in the event of overflow, so we'll check it.
4522 lchecktime
= strtol(optarg
, &tailptr
, 10);
4523 if (*tailptr
!= '\0' || lchecktime
< 10 || lchecktime
> INT_MAX
|| errno
) {
4526 PrintOut(LOG_CRIT
, "======> INVALID INTERVAL: %s <=======\n", optarg
);
4527 PrintOut(LOG_CRIT
, "======> INTERVAL MUST BE INTEGER BETWEEN %d AND %d <=======\n", 10, INT_MAX
);
4528 PrintOut(LOG_CRIT
, "\nUse smartd -h to get a usage summary\n\n");
4531 checktime
= (int)lchecktime
;
4534 // report IOCTL transactions
4539 // split_report_arg() may modify its first argument string, so use a
4540 // copy of optarg in case we want optarg for an error message.
4541 if (!(s
= strdup(optarg
))) {
4542 PrintOut(LOG_CRIT
, "No memory to process -r option - exiting\n");
4545 if (split_report_arg(s
, &i
)) {
4547 } else if (i
<1 || i
>3) {
4550 PrintOut(LOG_CRIT
, "======> INVALID REPORT LEVEL: %s <=======\n", optarg
);
4551 PrintOut(LOG_CRIT
, "======> LEVEL MUST BE INTEGER BETWEEN 1 AND 3<=======\n");
4553 } else if (!strcmp(s
,"ioctl")) {
4554 ata_debugmode
= scsi_debugmode
= i
;
4555 } else if (!strcmp(s
,"ataioctl")) {
4557 } else if (!strcmp(s
,"scsiioctl")) {
4562 free(s
); // TODO: use std::string
4566 // alternate configuration file
4567 if (strcmp(optarg
,"-"))
4568 configfile
= (configfile_alt
= optarg
).c_str();
4569 else // read from stdin
4570 configfile
=configfile_stdin
;
4573 // output file with PID number
4577 // path prefix of persistent state file
4578 state_path_prefix
= optarg
;
4581 // path prefix of attribute log file
4582 attrlog_path_prefix
= optarg
;
4586 const char * path
= optarg
;
4587 if (*path
== '+' && path
[1])
4590 no_defaultdb
= true;
4591 unsigned char savedebug
= debugmode
; debugmode
= 1;
4592 if (!read_drive_database(path
))
4594 debugmode
= savedebug
;
4598 warning_script
= optarg
;
4601 // print version and CVS info
4603 PrintOut(LOG_INFO
, "%s", format_version_info("smartd", true /*full*/).c_str());
4606 #ifdef HAVE_LIBCAP_NG
4608 // enable capabilities
4609 enable_capabilities
= true;
4613 // help: print summary of command-line options
4621 // unrecognized option
4624 // Point arg to the argument in which this option was found.
4625 arg
= argv
[optind
-1];
4626 // Check whether the option is a long option that doesn't map to -h.
4627 if (arg
[1] == '-' && optchar
!= 'h') {
4628 // Iff optopt holds a valid option then argument must be missing.
4629 if (optopt
&& (strchr(shortopts
, optopt
) != NULL
)) {
4630 PrintOut(LOG_CRIT
, "=======> ARGUMENT REQUIRED FOR OPTION: %s <=======\n",arg
+2);
4631 PrintValidArgs(optopt
);
4633 PrintOut(LOG_CRIT
, "=======> UNRECOGNIZED OPTION: %s <=======\n\n",arg
+2);
4635 PrintOut(LOG_CRIT
, "\nUse smartd --help to get a usage summary\n\n");
4639 // Iff optopt holds a valid option then argument must be missing.
4640 if (strchr(shortopts
, optopt
) != NULL
){
4641 PrintOut(LOG_CRIT
, "=======> ARGUMENT REQUIRED FOR OPTION: %c <=======\n",optopt
);
4642 PrintValidArgs(optopt
);
4644 PrintOut(LOG_CRIT
, "=======> UNRECOGNIZED OPTION: %c <=======\n\n",optopt
);
4646 PrintOut(LOG_CRIT
, "\nUse smartd -h to get a usage summary\n\n");
4653 // Check to see if option had an unrecognized or incorrect argument.
4657 // It would be nice to print the actual option name given by the user
4658 // here, but we just print the short form. Please fix this if you know
4659 // a clean way to do it.
4660 PrintOut(LOG_CRIT
, "=======> INVALID ARGUMENT TO -%c: %s <======= \n", optchar
, optarg
);
4661 PrintValidArgs(optchar
);
4662 PrintOut(LOG_CRIT
, "\nUse smartd -h to get a usage summary\n\n");
4667 // non-option arguments are not allowed
4668 if (argc
> optind
) {
4671 PrintOut(LOG_CRIT
, "=======> UNRECOGNIZED ARGUMENT: %s <=======\n\n", argv
[optind
]);
4672 PrintOut(LOG_CRIT
, "\nUse smartd -h to get a usage summary\n\n");
4676 // no pidfile in debug mode
4677 if (debugmode
&& !pid_file
.empty()) {
4680 PrintOut(LOG_CRIT
, "=======> INVALID CHOICE OF OPTIONS: -d and -p <======= \n\n");
4681 PrintOut(LOG_CRIT
, "Error: pid file %s not written in debug (-d) mode\n\n", pid_file
.c_str());
4687 // absolute path names are required due to chdir('/') after fork().
4688 check_abs_path('p', pid_file
);
4689 check_abs_path('s', state_path_prefix
);
4690 check_abs_path('A', attrlog_path_prefix
);
4694 // Read or init drive database
4695 if (!no_defaultdb
) {
4696 unsigned char savedebug
= debugmode
; debugmode
= 1;
4697 if (!read_default_drive_databases())
4699 debugmode
= savedebug
;
4706 // Function we call if no configuration file was found or if the
4707 // SCANDIRECTIVE Directive was found. It makes entries for device
4708 // names returned by scan_smart_devices() in os_OSNAME.cpp
4709 static int MakeConfigEntries(const dev_config
& base_cfg
,
4710 dev_config_vector
& conf_entries
, smart_device_list
& scanned_devs
, const char * type
)
4712 // make list of devices
4713 smart_device_list devlist
;
4714 if (!smi()->scan_smart_devices(devlist
, (*type
? type
: 0)))
4715 PrintOut(LOG_CRIT
,"Problem creating device name scan list\n");
4717 // if no devices, or error constructing list, return
4718 if (devlist
.size() <= 0)
4721 // add empty device slots for existing config entries
4722 while (scanned_devs
.size() < conf_entries
.size())
4723 scanned_devs
.push_back((smart_device
*)0);
4725 // loop over entries to create
4726 for (unsigned i
= 0; i
< devlist
.size(); i
++) {
4727 // Move device pointer
4728 smart_device
* dev
= devlist
.release(i
);
4729 scanned_devs
.push_back(dev
);
4731 // Copy configuration, update device and type name
4732 conf_entries
.push_back(base_cfg
);
4733 dev_config
& cfg
= conf_entries
.back();
4734 cfg
.name
= dev
->get_info().info_name
;
4735 cfg
.dev_name
= dev
->get_info().dev_name
;
4736 cfg
.dev_type
= type
;
4739 return devlist
.size();
4742 static void CanNotRegister(const char *name
, const char *type
, int line
, bool scandirective
)
4744 if (!debugmode
&& scandirective
)
4747 PrintOut(scandirective
?LOG_INFO
:LOG_CRIT
,
4748 "Unable to register %s device %s at line %d of file %s\n",
4749 type
, name
, line
, configfile
);
4751 PrintOut(LOG_INFO
,"Unable to register %s device %s\n",
4756 // Returns negative value (see ParseConfigFile()) if config file
4757 // had errors, else number of entries which may be zero or positive.
4758 static int ReadOrMakeConfigEntries(dev_config_vector
& conf_entries
, smart_device_list
& scanned_devs
)
4760 // parse configuration file configfile (normally /etc/smartd.conf)
4761 int entries
= ParseConfigFile(conf_entries
);
4764 // There was an error reading the configuration file.
4765 conf_entries
.clear();
4767 PrintOut(LOG_CRIT
, "Configuration file %s has fatal syntax errors.\n", configfile
);
4771 // no error parsing config file.
4773 // we did not find a SCANDIRECTIVE and did find valid entries
4774 PrintOut(LOG_INFO
, "Configuration file %s parsed.\n", configfile
);
4776 else if (!conf_entries
.empty()) {
4777 // we found a SCANDIRECTIVE or there was no configuration file so
4778 // scan. Configuration file's last entry contains all options
4780 dev_config first
= conf_entries
.back();
4781 conf_entries
.pop_back();
4784 PrintOut(LOG_INFO
,"Configuration file %s was parsed, found %s, scanning devices\n", configfile
, SCANDIRECTIVE
);
4786 PrintOut(LOG_INFO
,"No configuration file %s found, scanning devices\n", configfile
);
4788 // make config list of devices to search for
4789 MakeConfigEntries(first
, conf_entries
, scanned_devs
, first
.dev_type
.c_str());
4791 // warn user if scan table found no devices
4792 if (conf_entries
.empty())
4793 PrintOut(LOG_CRIT
,"In the system's table of devices NO devices found to scan\n");
4796 PrintOut(LOG_CRIT
, "Configuration file %s parsed but has no entries\n", configfile
);
4798 return conf_entries
.size();
4801 // Return true if TYPE contains a RAID drive number
4802 static bool is_raid_type(const char * type
)
4804 if (str_starts_with(type
, "sat,"))
4807 if (sscanf(type
, "%*[^,],%d", &i
) != 1)
4812 // Return true if DEV is already in DEVICES[0..NUMDEVS) or IGNORED[*]
4813 static bool is_duplicate_device(const smart_device
* dev
,
4814 const smart_device_list
& devices
, unsigned numdevs
,
4815 const dev_config_vector
& ignored
)
4817 const smart_device::device_info
& info1
= dev
->get_info();
4818 bool is_raid1
= is_raid_type(info1
.dev_type
.c_str());
4820 for (unsigned i
= 0; i
< numdevs
; i
++) {
4821 const smart_device::device_info
& info2
= devices
.at(i
)->get_info();
4822 // -d TYPE options must match if RAID drive number is specified
4823 if ( info1
.dev_name
== info2
.dev_name
4824 && ( info1
.dev_type
== info2
.dev_type
4825 || !is_raid1
|| !is_raid_type(info2
.dev_type
.c_str())))
4829 for (unsigned i
= 0; i
< ignored
.size(); i
++) {
4830 const dev_config
& cfg2
= ignored
.at(i
);
4831 if ( info1
.dev_name
== cfg2
.dev_name
4832 && ( info1
.dev_type
== cfg2
.dev_type
4833 || !is_raid1
|| !is_raid_type(cfg2
.dev_type
.c_str())))
4839 // This function tries devices from conf_entries. Each one that can be
4840 // registered is moved onto the [ata|scsi]devices lists and removed
4841 // from the conf_entries list.
4842 static void RegisterDevices(const dev_config_vector
& conf_entries
, smart_device_list
& scanned_devs
,
4843 dev_config_vector
& configs
, dev_state_vector
& states
, smart_device_list
& devices
)
4845 // start by clearing lists/memory of ALL existing devices
4851 dev_config_vector ignored_entries
;
4852 unsigned numnoscan
= 0;
4853 for (unsigned i
= 0; i
< conf_entries
.size(); i
++){
4855 dev_config cfg
= conf_entries
[i
];
4858 // Store for is_duplicate_device() check and ignore
4859 PrintOut(LOG_INFO
, "Device: %s%s%s%s, ignored\n", cfg
.name
.c_str(),
4860 (!cfg
.dev_type
.empty() ? " [" : ""),
4861 cfg
.dev_type
.c_str(),
4862 (!cfg
.dev_type
.empty() ? "]" : ""));
4863 ignored_entries
.push_back(cfg
);
4867 // get device of appropriate type
4868 smart_device_auto_ptr dev
;
4869 bool scanning
= false;
4871 // Device may already be detected during devicescan
4872 if (i
< scanned_devs
.size()) {
4873 dev
= scanned_devs
.release(i
);
4875 // Check for a preceding non-DEVICESCAN entry for the same device
4876 if ( (numnoscan
|| !ignored_entries
.empty())
4877 && is_duplicate_device(dev
.get(), devices
, numnoscan
, ignored_entries
)) {
4878 PrintOut(LOG_INFO
, "Device: %s, duplicate, ignored\n", dev
->get_info_name());
4886 dev
= smi()->get_smart_device(cfg
.name
.c_str(), cfg
.dev_type
.c_str());
4888 if (cfg
.dev_type
.empty())
4889 PrintOut(LOG_INFO
,"Device: %s, unable to autodetect device type\n", cfg
.name
.c_str());
4891 PrintOut(LOG_INFO
,"Device: %s, unsupported device type '%s'\n", cfg
.name
.c_str(), cfg
.dev_type
.c_str());
4897 smart_device::device_info oldinfo
= dev
->get_info();
4899 // Open with autodetect support, may return 'better' device
4900 dev
.replace( dev
->autodetect_open() );
4902 // Report if type has changed
4903 if (oldinfo
.dev_type
!= dev
->get_dev_type())
4904 PrintOut(LOG_INFO
,"Device: %s, type changed from '%s' to '%s'\n",
4905 cfg
.name
.c_str(), oldinfo
.dev_type
.c_str(), dev
->get_dev_type());
4907 if (!dev
->is_open()) {
4908 // For linux+devfs, a nonexistent device gives a strange error
4909 // message. This makes the error message a bit more sensible.
4910 // If no debug and scanning - don't print errors
4911 if (debugmode
|| !scanning
)
4912 PrintOut(LOG_INFO
, "Device: %s, open() failed: %s\n", dev
->get_info_name(), dev
->get_errmsg());
4916 // Update informal name
4917 cfg
.name
= dev
->get_info().info_name
;
4918 PrintOut(LOG_INFO
, "Device: %s, opened\n", cfg
.name
.c_str());
4920 // Prepare initial state
4923 // register ATA devices
4925 if (ATADeviceScan(cfg
, state
, dev
->to_ata())) {
4926 CanNotRegister(cfg
.name
.c_str(), "ATA", cfg
.lineno
, scanning
);
4930 // or register SCSI devices
4931 else if (dev
->is_scsi()){
4932 if (SCSIDeviceScan(cfg
, state
, dev
->to_scsi())) {
4933 CanNotRegister(cfg
.name
.c_str(), "SCSI", cfg
.lineno
, scanning
);
4938 PrintOut(LOG_INFO
, "Device: %s, neither ATA nor SCSI device\n", cfg
.name
.c_str());
4943 // move onto the list of devices
4944 configs
.push_back(cfg
);
4945 states
.push_back(state
);
4946 devices
.push_back(dev
);
4948 numnoscan
= devices
.size();
4950 // if device is explictly listed and we can't register it, then
4951 // exit unless the user has specified that the device is removable
4952 else if (!scanning
) {
4953 if (cfg
.removable
|| quit
==2)
4954 PrintOut(LOG_INFO
, "Device %s not available\n", cfg
.name
.c_str());
4956 PrintOut(LOG_CRIT
, "Unable to register device %s (no Directive -d removable). Exiting.\n", cfg
.name
.c_str());
4962 init_disable_standby_check(configs
);
4966 // Main program without exception handling
4967 static int main_worker(int argc
, char **argv
)
4969 // Initialize interface
4970 smart_interface::init();
4974 // is it our first pass through?
4975 bool firstpass
= true;
4977 // next time to wake up
4978 time_t wakeuptime
= 0;
4980 // parse input and print header and usage info if needed
4981 ParseOpts(argc
,argv
);
4983 // Configuration for each device
4984 dev_config_vector configs
;
4986 dev_state_vector states
;
4987 // Devices to monitor
4988 smart_device_list devices
;
4990 bool write_states_always
= true;
4992 #ifdef HAVE_LIBCAP_NG
4993 // Drop capabilities
4994 if (enable_capabilities
) {
4995 capng_clear(CAPNG_SELECT_BOTH
);
4996 capng_updatev(CAPNG_ADD
, (capng_type_t
)(CAPNG_EFFECTIVE
|CAPNG_PERMITTED
),
4997 CAP_SYS_ADMIN
, CAP_MKNOD
, CAP_SYS_RAWIO
, -1);
4998 capng_apply(CAPNG_SELECT_BOTH
);
5002 // the main loop of the code
5005 // are we exiting from a signal?
5006 if (caughtsigEXIT
) {
5007 // are we exiting with SIGTERM?
5008 int isterm
=(caughtsigEXIT
==SIGTERM
);
5009 int isquit
=(caughtsigEXIT
==SIGQUIT
);
5010 int isok
=debugmode
?isterm
|| isquit
:isterm
;
5012 PrintOut(isok
?LOG_INFO
:LOG_CRIT
, "smartd received signal %d: %s\n",
5013 caughtsigEXIT
, strsignal(caughtsigEXIT
));
5018 // Write state files
5019 if (!state_path_prefix
.empty())
5020 write_all_dev_states(configs
, states
);
5025 // Should we (re)read the config file?
5026 if (firstpass
|| caughtsigHUP
){
5028 // Write state files
5029 if (!state_path_prefix
.empty())
5030 write_all_dev_states(configs
, states
);
5034 "Signal HUP - rereading configuration file %s\n":
5035 "\a\nSignal INT - rereading configuration file %s (" SIGQUIT_KEYNAME
" quits)\n\n",
5040 dev_config_vector conf_entries
; // Entries read from smartd.conf
5041 smart_device_list scanned_devs
; // Devices found during scan
5042 // (re)reads config file, makes >=0 entries
5043 int entries
= ReadOrMakeConfigEntries(conf_entries
, scanned_devs
);
5046 // checks devices, then moves onto ata/scsi list or deallocates.
5047 RegisterDevices(conf_entries
, scanned_devs
, configs
, states
, devices
);
5048 if (!(configs
.size() == devices
.size() && configs
.size() == states
.size()))
5049 throw std::logic_error("Invalid result from RegisterDevices");
5051 else if (quit
==2 || ((quit
==0 || quit
==1) && !firstpass
)) {
5052 // user has asked to continue on error in configuration file
5054 PrintOut(LOG_INFO
,"Reusing previous configuration\n");
5057 // exit with configuration file error status
5058 return (entries
==-3 ? EXIT_READCONF
: entries
==-2 ? EXIT_NOCONF
: EXIT_BADCONF
);
5062 // Log number of devices we are monitoring...
5063 if (devices
.size() > 0 || quit
==2 || (quit
==1 && !firstpass
)) {
5065 for (unsigned i
= 0; i
< devices
.size(); i
++) {
5066 if (devices
.at(i
)->is_ata())
5069 PrintOut(LOG_INFO
,"Monitoring %d ATA and %d SCSI devices\n",
5070 numata
, devices
.size() - numata
);
5073 PrintOut(LOG_INFO
,"Unable to monitor any SMART enabled devices. Try debug (-d) option. Exiting...\n");
5078 // user has asked to print test schedule
5079 PrintTestSchedule(configs
, states
, devices
);
5083 #ifdef HAVE_LIBCAP_NG
5084 if (enable_capabilities
) {
5085 for (unsigned i
= 0; i
< configs
.size(); i
++) {
5086 if (!configs
[i
].emailaddress
.empty() || !configs
[i
].emailcmdline
.empty()) {
5087 PrintOut(LOG_WARNING
, "Mail can't be enabled together with --capabilities. All mail will be suppressed.\n");
5097 // Always write state files after (re)configuration
5098 write_states_always
= true;
5101 // check all devices once,
5102 // self tests are not started in first pass unless '-q onecheck' is specified
5103 CheckDevicesOnce(configs
, states
, devices
, firstpass
, (!firstpass
|| quit
==3));
5105 // Write state files
5106 if (!state_path_prefix
.empty())
5107 write_all_dev_states(configs
, states
, write_states_always
);
5108 write_states_always
= false;
5110 // Write attribute logs
5111 if (!attrlog_path_prefix
.empty())
5112 write_all_dev_attrlogs(configs
, states
);
5114 // user has asked us to exit after first check
5116 PrintOut(LOG_INFO
,"Started with '-q onecheck' option. All devices sucessfully checked once.\n"
5117 "smartd is exiting (exit status 0)\n");
5121 // fork into background if needed
5122 if (firstpass
&& !debugmode
) {
5126 // set exit and signal handlers, write PID file, set wake-up time
5128 Initialize(&wakeuptime
);
5132 // sleep until next check time, or a signal arrives
5133 wakeuptime
= dosleep(wakeuptime
, write_states_always
);
5140 int main(int argc
, char **argv
)
5142 // Windows: internal main function started direct or by service control manager
5143 static int smartd_main(int argc
, char **argv
)
5148 // Do the real work ...
5149 status
= main_worker(argc
, argv
);
5152 // EXIT(status) arrives here
5155 catch (const std::bad_alloc
& /*ex*/) {
5156 // Memory allocation failed (also thrown by std::operator new)
5157 PrintOut(LOG_CRIT
, "Smartd: Out of memory\n");
5158 status
= EXIT_NOMEM
;
5160 catch (const std::exception
& ex
) {
5161 // Other fatal errors
5162 PrintOut(LOG_CRIT
, "Smartd: Exception: %s\n", ex
.what());
5163 status
= EXIT_BADCODE
;
5167 status
= Goodbye(status
);
5170 daemon_winsvc_exitcode
= status
;
5177 // Main function for Windows
5178 int main(int argc
, char **argv
){
5179 // Options for smartd windows service
5180 static const daemon_winsvc_options svc_opts
= {
5181 "--service", // cmd_opt
5182 "smartd", "SmartD Service", // servicename, displayname
5184 "Controls and monitors storage devices using the Self-Monitoring, "
5185 "Analysis and Reporting Technology System (SMART) built into "
5186 "ATA/SATA and SCSI/SAS hard drives and solid-state drives. "
5187 "www.smartmontools.org"
5189 // daemon_main() handles daemon and service specific commands
5190 // and starts smartd_main() direct, from a new process,
5191 // or via service control manager
5192 return daemon_main("smartd", &svc_opts
, smartd_main
, argc
, argv
);