4 * Home page of code is: http://www.smartmontools.org
6 * Copyright (C) 2002-11 Bruce Allen
7 * Copyright (C) 2008-15 Christian Franke
8 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
9 * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2, or (at your option)
16 * You should have received a copy of the GNU General Public License
17 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
19 * This code was originally developed as a Senior Thesis by Michael Cornwell
20 * at the Concurrent Systems Laboratory (now part of the Storage Systems
21 * Research Center), Jack Baskin School of Engineering, University of
22 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
35 #include "knowndrives.h" // get_default_attr_defs()
37 #include "dev_ata_cmd_set.h" // for parsed_ata_device
39 const char * atacmds_cpp_cvsid
= "$Id: atacmds.cpp 4301 2016-04-16 20:48:29Z chrfranke $"
42 // Print ATA debug messages?
43 unsigned char ata_debugmode
= 0;
45 // Suppress serial number?
46 // (also used in scsiprint.cpp)
47 bool dont_print_serial_number
= false;
50 #define SMART_CYL_LOW 0x4F
51 #define SMART_CYL_HI 0xC2
53 // SMART RETURN STATUS yields SMART_CYL_HI,SMART_CYL_LOW to indicate drive
54 // is healthy and SRET_STATUS_HI_EXCEEDED,SRET_STATUS_MID_EXCEEDED to
55 // indicate that a threshhold exceeded condition has been detected.
56 // Those values (byte pairs) are placed in ATA register "LBA 23:8".
57 #define SRET_STATUS_HI_EXCEEDED 0x2C
58 #define SRET_STATUS_MID_EXCEEDED 0xF4
61 // Get ID and increase flag of current pending or offline
62 // uncorrectable attribute.
63 unsigned char get_unc_attr_id(bool offline
, const ata_vendor_attr_defs
& defs
,
66 unsigned char id
= (!offline
? 197 : 198);
67 const ata_vendor_attr_defs::entry
& def
= defs
[id
];
68 if (def
.flags
& ATTRFLAG_INCREASING
)
69 increase
= true; // '-v 19[78],increasing' option
70 else if (def
.name
.empty() || (id
== 198 && def
.name
== "Offline_Scan_UNC_SectCt"))
71 increase
= false; // no or '-v 198,offlinescanuncsectorct' option
73 id
= 0; // other '-v 19[78],...' option
77 #if 0 // TODO: never used
78 // This are the meanings of the Self-test failure checkpoint byte.
79 // This is in the self-test log at offset 4 bytes into the self-test
80 // descriptor and in the SMART READ DATA structure at byte offset
81 // 371. These codes are not well documented. The meanings returned by
82 // this routine are used (at least) by Maxtor and IBM. Returns NULL if
83 // not recognized. Currently the maximum length is 15 bytes.
84 const char *SelfTestFailureCodeName(unsigned char which
){
92 return "Servo_Random";
96 return "Handling_Damage";
106 // Table of raw print format names
107 struct format_name_entry
110 ata_attr_raw_format format
;
113 const format_name_entry format_names
[] = {
114 {"raw8" , RAWFMT_RAW8
},
115 {"raw16" , RAWFMT_RAW16
},
116 {"raw48" , RAWFMT_RAW48
},
117 {"hex48" , RAWFMT_HEX48
},
118 {"raw56" , RAWFMT_RAW56
},
119 {"hex56" , RAWFMT_HEX56
},
120 {"raw64" , RAWFMT_RAW64
},
121 {"hex64" , RAWFMT_HEX64
},
122 {"raw16(raw16)" , RAWFMT_RAW16_OPT_RAW16
},
123 {"raw16(avg16)" , RAWFMT_RAW16_OPT_AVG16
},
124 {"raw24(raw8)" , RAWFMT_RAW24_OPT_RAW8
},
125 {"raw24/raw24" , RAWFMT_RAW24_DIV_RAW24
},
126 {"raw24/raw32" , RAWFMT_RAW24_DIV_RAW32
},
127 {"sec2hour" , RAWFMT_SEC2HOUR
},
128 {"min2hour" , RAWFMT_MIN2HOUR
},
129 {"halfmin2hour" , RAWFMT_HALFMIN2HOUR
},
130 {"msec24hour32" , RAWFMT_MSEC24_HOUR32
},
131 {"tempminmax" , RAWFMT_TEMPMINMAX
},
132 {"temp10x" , RAWFMT_TEMP10X
},
135 const unsigned num_format_names
= sizeof(format_names
)/sizeof(format_names
[0]);
137 // Table to map old to new '-v' option arguments
138 const char * const map_old_vendor_opts
[][2] = {
139 { "9,halfminutes" , "9,halfmin2hour,Power_On_Half_Minutes"},
140 { "9,minutes" , "9,min2hour,Power_On_Minutes"},
141 { "9,seconds" , "9,sec2hour,Power_On_Seconds"},
142 { "9,temp" , "9,tempminmax,Temperature_Celsius"},
143 {"192,emergencyretractcyclect" , "192,raw48,Emerg_Retract_Cycle_Ct"},
144 {"193,loadunload" , "193,raw24/raw24"},
145 {"194,10xCelsius" , "194,temp10x,Temperature_Celsius_x10"},
146 {"194,unknown" , "194,raw48,Unknown_Attribute"},
147 {"197,increasing" , "197,raw48+,Total_Pending_Sectors"}, // '+' sets flag
148 {"198,offlinescanuncsectorct" , "198,raw48,Offline_Scan_UNC_SectCt"}, // see also get_unc_attr_id() above
149 {"198,increasing" , "198,raw48+,Total_Offl_Uncorrectabl"}, // '+' sets flag
150 {"200,writeerrorcount" , "200,raw48,Write_Error_Count"},
151 {"201,detectedtacount" , "201,raw48,Detected_TA_Count"},
152 {"220,temp" , "220,tempminmax,Temperature_Celsius"},
155 const unsigned num_old_vendor_opts
= sizeof(map_old_vendor_opts
)/sizeof(map_old_vendor_opts
[0]);
157 // Parse vendor attribute display def (-v option).
158 // Return false on error.
159 bool parse_attribute_def(const char * opt
, ata_vendor_attr_defs
& defs
,
160 ata_vendor_def_prior priority
)
162 // Map old -> new options
164 for (i
= 0; i
< num_old_vendor_opts
; i
++) {
165 if (!strcmp(opt
, map_old_vendor_opts
[i
][0])) {
166 opt
= map_old_vendor_opts
[i
][1];
172 int len
= strlen(opt
);
173 int id
= 0, n1
= -1, n2
= -1;
174 char fmtname
[32+1], attrname
[32+1], hddssd
[3+1];
175 attrname
[0] = hddssd
[0] = 0;
179 if (!( sscanf(opt
, "N,%32[^,]%n,%32[^,]%n", fmtname
, &n1
, attrname
, &n2
) >= 1
180 && (n1
== len
|| n2
== len
)))
184 // "id,format[+][,name[,HDD|SSD]]"
186 if (!( sscanf(opt
, "%d,%32[^,]%n,%32[^,]%n,%3[DHS]%n",
187 &id
, fmtname
, &n1
, attrname
, &n2
, hddssd
, &n3
) >= 2
188 && 1 <= id
&& id
<= 255
189 && ( n1
== len
|| n2
== len
190 // ",HDD|SSD" for DEFAULT settings only
191 || (n3
== len
&& priority
== PRIOR_DEFAULT
))))
196 // For "-v 19[78],increasing" above
197 if (fmtname
[strlen(fmtname
)-1] == '+') {
198 fmtname
[strlen(fmtname
)-1] = 0;
199 flags
= ATTRFLAG_INCREASING
;
202 // Split "format[:byteorder]"
203 char byteorder
[8+1] = "";
204 if (strchr(fmtname
, ':')) {
205 if (priority
== PRIOR_DEFAULT
)
206 // TODO: Allow Byteorder in DEFAULT entry
209 if (!( sscanf(fmtname
, "%*[^:]%n:%8[012345rvwz]%n", &n1
, byteorder
, &n2
) >= 1
210 && n2
== (int)strlen(fmtname
)))
213 if (strchr(byteorder
, 'v'))
214 flags
|= (ATTRFLAG_NO_NORMVAL
|ATTRFLAG_NO_WORSTVAL
);
215 if (strchr(byteorder
, 'w'))
216 flags
|= ATTRFLAG_NO_WORSTVAL
;
221 if (i
>= num_format_names
)
222 return false; // Not found
223 if (!strcmp(fmtname
, format_names
[i
].name
))
226 ata_attr_raw_format format
= format_names
[i
].format
;
228 // 64-bit formats use the normalized and worst value bytes.
229 if (!*byteorder
&& (format
== RAWFMT_RAW64
|| format
== RAWFMT_HEX64
))
230 flags
|= (ATTRFLAG_NO_NORMVAL
|ATTRFLAG_NO_WORSTVAL
);
232 // ",HDD|SSD" suffix for DEFAULT settings
234 if (!strcmp(hddssd
, "HDD"))
235 flags
|= ATTRFLAG_HDD_ONLY
;
236 else if (!strcmp(hddssd
, "SSD"))
237 flags
|= ATTRFLAG_SSD_ONLY
;
243 // "N,format" -> set format for all entries
244 for (i
= 0; i
< MAX_ATTRIBUTE_NUM
; i
++) {
245 if (defs
[i
].priority
>= priority
)
248 defs
[i
].name
= attrname
;
249 defs
[i
].priority
= priority
;
250 defs
[i
].raw_format
= format
;
251 defs
[i
].flags
= flags
;
252 snprintf(defs
[i
].byteorder
, sizeof(defs
[i
].byteorder
), "%s", byteorder
);
255 else if (defs
[id
].priority
<= priority
) {
256 // "id,format[,name]"
258 defs
[id
].name
= attrname
;
259 defs
[id
].raw_format
= format
;
260 defs
[id
].priority
= priority
;
261 defs
[id
].flags
= flags
;
262 snprintf(defs
[id
].byteorder
, sizeof(defs
[id
].byteorder
), "%s", byteorder
);
269 // Return a multiline string containing a list of valid arguments for
270 // parse_attribute_def(). The strings are preceeded by tabs and followed
271 // (except for the last) by newlines.
272 std::string
create_vendor_attribute_arg_list()
276 for (i
= 0; i
< num_format_names
; i
++)
277 s
+= strprintf("%s\tN,%s[:012345rvwz][,ATTR_NAME]",
278 (i
>0 ? "\n" : ""), format_names
[i
].name
);
279 for (i
= 0; i
< num_old_vendor_opts
; i
++)
280 s
+= strprintf("\n\t%s", map_old_vendor_opts
[i
][0]);
285 // Parse firmwarebug def (-F option).
286 // Return false on error.
287 bool parse_firmwarebug_def(const char * opt
, firmwarebug_defs
& firmwarebugs
)
289 if (!strcmp(opt
, "none"))
290 firmwarebugs
.set(BUG_NONE
);
291 else if (!strcmp(opt
, "nologdir"))
292 firmwarebugs
.set(BUG_NOLOGDIR
);
293 else if (!strcmp(opt
, "samsung"))
294 firmwarebugs
.set(BUG_SAMSUNG
);
295 else if (!strcmp(opt
, "samsung2"))
296 firmwarebugs
.set(BUG_SAMSUNG2
);
297 else if (!strcmp(opt
, "samsung3"))
298 firmwarebugs
.set(BUG_SAMSUNG3
);
299 else if (!strcmp(opt
, "xerrorlba"))
300 firmwarebugs
.set(BUG_XERRORLBA
);
306 // Return a string of valid argument words for parse_firmwarebug_def()
307 const char * get_valid_firmwarebug_args()
309 return "none, nologdir, samsung, samsung2, samsung3, xerrorlba";
313 // swap two bytes. Point to low address
314 void swap2(char *location
){
316 *location
=*(location
+1);
321 // swap four bytes. Point to low address
322 void swap4(char *location
){
324 *location
=*(location
+3);
330 // swap eight bytes. Points to low address
331 void swap8(char *location
){
333 *location
=*(location
+7);
336 *(location
+1)=*(location
+6);
342 // Invalidate serial number and WWN and adjust checksum in IDENTIFY data
343 static void invalidate_serno(ata_identify_device
* id
)
345 unsigned char sum
= 0;
347 for (i
= 0; i
< sizeof(id
->serial_no
); i
++) {
348 sum
+= id
->serial_no
[i
]; sum
-= id
->serial_no
[i
] = 'X';
350 unsigned char * b
= (unsigned char *)id
;
351 for (i
= 2*108; i
< 2*112; i
++) { // words108-111: WWN
352 sum
+= b
[i
]; sum
-= b
[i
] = 0x00;
356 bool must_swap
= !!isbigendian();
358 swapx(id
->words088_255
+255-88);
360 if ((id
->words088_255
[255-88] & 0x00ff) == 0x00a5)
361 id
->words088_255
[255-88] += sum
<< 8;
364 swapx(id
->words088_255
+255-88);
368 static const char * const commandstrings
[]={
371 "SMART AUTOMATIC ATTRIBUTE SAVE",
372 "SMART IMMEDIATE OFFLINE",
373 "SMART AUTO OFFLINE",
375 "SMART STATUS CHECK",
376 "SMART READ ATTRIBUTE VALUES",
377 "SMART READ ATTRIBUTE THRESHOLDS",
380 "IDENTIFY PACKET DEVICE",
383 "WARNING (UNDEFINED COMMAND -- CONTACT DEVELOPERS AT " PACKAGE_BUGREPORT
")\n"
387 static const char * preg(const ata_register
& r
, char (& buf
)[8])
392 snprintf(buf
, sizeof(buf
), "0x%02x", r
.val());
396 static void print_regs(const char * prefix
, const ata_in_regs
& r
, const char * suffix
= "\n")
399 pout("%s FR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, CMD=%s%s", prefix
,
400 preg(r
.features
, bufs
[0]), preg(r
.sector_count
, bufs
[1]), preg(r
.lba_low
, bufs
[2]),
401 preg(r
.lba_mid
, bufs
[3]), preg(r
.lba_high
, bufs
[4]), preg(r
.device
, bufs
[5]),
402 preg(r
.command
, bufs
[6]), suffix
);
405 static void print_regs(const char * prefix
, const ata_out_regs
& r
, const char * suffix
= "\n")
408 pout("%sERR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, STS=%s%s", prefix
,
409 preg(r
.error
, bufs
[0]), preg(r
.sector_count
, bufs
[1]), preg(r
.lba_low
, bufs
[2]),
410 preg(r
.lba_mid
, bufs
[3]), preg(r
.lba_high
, bufs
[4]), preg(r
.device
, bufs
[5]),
411 preg(r
.status
, bufs
[6]), suffix
);
414 static void prettyprint(const unsigned char *p
, const char *name
){
415 pout("\n===== [%s] DATA START (BASE-16) =====\n", name
);
416 for (int i
=0; i
<512; i
+=16, p
+=16)
417 #define P(n) (' ' <= p[n] && p[n] <= '~' ? (int)p[n] : '.')
418 // print complete line to avoid slow tty output and extra lines in syslog.
419 pout("%03d-%03d: %02x %02x %02x %02x %02x %02x %02x %02x "
420 "%02x %02x %02x %02x %02x %02x %02x %02x"
421 " |%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c|"
424 p
[ 0], p
[ 1], p
[ 2], p
[ 3], p
[ 4], p
[ 5], p
[ 6], p
[ 7],
425 p
[ 8], p
[ 9], p
[10], p
[11], p
[12], p
[13], p
[14], p
[15],
426 P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
427 P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15),
430 pout("===== [%s] DATA END (512 Bytes) =====\n\n", name
);
433 // This function provides the pretty-print reporting for SMART
434 // commands: it implements the various -r "reporting" options for ATA
436 int smartcommandhandler(ata_device
* device
, smart_command_set command
, int select
, char *data
){
437 // TODO: Rework old stuff below
438 // This conditional is true for commands that return data
439 int getsdata
=(command
==PIDENTIFY
||
442 command
==READ_THRESHOLDS
||
443 command
==READ_VALUES
||
444 command
==CHECK_POWER_MODE
);
446 int sendsdata
=(command
==WRITE_LOG
);
448 // If reporting is enabled, say what the command will be before it's executed
450 // conditional is true for commands that use parameters
451 int usesparam
=(command
==READ_LOG
||
452 command
==AUTO_OFFLINE
||
454 command
==IMMEDIATE_OFFLINE
||
457 pout("\nREPORT-IOCTL: Device=%s Command=%s", device
->get_dev_name(), commandstrings
[command
]);
459 pout(" InputParameter=%d\n", select
);
464 if ((getsdata
|| sendsdata
) && !data
){
465 pout("REPORT-IOCTL: Unable to execute command %s : data destination address is NULL\n", commandstrings
[command
]);
469 // The reporting is cleaner, and we will find coding bugs faster, if
470 // the commands that failed clearly return empty (zeroed) data
473 if (command
==CHECK_POWER_MODE
)
476 memset(data
, '\0', 512);
480 // if requested, pretty-print the input data structure
481 if (ata_debugmode
> 1 && sendsdata
)
482 //pout("REPORT-IOCTL: Device=%s Command=%s\n", device->get_dev_name(), commandstrings[command]);
483 prettyprint((unsigned char *)data
, commandstrings
[command
]);
485 // now execute the command
489 // Set common register values
491 default: // SMART commands
492 in
.in_regs
.command
= ATA_SMART_CMD
;
493 in
.in_regs
.lba_high
= SMART_CYL_HI
; in
.in_regs
.lba_mid
= SMART_CYL_LOW
;
495 case IDENTIFY
: case PIDENTIFY
: case CHECK_POWER_MODE
: // Non SMART commands
498 // Set specific values
501 in
.in_regs
.command
= ATA_IDENTIFY_DEVICE
;
502 in
.set_data_in(data
, 1);
505 in
.in_regs
.command
= ATA_IDENTIFY_PACKET_DEVICE
;
506 in
.set_data_in(data
, 1);
508 case CHECK_POWER_MODE
:
509 in
.in_regs
.command
= ATA_CHECK_POWER_MODE
;
510 in
.out_needed
.sector_count
= true; // Powermode returned here
513 in
.in_regs
.features
= ATA_SMART_READ_VALUES
;
514 in
.set_data_in(data
, 1);
516 case READ_THRESHOLDS
:
517 in
.in_regs
.features
= ATA_SMART_READ_THRESHOLDS
;
518 in
.in_regs
.lba_low
= 1; // TODO: CORRECT ???
519 in
.set_data_in(data
, 1);
522 in
.in_regs
.features
= ATA_SMART_READ_LOG_SECTOR
;
523 in
.in_regs
.lba_low
= select
;
524 in
.set_data_in(data
, 1);
527 in
.in_regs
.features
= ATA_SMART_WRITE_LOG_SECTOR
;
528 in
.in_regs
.lba_low
= select
;
529 in
.set_data_out(data
, 1);
532 in
.in_regs
.features
= ATA_SMART_ENABLE
;
533 in
.in_regs
.lba_low
= 1; // TODO: CORRECT ???
536 in
.in_regs
.features
= ATA_SMART_DISABLE
;
537 in
.in_regs
.lba_low
= 1; // TODO: CORRECT ???
540 in
.out_needed
.lba_high
= in
.out_needed
.lba_mid
= true; // Status returned here
542 in
.in_regs
.features
= ATA_SMART_STATUS
;
545 in
.in_regs
.features
= ATA_SMART_AUTO_OFFLINE
;
546 in
.in_regs
.sector_count
= select
; // Caution: Non-DATA command!
549 in
.in_regs
.features
= ATA_SMART_AUTOSAVE
;
550 in
.in_regs
.sector_count
= select
; // Caution: Non-DATA command!
552 case IMMEDIATE_OFFLINE
:
553 in
.in_regs
.features
= ATA_SMART_IMMEDIATE_OFFLINE
;
554 in
.in_regs
.lba_low
= select
;
557 pout("Unrecognized command %d in smartcommandhandler()\n"
558 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
559 device
->set_err(ENOSYS
);
564 print_regs(" Input: ", in
.in_regs
,
565 (in
.direction
==ata_cmd_in::data_in
? " IN\n":
566 in
.direction
==ata_cmd_in::data_out
? " OUT\n":"\n"));
570 int64_t start_usec
= -1;
572 start_usec
= smi()->get_timer_usec();
574 bool ok
= device
->ata_pass_through(in
, out
);
576 if (start_usec
>= 0) {
577 int64_t duration_usec
= smi()->get_timer_usec() - start_usec
;
578 if (duration_usec
>= 500)
579 pout(" [Duration: %.3fs]\n", duration_usec
/ 1000000.0);
582 if (ata_debugmode
&& out
.out_regs
.is_set())
583 print_regs(" Output: ", out
.out_regs
);
585 if (ok
) switch (command
) {
589 case CHECK_POWER_MODE
:
590 if (out
.out_regs
.sector_count
.is_set()) {
591 data
[0] = out
.out_regs
.sector_count
;
595 pout("CHECK POWER MODE: incomplete response, ATA output registers missing\n");
596 device
->set_err(ENOSYS
);
601 // Cyl low and Cyl high unchanged means "Good SMART status"
602 if ((out
.out_regs
.lba_high
== SMART_CYL_HI
) &&
603 (out
.out_regs
.lba_mid
== SMART_CYL_LOW
))
605 // These values mean "Bad SMART status"
606 else if ((out
.out_regs
.lba_high
== SRET_STATUS_HI_EXCEEDED
) &&
607 (out
.out_regs
.lba_mid
== SRET_STATUS_MID_EXCEEDED
))
609 else if (out
.out_regs
.lba_mid
== SMART_CYL_LOW
) {
612 pout("SMART STATUS RETURN: half healthy response sequence, "
613 "probable SAT/USB truncation\n");
614 } else if (out
.out_regs
.lba_mid
== SRET_STATUS_MID_EXCEEDED
) {
617 pout("SMART STATUS RETURN: half unhealthy response sequence, "
618 "probable SAT/USB truncation\n");
620 else if (!out
.out_regs
.is_set()) {
621 device
->set_err(ENOSYS
, "Incomplete response, ATA output registers missing");
625 // We haven't gotten output that makes sense; print out some debugging info
626 pout("SMART Status command failed\n");
627 pout("Please get assistance from %s\n", PACKAGE_HOMEPAGE
);
628 pout("Register values returned from SMART Status command are:\n");
629 print_regs(" ", out
.out_regs
);
630 device
->set_err(ENOSYS
, "Invalid ATA output register values");
637 // If requested, invalidate serial number before any printing is done
638 if ((command
== IDENTIFY
|| command
== PIDENTIFY
) && !retval
&& dont_print_serial_number
)
639 invalidate_serno( reinterpret_cast<ata_identify_device
*>(data
) );
641 // If reporting is enabled, say what output was produced by the command
643 if (device
->get_errno())
644 pout("REPORT-IOCTL: Device=%s Command=%s returned %d errno=%d [%s]\n",
645 device
->get_dev_name(), commandstrings
[command
], retval
,
646 device
->get_errno(), device
->get_errmsg());
648 pout("REPORT-IOCTL: Device=%s Command=%s returned %d\n",
649 device
->get_dev_name(), commandstrings
[command
], retval
);
651 // if requested, pretty-print the output data structure
652 if (ata_debugmode
> 1 && getsdata
) {
653 if (command
==CHECK_POWER_MODE
)
654 pout("Sector Count Register (BASE-16): %02x\n", (unsigned char)(*data
));
656 prettyprint((unsigned char *)data
, commandstrings
[command
]);
663 // Get capacity and sector sizes from IDENTIFY data
664 void ata_get_size_info(const ata_identify_device
* id
, ata_size_info
& sizes
)
666 sizes
.sectors
= sizes
.capacity
= 0;
667 sizes
.log_sector_size
= sizes
.phy_sector_size
= 0;
668 sizes
.log_sector_offset
= 0;
670 // Return if no LBA support
671 if (!(id
->words047_079
[49-47] & 0x0200))
674 // Determine 28-bit LBA capacity
675 unsigned lba28
= (unsigned)id
->words047_079
[61-47] << 16
676 | (unsigned)id
->words047_079
[60-47] ;
678 // Determine 48-bit LBA capacity if supported
680 if ((id
->command_set_2
& 0xc400) == 0x4400)
681 lba48
= (uint64_t)id
->words088_255
[103-88] << 48
682 | (uint64_t)id
->words088_255
[102-88] << 32
683 | (uint64_t)id
->words088_255
[101-88] << 16
684 | (uint64_t)id
->words088_255
[100-88] ;
686 // Return if capacity unknown (ATAPI CD/DVD)
687 if (!(lba28
|| lba48
))
690 // Determine sector sizes
691 sizes
.log_sector_size
= sizes
.phy_sector_size
= 512;
693 unsigned short word106
= id
->words088_255
[106-88];
694 if ((word106
& 0xc000) == 0x4000) {
695 // Long Logical/Physical Sectors (LLS/LPS) ?
696 if (word106
& 0x1000)
697 // Logical sector size is specified in 16-bit words
698 sizes
.log_sector_size
= sizes
.phy_sector_size
=
699 ((id
->words088_255
[118-88] << 16) | id
->words088_255
[117-88]) << 1;
701 if (word106
& 0x2000)
702 // Physical sector size is multiple of logical sector size
703 sizes
.phy_sector_size
<<= (word106
& 0x0f);
705 unsigned short word209
= id
->words088_255
[209-88];
706 if ((word209
& 0xc000) == 0x4000)
707 sizes
.log_sector_offset
= (word209
& 0x3fff) * sizes
.log_sector_size
;
710 // Some early 4KiB LLS disks (Samsung N3U-3) return bogus lba28 value
711 if (lba48
>= lba28
|| (lba48
&& sizes
.log_sector_size
> 512))
712 sizes
.sectors
= lba48
;
714 sizes
.sectors
= lba28
;
716 sizes
.capacity
= sizes
.sectors
* sizes
.log_sector_size
;
719 // This function computes the checksum of a single disk sector (512
720 // bytes). Returns zero if checksum is OK, nonzero if the checksum is
721 // incorrect. The size (512) is correct for all SMART structures.
722 unsigned char checksum(const void * data
)
724 unsigned char sum
= 0;
725 for (int i
= 0; i
< 512; i
++)
726 sum
+= ((const unsigned char *)data
)[i
];
730 // Copies n bytes (or n-1 if n is odd) from in to out, but swaps adjacents
732 static void swapbytes(char * out
, const char * in
, size_t n
)
734 for (size_t i
= 0; i
< n
; i
+= 2) {
740 // Copies in to out, but removes leading and trailing whitespace.
741 static void trim(char * out
, const char * in
)
743 // Find the first non-space character (maybe none).
746 for (i
= 0; in
[i
]; i
++)
747 if (!isspace((int)in
[i
])) {
753 // There are no non-space characters.
758 // Find the last non-space character.
759 for (i
= strlen(in
)-1; i
>= first
&& isspace((int)in
[i
]); i
--)
763 strncpy(out
, in
+first
, last
-first
+1);
764 out
[last
-first
+1] = '\0';
767 // Convenience function for formatting strings from ata_identify_device
768 void ata_format_id_string(char * out
, const unsigned char * in
, int n
)
770 bool must_swap
= true;
772 /* NetBSD kernel delivers IDENTIFY data in host byte order (but all else is LE) */
773 // TODO: Handle NetBSD case in os_netbsd.cpp
775 must_swap
= !must_swap
;
781 strncpy(tmp
, (const char *)in
, n
);
783 swapbytes(tmp
, (const char *)in
, n
);
788 // returns -1 if command fails or the device is in Sleep mode, else
789 // value of Sector Count register. Sector Count result values:
790 // 00h device is in Standby mode.
791 // 80h device is in Idle mode.
792 // FFh device is in Active mode or Idle mode.
794 int ataCheckPowerMode(ata_device
* device
) {
795 unsigned char result
;
797 if ((smartcommandhandler(device
, CHECK_POWER_MODE
, 0, (char *)&result
)))
803 // Issue a no-data ATA command with optional sector count register value
804 bool ata_nodata_command(ata_device
* device
, unsigned char command
,
805 int sector_count
/* = -1 */)
808 in
.in_regs
.command
= command
;
809 if (sector_count
>= 0)
810 in
.in_regs
.sector_count
= sector_count
;
812 return device
->ata_pass_through(in
);
815 // Issue SET FEATURES command with optional sector count register value
816 bool ata_set_features(ata_device
* device
, unsigned char features
,
817 int sector_count
/* = -1 */)
820 in
.in_regs
.command
= ATA_SET_FEATURES
;
821 in
.in_regs
.features
= features
;
822 if (sector_count
>= 0)
823 in
.in_regs
.sector_count
= sector_count
;
825 return device
->ata_pass_through(in
);
828 // Reads current Device Identity info (512 bytes) into buf. Returns 0
829 // if all OK. Returns -1 if no ATA Device identity can be
830 // established. Returns >0 if Device is ATA Packet Device (not SMART
831 // capable). The value of the integer helps identify the type of
832 // Packet device, which is useful so that the user can connect the
833 // formal device number with whatever object is inside their computer.
834 int ata_read_identity(ata_device
* device
, ata_identify_device
* buf
, bool fix_swapped_id
,
835 unsigned char * raw_buf
/* = 0 */)
837 unsigned short *rawshort
=(unsigned short *)buf
;
838 unsigned char *rawbyte
=(unsigned char *)buf
;
840 // See if device responds either to IDENTIFY DEVICE or IDENTIFY
843 if ((smartcommandhandler(device
, IDENTIFY
, 0, (char *)buf
))){
844 if (smartcommandhandler(device
, PIDENTIFY
, 0, (char *)buf
)){
850 if (fix_swapped_id
) {
853 for (i
= 0; i
< sizeof(buf
->serial_no
)-1; i
+= 2)
854 swap2((char *)(buf
->serial_no
+i
));
855 for (i
= 0; i
< sizeof(buf
->fw_rev
)-1; i
+= 2)
856 swap2((char *)(buf
->fw_rev
+i
));
857 for (i
= 0; i
< sizeof(buf
->model
)-1; i
+= 2)
858 swap2((char *)(buf
->model
+i
));
861 // If requested, save raw data before endianness adjustments
863 memcpy(raw_buf
, buf
, sizeof(*buf
));
866 // if machine is big-endian, swap byte order as needed
867 // NetBSD kernel delivers IDENTIFY data in host byte order
868 // TODO: Handle NetBSD case in os_netbsd.cpp
870 // swap various capability words that are needed
873 swap2((char *)(buf
->words047_079
+i
));
874 for (i
=80; i
<=87; i
++)
875 swap2((char *)(rawshort
+i
));
876 for (i
=0; i
<168; i
++)
877 swap2((char *)(buf
->words088_255
+i
));
881 // If there is a checksum there, validate it
882 if ((rawshort
[255] & 0x00ff) == 0x00a5 && checksum(rawbyte
))
883 checksumwarning("Drive Identity Structure");
885 // AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
886 // T13/1699-D Revision 6a (Final Draft), September 6, 2008.
887 // Sections 7.16.7 and 7.17.6:
889 // Word 0 of IDENTIFY DEVICE data:
890 // Bit 15 = 0 : ATA device
892 // Word 0 of IDENTIFY PACKET DEVICE data:
893 // Bits 15:14 = 10b : ATAPI device
894 // Bits 15:14 = 11b : Reserved
895 // Bits 12:8 : Device type (SPC-4, e.g 0x05 = CD/DVD)
897 // CF+ and CompactFlash Specification Revision 4.0, May 24, 2006.
900 // Word 0 of IDENTIFY DEVICE data:
901 // 848Ah = Signature for CompactFlash Storage Card
902 // 044Ah = Alternate value turns on ATA device while preserving all retired bits
903 // 0040h = Alternate value turns on ATA device while zeroing all retired bits
905 // Assume ATA if IDENTIFY DEVICE returns CompactFlash Signature
906 if (!packet
&& rawbyte
[1] == 0x84 && rawbyte
[0] == 0x8a)
909 // If this is a PACKET DEVICE, return device type
910 if (rawbyte
[1] & 0x80)
911 return 1+(rawbyte
[1] & 0x1f);
913 // Not a PACKET DEVICE
917 // Get World Wide Name (WWN) fields.
918 // Return NAA field or -1 if WWN is unsupported.
919 // Table 34 of T13/1699-D Revision 6a (ATA8-ACS), September 6, 2008.
920 // (WWN was introduced in ATA/ATAPI-7 and is mandatory since ATA8-ACS Revision 3b)
921 int ata_get_wwn(const ata_identify_device
* id
, unsigned & oui
, uint64_t & unique_id
)
923 // Don't use word 84 to be compatible with some older ATA-7 disks
924 unsigned short word087
= id
->csf_default
;
925 if ((word087
& 0xc100) != 0x4100)
926 return -1; // word not valid or WWN support bit 8 not set
928 unsigned short word108
= id
->words088_255
[108-88];
929 unsigned short word109
= id
->words088_255
[109-88];
930 unsigned short word110
= id
->words088_255
[110-88];
931 unsigned short word111
= id
->words088_255
[111-88];
933 oui
= ((word108
& 0x0fff) << 12) | (word109
>> 4);
934 unique_id
= ((uint64_t)(word109
& 0xf) << 32)
935 | (unsigned)((word110
<< 16) | word111
);
936 return (word108
>> 12);
939 // Get nominal media rotation rate.
940 // Returns: 0 = not reported, 1 = SSD, >1 = HDD rpm, < 0 = -(Unknown value)
941 int ata_get_rotation_rate(const ata_identify_device
* id
)
943 // Table 37 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
944 // Table A.31 of T13/2161-D (ACS-3) Revision 3b, August 25, 2012
945 unsigned short word217
= id
->words088_255
[217-88];
946 if (word217
== 0x0000 || word217
== 0xffff)
948 else if (word217
== 0x0001)
950 else if (word217
> 0x0400)
953 return -(int)word217
;
956 // returns 1 if SMART supported, 0 if SMART unsupported, -1 if can't tell
957 int ataSmartSupport(const ata_identify_device
* drive
)
959 unsigned short word82
=drive
->command_set_1
;
960 unsigned short word83
=drive
->command_set_2
;
962 // check if words 82/83 contain valid info
963 if ((word83
>>14) == 0x01)
964 // return value of SMART support bit
965 return word82
& 0x0001;
967 // since we can're rely on word 82, we don't know if SMART supported
971 // returns 1 if SMART enabled, 0 if SMART disabled, -1 if can't tell
972 int ataIsSmartEnabled(const ata_identify_device
* drive
)
974 unsigned short word85
=drive
->cfs_enable_1
;
975 unsigned short word87
=drive
->csf_default
;
977 // check if words 85/86/87 contain valid info
978 if ((word87
>>14) == 0x01)
979 // return value of SMART enabled bit
980 return word85
& 0x0001;
982 // Since we can't rely word85, we don't know if SMART is enabled.
987 // Reads SMART attributes into *data
988 int ataReadSmartValues(ata_device
* device
, struct ata_smart_values
*data
){
990 if (smartcommandhandler(device
, READ_VALUES
, 0, (char *)data
)){
996 checksumwarning("SMART Attribute Data Structure");
998 // swap endian order if needed
1001 swap2((char *)&(data
->revnumber
));
1002 swap2((char *)&(data
->total_time_to_complete_off_line
));
1003 swap2((char *)&(data
->smart_capability
));
1004 swapx(&data
->extend_test_completion_time_w
);
1005 for (i
=0; i
<NUMBER_ATA_SMART_ATTRIBUTES
; i
++){
1006 struct ata_smart_attribute
*x
=data
->vendor_attributes
+i
;
1007 swap2((char *)&(x
->flags
));
1015 // This corrects some quantities that are byte reversed in the SMART
1017 static void fixsamsungselftestlog(ata_smart_selftestlog
* data
)
1019 // bytes 508/509 (numbered from 0) swapped (swap of self-test index
1020 // with one byte of reserved.
1021 swap2((char *)&(data
->mostrecenttest
));
1023 // LBA low register (here called 'selftestnumber", containing
1024 // information about the TYPE of the self-test) is byte swapped with
1025 // Self-test execution status byte. These are bytes N, N+1 in the
1027 for (int i
= 0; i
< 21; i
++)
1028 swap2((char *)&(data
->selftest_struct
[i
].selftestnumber
));
1033 // Reads the Self Test Log (log #6)
1034 int ataReadSelfTestLog (ata_device
* device
, ata_smart_selftestlog
* data
,
1035 firmwarebug_defs firmwarebugs
)
1038 // get data from device
1039 if (smartcommandhandler(device
, READ_LOG
, 0x06, (char *)data
)){
1043 // compute its checksum, and issue a warning if needed
1045 checksumwarning("SMART Self-Test Log Structure");
1047 // fix firmware bugs in self-test log
1048 if (firmwarebugs
.is_set(BUG_SAMSUNG
))
1049 fixsamsungselftestlog(data
);
1051 // swap endian order if needed
1054 swap2((char*)&(data
->revnumber
));
1055 for (i
=0; i
<21; i
++){
1056 struct ata_smart_selftestlog_struct
*x
=data
->selftest_struct
+i
;
1057 swap2((char *)&(x
->timestamp
));
1058 swap4((char *)&(x
->lbafirstfailure
));
1065 // Print checksum warning for multi sector log
1066 static void check_multi_sector_sum(const void * data
, unsigned nsectors
, const char * msg
)
1069 for (unsigned i
= 0; i
< nsectors
; i
++) {
1070 if (checksum((const unsigned char *)data
+ i
*512))
1075 checksumwarning(msg
);
1077 checksumwarning(strprintf("%s (%u/%u)", msg
, errs
, nsectors
).c_str());
1081 // Read SMART Extended Self-test Log
1082 bool ataReadExtSelfTestLog(ata_device
* device
, ata_smart_extselftestlog
* log
,
1085 if (!ataReadLogExt(device
, 0x07, 0x00, 0, log
, nsectors
))
1088 check_multi_sector_sum(log
, nsectors
, "SMART Extended Self-test Log Structure");
1090 if (isbigendian()) {
1091 swapx(&log
->log_desc_index
);
1092 for (unsigned i
= 0; i
< nsectors
; i
++) {
1093 for (unsigned j
= 0; j
< 19; j
++)
1094 swapx(&log
->log_descs
[i
].timestamp
);
1101 // Read GP Log page(s)
1102 bool ataReadLogExt(ata_device
* device
, unsigned char logaddr
,
1103 unsigned char features
, unsigned page
,
1104 void * data
, unsigned nsectors
)
1107 in
.in_regs
.command
= ATA_READ_LOG_EXT
;
1108 in
.in_regs
.features
= features
; // log specific
1109 in
.set_data_in_48bit(data
, nsectors
);
1110 in
.in_regs
.lba_low
= logaddr
;
1111 in
.in_regs
.lba_mid_16
= page
;
1113 if (!device
->ata_pass_through(in
)) { // TODO: Debug output
1114 if (nsectors
<= 1) {
1115 pout("ATA_READ_LOG_EXT (addr=0x%02x:0x%02x, page=%u, n=%u) failed: %s\n",
1116 logaddr
, features
, page
, nsectors
, device
->get_errmsg());
1120 // Recurse to retry with single sectors,
1121 // multi-sector reads may not be supported by ioctl.
1122 for (unsigned i
= 0; i
< nsectors
; i
++) {
1123 if (!ataReadLogExt(device
, logaddr
,
1125 (char *)data
+ 512*i
, 1))
1133 // Read SMART Log page(s)
1134 bool ataReadSmartLog(ata_device
* device
, unsigned char logaddr
,
1135 void * data
, unsigned nsectors
)
1138 in
.in_regs
.command
= ATA_SMART_CMD
;
1139 in
.in_regs
.features
= ATA_SMART_READ_LOG_SECTOR
;
1140 in
.set_data_in(data
, nsectors
);
1141 in
.in_regs
.lba_high
= SMART_CYL_HI
;
1142 in
.in_regs
.lba_mid
= SMART_CYL_LOW
;
1143 in
.in_regs
.lba_low
= logaddr
;
1145 if (!device
->ata_pass_through(in
)) { // TODO: Debug output
1146 pout("ATA_SMART_READ_LOG failed: %s\n", device
->get_errmsg());
1154 // Reads the SMART or GPL Log Directory (log #0)
1155 int ataReadLogDirectory(ata_device
* device
, ata_smart_log_directory
* data
, bool gpl
)
1157 if (!gpl
) { // SMART Log directory
1158 if (smartcommandhandler(device
, READ_LOG
, 0x00, (char *)data
))
1161 else { // GP Log directory
1162 if (!ataReadLogExt(device
, 0x00, 0x00, 0, data
, 1))
1166 // swap endian order if needed
1168 swapx(&data
->logversion
);
1174 // Reads the selective self-test log (log #9)
1175 int ataReadSelectiveSelfTestLog(ata_device
* device
, struct ata_selective_self_test_log
*data
){
1177 // get data from device
1178 if (smartcommandhandler(device
, READ_LOG
, 0x09, (char *)data
)){
1182 // compute its checksum, and issue a warning if needed
1184 checksumwarning("SMART Selective Self-Test Log Structure");
1186 // swap endian order if needed
1189 swap2((char *)&(data
->logversion
));
1191 swap8((char *)&(data
->span
[i
].start
));
1192 swap8((char *)&(data
->span
[i
].end
));
1194 swap8((char *)&(data
->currentlba
));
1195 swap2((char *)&(data
->currentspan
));
1196 swap2((char *)&(data
->flags
));
1197 swap2((char *)&(data
->pendingtime
));
1203 // Writes the selective self-test log (log #9)
1204 int ataWriteSelectiveSelfTestLog(ata_device
* device
, ata_selective_selftest_args
& args
,
1205 const ata_smart_values
* sv
, uint64_t num_sectors
,
1206 const ata_selective_selftest_args
* prev_args
)
1208 // Disk size must be known
1210 pout("Disk size is unknown, unable to check selective self-test spans\n");
1215 struct ata_selective_self_test_log sstlog
, *data
=&sstlog
;
1216 unsigned char *ptr
=(unsigned char *)data
;
1217 if (ataReadSelectiveSelfTestLog(device
, data
)) {
1218 pout("SMART Read Selective Self-test Log failed: %s\n", device
->get_errmsg());
1219 pout("Since Read failed, will not attempt to WRITE Selective Self-test Log\n");
1224 data
->logversion
= 1;
1226 // Host is NOT allowed to write selective self-test log if a selective
1227 // self-test is in progress.
1228 if (0<data
->currentspan
&& data
->currentspan
<6 && ((sv
->self_test_exec_status
)>>4)==15) {
1229 pout("SMART Selective or other Self-test in progress\n");
1233 // Set start/end values based on old spans for special -t select,... options
1235 for (i
= 0; i
< args
.num_spans
; i
++) {
1236 int mode
= args
.span
[i
].mode
;
1237 uint64_t start
= args
.span
[i
].start
;
1238 uint64_t end
= args
.span
[i
].end
;
1239 if (mode
== SEL_CONT
) {// redo or next dependig on last test status
1240 switch (sv
->self_test_exec_status
>> 4) {
1241 case 1: case 2: // Aborted/Interrupted by host
1242 pout("Continue Selective Self-Test: Redo last span\n");
1245 default: // All others
1246 pout("Continue Selective Self-Test: Start next span\n");
1252 if ( (mode
== SEL_REDO
|| mode
== SEL_NEXT
)
1253 && prev_args
&& i
< prev_args
->num_spans
1254 && !data
->span
[i
].start
&& !data
->span
[i
].end
) {
1255 // Some drives do not preserve the selective self-test log accross
1256 // power-cyles. If old span on drive is cleared use span provided
1257 // by caller. This is used by smartd (first span only).
1258 data
->span
[i
].start
= prev_args
->span
[i
].start
;
1259 data
->span
[i
].end
= prev_args
->span
[i
].end
;
1263 case SEL_RANGE
: // -t select,START-END
1265 case SEL_REDO
: // -t select,redo... => Redo current
1266 start
= data
->span
[i
].start
;
1267 if (end
> 0) { // -t select,redo+SIZE
1268 end
--; end
+= start
; // [oldstart, oldstart+SIZE)
1270 else // -t select,redo
1271 end
= data
->span
[i
].end
; // [oldstart, oldend]
1273 case SEL_NEXT
: // -t select,next... => Do next
1274 if (data
->span
[i
].end
== 0) {
1275 start
= end
= 0; break; // skip empty spans
1277 start
= data
->span
[i
].end
+ 1;
1278 if (start
>= num_sectors
)
1279 start
= 0; // wrap around
1280 if (end
> 0) { // -t select,next+SIZE
1281 end
--; end
+= start
; // (oldend, oldend+SIZE]
1283 else { // -t select,next
1284 uint64_t oldsize
= data
->span
[i
].end
- data
->span
[i
].start
+ 1;
1285 end
= start
+ oldsize
- 1; // (oldend, oldend+oldsize]
1286 if (end
>= num_sectors
) {
1287 // Adjust size to allow round-robin testing without future size decrease
1288 uint64_t spans
= (num_sectors
+ oldsize
-1) / oldsize
;
1289 uint64_t newsize
= (num_sectors
+ spans
-1) / spans
;
1290 uint64_t newstart
= num_sectors
- newsize
, newend
= num_sectors
- 1;
1291 pout("Span %d changed from %" PRIu64
"-%" PRIu64
" (%" PRIu64
" sectors)\n",
1292 i
, start
, end
, oldsize
);
1293 pout(" to %" PRIu64
"-%" PRIu64
" (%" PRIu64
" sectors) (%" PRIu64
" spans)\n",
1294 newstart
, newend
, newsize
, spans
);
1295 start
= newstart
; end
= newend
;
1300 pout("ataWriteSelectiveSelfTestLog: Invalid mode %d\n", mode
);
1304 if (start
< num_sectors
&& num_sectors
<= end
) {
1305 if (end
!= ~(uint64_t)0) // -t select,N-max
1306 pout("Size of self-test span %d decreased according to disk size\n", i
);
1307 end
= num_sectors
- 1;
1309 if (!(start
<= end
&& end
< num_sectors
)) {
1310 pout("Invalid selective self-test span %d: %" PRIu64
"-%" PRIu64
" (%" PRIu64
" sectors)\n",
1311 i
, start
, end
, num_sectors
);
1314 // Return the actual mode and range to caller.
1315 args
.span
[i
].mode
= mode
;
1316 args
.span
[i
].start
= start
;
1317 args
.span
[i
].end
= end
;
1322 memset(data
->span
+i
, 0, sizeof(struct test_span
));
1324 // Set spans for testing
1325 for (i
= 0; i
< args
.num_spans
; i
++){
1326 data
->span
[i
].start
= args
.span
[i
].start
;
1327 data
->span
[i
].end
= args
.span
[i
].end
;
1330 // host must initialize to zero before initiating selective self-test
1332 data
->currentspan
=0;
1334 // Perform off-line scan after selective test?
1335 if (args
.scan_after_select
== 1)
1337 data
->flags
&= ~SELECTIVE_FLAG_DOSCAN
;
1338 else if (args
.scan_after_select
== 2)
1340 data
->flags
|= SELECTIVE_FLAG_DOSCAN
;
1342 // Must clear active and pending flags before writing
1343 data
->flags
&= ~(SELECTIVE_FLAG_ACTIVE
);
1344 data
->flags
&= ~(SELECTIVE_FLAG_PENDING
);
1346 // modify pending time?
1347 if (args
.pending_time
)
1348 data
->pendingtime
= (unsigned short)(args
.pending_time
-1);
1350 // Set checksum to zero, then compute checksum
1352 unsigned char cksum
=0;
1353 for (i
=0; i
<512; i
++)
1357 data
->checksum
=cksum
;
1359 // swap endian order if needed
1361 swap2((char *)&(data
->logversion
));
1362 for (int b
= 0; b
< 5; b
++) {
1363 swap8((char *)&(data
->span
[b
].start
));
1364 swap8((char *)&(data
->span
[b
].end
));
1366 swap8((char *)&(data
->currentlba
));
1367 swap2((char *)&(data
->currentspan
));
1368 swap2((char *)&(data
->flags
));
1369 swap2((char *)&(data
->pendingtime
));
1372 // write new selective self-test log
1373 if (smartcommandhandler(device
, WRITE_LOG
, 0x09, (char *)data
)){
1374 pout("Write Selective Self-test Log failed: %s\n", device
->get_errmsg());
1381 // This corrects some quantities that are byte reversed in the SMART
1383 static void fixsamsungerrorlog(ata_smart_errorlog
* data
)
1385 // FIXED IN SAMSUNG -25 FIRMWARE???
1386 // Device error count in bytes 452-3
1387 swap2((char *)&(data
->ata_error_count
));
1389 // FIXED IN SAMSUNG -22a FIRMWARE
1390 // step through 5 error log data structures
1391 for (int i
= 0; i
< 5; i
++){
1392 // step through 5 command data structures
1393 for (int j
= 0; j
< 5; j
++)
1394 // Command data structure 4-byte millisec timestamp. These are
1395 // bytes (N+8, N+9, N+10, N+11).
1396 swap4((char *)&(data
->errorlog_struct
[i
].commands
[j
].timestamp
));
1397 // Error data structure two-byte hour life timestamp. These are
1398 // bytes (N+28, N+29).
1399 swap2((char *)&(data
->errorlog_struct
[i
].error_struct
.timestamp
));
1404 // NEEDED ONLY FOR SAMSUNG -22 (some) -23 AND -24?? FIRMWARE
1405 static void fixsamsungerrorlog2(ata_smart_errorlog
* data
)
1407 // Device error count in bytes 452-3
1408 swap2((char *)&(data
->ata_error_count
));
1412 // Reads the Summary SMART Error Log (log #1). The Comprehensive SMART
1413 // Error Log is #2, and the Extended Comprehensive SMART Error log is
1415 int ataReadErrorLog (ata_device
* device
, ata_smart_errorlog
*data
,
1416 firmwarebug_defs firmwarebugs
)
1419 // get data from device
1420 if (smartcommandhandler(device
, READ_LOG
, 0x01, (char *)data
)){
1424 // compute its checksum, and issue a warning if needed
1426 checksumwarning("SMART ATA Error Log Structure");
1428 // Some disks have the byte order reversed in some SMART Summary
1429 // Error log entries
1430 if (firmwarebugs
.is_set(BUG_SAMSUNG
))
1431 fixsamsungerrorlog(data
);
1432 else if (firmwarebugs
.is_set(BUG_SAMSUNG2
))
1433 fixsamsungerrorlog2(data
);
1435 // swap endian order if needed
1439 // Device error count in bytes 452-3
1440 swap2((char *)&(data
->ata_error_count
));
1442 // step through 5 error log data structures
1443 for (i
=0; i
<5; i
++){
1444 // step through 5 command data structures
1446 // Command data structure 4-byte millisec timestamp
1447 swap4((char *)&(data
->errorlog_struct
[i
].commands
[j
].timestamp
));
1448 // Error data structure life timestamp
1449 swap2((char *)&(data
->errorlog_struct
[i
].error_struct
.timestamp
));
1457 // Fix LBA byte ordering of Extended Comprehensive Error Log
1458 // if little endian instead of ATA register ordering is provided
1460 static inline void fix_exterrlog_lba_cmd(T
& cmd
)
1463 cmd
.lba_mid_register_hi
= org
.lba_high_register
;
1464 cmd
.lba_low_register_hi
= org
.lba_mid_register_hi
;
1465 cmd
.lba_high_register
= org
.lba_mid_register
;
1466 cmd
.lba_mid_register
= org
.lba_low_register_hi
;
1469 static void fix_exterrlog_lba(ata_smart_exterrlog
* log
, unsigned nsectors
)
1471 for (unsigned i
= 0; i
< nsectors
; i
++) {
1472 for (int ei
= 0; ei
< 4; ei
++) {
1473 ata_smart_exterrlog_error_log
& entry
= log
[i
].error_logs
[ei
];
1474 fix_exterrlog_lba_cmd(entry
.error
);
1475 for (int ci
= 0; ci
< 5; ci
++)
1476 fix_exterrlog_lba_cmd(entry
.commands
[ci
]);
1481 // Read Extended Comprehensive Error Log
1482 bool ataReadExtErrorLog(ata_device
* device
, ata_smart_exterrlog
* log
,
1483 unsigned page
, unsigned nsectors
, firmwarebug_defs firmwarebugs
)
1485 if (!ataReadLogExt(device
, 0x03, 0x00, page
, log
, nsectors
))
1488 check_multi_sector_sum(log
, nsectors
, "SMART Extended Comprehensive Error Log Structure");
1490 if (isbigendian()) {
1491 swapx(&log
->device_error_count
);
1492 swapx(&log
->error_log_index
);
1493 for (unsigned i
= 0; i
< nsectors
; i
++) {
1494 for (unsigned j
= 0; j
< 4; j
++) {
1495 for (unsigned k
= 0; k
< 5; k
++)
1496 swapx(&log
[i
].error_logs
[j
].commands
[k
].timestamp
);
1497 swapx(&log
[i
].error_logs
[j
].error
.timestamp
);
1502 if (firmwarebugs
.is_set(BUG_XERRORLBA
))
1503 fix_exterrlog_lba(log
, nsectors
);
1509 int ataReadSmartThresholds (ata_device
* device
, struct ata_smart_thresholds_pvt
*data
){
1511 // get data from device
1512 if (smartcommandhandler(device
, READ_THRESHOLDS
, 0, (char *)data
)){
1516 // compute its checksum, and issue a warning if needed
1518 checksumwarning("SMART Attribute Thresholds Structure");
1520 // swap endian order if needed
1522 swap2((char *)&(data
->revnumber
));
1527 int ataEnableSmart (ata_device
* device
){
1528 if (smartcommandhandler(device
, ENABLE
, 0, NULL
)){
1534 int ataDisableSmart (ata_device
* device
){
1536 if (smartcommandhandler(device
, DISABLE
, 0, NULL
)){
1542 int ataEnableAutoSave(ata_device
* device
){
1543 if (smartcommandhandler(device
, AUTOSAVE
, 241, NULL
)){
1549 int ataDisableAutoSave(ata_device
* device
){
1551 if (smartcommandhandler(device
, AUTOSAVE
, 0, NULL
)){
1557 // In *ALL* ATA standards the Enable/Disable AutoOffline command is
1558 // marked "OBSOLETE". It is defined in SFF-8035i Revision 2, and most
1559 // vendors still support it for backwards compatibility. IBM documents
1560 // it for some drives.
1561 int ataEnableAutoOffline (ata_device
* device
){
1563 /* timer hard coded to 4 hours */
1564 if (smartcommandhandler(device
, AUTO_OFFLINE
, 248, NULL
)){
1570 // Another Obsolete Command. See comments directly above, associated
1571 // with the corresponding Enable command.
1572 int ataDisableAutoOffline (ata_device
* device
){
1574 if (smartcommandhandler(device
, AUTO_OFFLINE
, 0, NULL
)){
1580 // If SMART is enabled, supported, and working, then this call is
1581 // guaranteed to return 1, else zero. Note that it should return 1
1582 // regardless of whether the disk's SMART status is 'healthy' or
1584 int ataDoesSmartWork(ata_device
* device
){
1585 int retval
=smartcommandhandler(device
, STATUS
, 0, NULL
);
1593 // This function uses a different interface (DRIVE_TASK) than the
1594 // other commands in this file.
1595 int ataSmartStatus2(ata_device
* device
){
1596 return smartcommandhandler(device
, STATUS_CHECK
, 0, NULL
);
1599 // This is the way to execute ALL tests: offline, short self-test,
1600 // extended self test, with and without captive mode, etc.
1601 // TODO: Move to ataprint.cpp ?
1602 int ataSmartTest(ata_device
* device
, int testtype
, bool force
,
1603 const ata_selective_selftest_args
& selargs
,
1604 const ata_smart_values
* sv
, uint64_t num_sectors
)
1606 char cmdmsg
[128]; const char *type
, *captive
;
1607 int cap
, retval
, select
=0;
1609 // Boolean, if set, says test is captive
1610 cap
=testtype
& CAPTIVE_MASK
;
1612 // Set up strings that describe the type of test
1618 if (testtype
==OFFLINE_FULL_SCAN
)
1620 else if (testtype
==SHORT_SELF_TEST
|| testtype
==SHORT_CAPTIVE_SELF_TEST
)
1621 type
="Short self-test";
1622 else if (testtype
==EXTEND_SELF_TEST
|| testtype
==EXTEND_CAPTIVE_SELF_TEST
)
1623 type
="Extended self-test";
1624 else if (testtype
==CONVEYANCE_SELF_TEST
|| testtype
==CONVEYANCE_CAPTIVE_SELF_TEST
)
1625 type
="Conveyance self-test";
1626 else if ((select
=(testtype
==SELECTIVE_SELF_TEST
|| testtype
==SELECTIVE_CAPTIVE_SELF_TEST
)))
1627 type
="Selective self-test";
1631 // Check whether another test is already running
1632 if (type
&& (sv
->self_test_exec_status
>> 4) == 0xf) {
1634 pout("Can't start self-test without aborting current test (%d0%% remaining),\n"
1635 "%srun 'smartctl -X' to abort test.\n",
1636 sv
->self_test_exec_status
& 0x0f,
1637 (!select
? "add '-t force' option to override, or " : ""));
1644 // If doing a selective self-test, first use WRITE_LOG to write the
1645 // selective self-test log.
1646 ata_selective_selftest_args selargs_io
= selargs
; // filled with info about actual spans
1647 if (select
&& (retval
= ataWriteSelectiveSelfTestLog(device
, selargs_io
, sv
, num_sectors
))) {
1649 pout("Can't start selective self-test without aborting current test: use '-X' option to smartctl.\n");
1653 // Print ouf message that we are sending the command to test
1654 if (testtype
==ABORT_SELF_TEST
)
1655 snprintf(cmdmsg
, sizeof(cmdmsg
), "Abort SMART off-line mode self-test routine");
1657 snprintf(cmdmsg
, sizeof(cmdmsg
), "SMART EXECUTE OFF-LINE IMMEDIATE subcommand 0x%02x", testtype
);
1659 snprintf(cmdmsg
, sizeof(cmdmsg
), "Execute SMART %s routine immediately in %s mode", type
, captive
);
1660 pout("Sending command: \"%s\".\n",cmdmsg
);
1664 pout("SPAN STARTING_LBA ENDING_LBA\n");
1665 for (i
= 0; i
< selargs_io
.num_spans
; i
++)
1666 pout(" %d %20" PRId64
" %20" PRId64
"\n", i
,
1667 selargs_io
.span
[i
].start
,
1668 selargs_io
.span
[i
].end
);
1671 // Now send the command to test
1672 if (smartcommandhandler(device
, IMMEDIATE_OFFLINE
, testtype
, NULL
)) {
1673 if (!(cap
&& device
->get_errno() == EIO
)) {
1674 pout("Command \"%s\" failed: %s\n", cmdmsg
, device
->get_errmsg());
1679 // Since the command succeeded, tell user
1680 if (testtype
==ABORT_SELF_TEST
)
1681 pout("Self-testing aborted!\n");
1683 pout("Drive command \"%s\" successful.\n", cmdmsg
);
1685 pout("Testing has begun%s.\n", (force
? " (previous test aborted)" : ""));
1690 /* Test Time Functions */
1691 int TestTime(const ata_smart_values
*data
, int testtype
)
1694 case OFFLINE_FULL_SCAN
:
1695 return (int) data
->total_time_to_complete_off_line
;
1696 case SHORT_SELF_TEST
:
1697 case SHORT_CAPTIVE_SELF_TEST
:
1698 return (int) data
->short_test_completion_time
;
1699 case EXTEND_SELF_TEST
:
1700 case EXTEND_CAPTIVE_SELF_TEST
:
1701 if (data
->extend_test_completion_time_b
== 0xff
1702 && data
->extend_test_completion_time_w
!= 0x0000
1703 && data
->extend_test_completion_time_w
!= 0xffff)
1704 return data
->extend_test_completion_time_w
; // ATA-8
1706 return data
->extend_test_completion_time_b
;
1707 case CONVEYANCE_SELF_TEST
:
1708 case CONVEYANCE_CAPTIVE_SELF_TEST
:
1709 return (int) data
->conveyance_test_completion_time
;
1715 // This function tells you both about the ATA error log and the
1716 // self-test error log capability (introduced in ATA-5). The bit is
1717 // poorly documented in the ATA/ATAPI standard. Starting with ATA-6,
1718 // SMART error logging is also indicated in bit 0 of DEVICE IDENTIFY
1719 // word 84 and 87. Top two bits must match the pattern 01. BEFORE
1720 // ATA-6 these top two bits still had to match the pattern 01, but the
1721 // remaining bits were reserved (==0).
1722 int isSmartErrorLogCapable (const ata_smart_values
* data
, const ata_identify_device
* identity
)
1724 unsigned short word84
=identity
->command_set_extension
;
1725 unsigned short word87
=identity
->csf_default
;
1726 int isata6
=identity
->major_rev_num
& (0x01<<6);
1727 int isata7
=identity
->major_rev_num
& (0x01<<7);
1729 if ((isata6
|| isata7
) && (word84
>>14) == 0x01 && (word84
& 0x01))
1732 if ((isata6
|| isata7
) && (word87
>>14) == 0x01 && (word87
& 0x01))
1735 // otherwise we'll use the poorly documented capability bit
1736 return data
->errorlog_capability
& 0x01;
1739 // See previous function. If the error log exists then the self-test
1740 // log should (must?) also exist.
1741 int isSmartTestLogCapable (const ata_smart_values
* data
, const ata_identify_device
*identity
)
1743 unsigned short word84
=identity
->command_set_extension
;
1744 unsigned short word87
=identity
->csf_default
;
1745 int isata6
=identity
->major_rev_num
& (0x01<<6);
1746 int isata7
=identity
->major_rev_num
& (0x01<<7);
1748 if ((isata6
|| isata7
) && (word84
>>14) == 0x01 && (word84
& 0x02))
1751 if ((isata6
|| isata7
) && (word87
>>14) == 0x01 && (word87
& 0x02))
1755 // otherwise we'll use the poorly documented capability bit
1756 return data
->errorlog_capability
& 0x01;
1760 int isGeneralPurposeLoggingCapable(const ata_identify_device
*identity
)
1762 unsigned short word84
=identity
->command_set_extension
;
1763 unsigned short word87
=identity
->csf_default
;
1765 // If bit 14 of word 84 is set to one and bit 15 of word 84 is
1766 // cleared to zero, the contents of word 84 contains valid support
1767 // information. If not, support information is not valid in this
1769 if ((word84
>>14) == 0x01)
1770 // If bit 5 of word 84 is set to one, the device supports the
1771 // General Purpose Logging feature set.
1772 return (word84
& (0x01 << 5));
1774 // If bit 14 of word 87 is set to one and bit 15 of word 87 is
1775 // cleared to zero, the contents of words (87:85) contain valid
1776 // information. If not, information is not valid in these words.
1777 if ((word87
>>14) == 0x01)
1778 // If bit 5 of word 87 is set to one, the device supports
1779 // the General Purpose Logging feature set.
1780 return (word87
& (0x01 << 5));
1787 // SMART self-test capability is also indicated in bit 1 of DEVICE
1788 // IDENTIFY word 87 (if top two bits of word 87 match pattern 01).
1789 // However this was only introduced in ATA-6 (but self-test log was in
1791 int isSupportExecuteOfflineImmediate(const ata_smart_values
*data
)
1793 return data
->offline_data_collection_capability
& 0x01;
1796 // Note in the ATA-5 standard, the following bit is listed as "Vendor
1797 // Specific". So it may not be reliable. The only use of this that I
1798 // have found is in IBM drives, where it is well-documented. See for
1799 // example page 170, section 13.32.1.18 of the IBM Travelstar 40GNX
1800 // hard disk drive specifications page 164 Revision 1.1 22 Apr 2002.
1801 int isSupportAutomaticTimer(const ata_smart_values
* data
)
1803 return data
->offline_data_collection_capability
& 0x02;
1805 int isSupportOfflineAbort(const ata_smart_values
*data
)
1807 return data
->offline_data_collection_capability
& 0x04;
1809 int isSupportOfflineSurfaceScan(const ata_smart_values
* data
)
1811 return data
->offline_data_collection_capability
& 0x08;
1813 int isSupportSelfTest (const ata_smart_values
* data
)
1815 return data
->offline_data_collection_capability
& 0x10;
1817 int isSupportConveyanceSelfTest(const ata_smart_values
* data
)
1819 return data
->offline_data_collection_capability
& 0x20;
1821 int isSupportSelectiveSelfTest(const ata_smart_values
* data
)
1823 return data
->offline_data_collection_capability
& 0x40;
1826 // Get attribute state
1827 ata_attr_state
ata_get_attr_state(const ata_smart_attribute
& attr
,
1829 const ata_smart_threshold_entry
* thresholds
,
1830 const ata_vendor_attr_defs
& defs
,
1831 unsigned char * threshval
/* = 0 */)
1834 return ATTRSTATE_NON_EXISTING
;
1836 // Normalized values (current,worst,threshold) not valid
1837 // if specified by '-v' option.
1838 // (Some SSD disks uses these bytes to store raw value).
1839 if (defs
[attr
.id
].flags
& ATTRFLAG_NO_NORMVAL
)
1840 return ATTRSTATE_NO_NORMVAL
;
1842 // Normally threshold is at same index as attribute
1844 if (thresholds
[i
].id
!= attr
.id
) {
1845 // Find threshold id in table
1846 for (i
= 0; thresholds
[i
].id
!= attr
.id
; ) {
1847 if (++i
>= NUMBER_ATA_SMART_ATTRIBUTES
)
1848 // Threshold id missing or thresholds cannot be read
1849 return ATTRSTATE_NO_THRESHOLD
;
1852 unsigned char threshold
= thresholds
[i
].threshold
;
1854 // Return threshold if requested
1856 *threshval
= threshold
;
1858 // Don't report a failed attribute if its threshold is 0.
1859 // ATA-3 (X3T13/2008D Revision 7b) declares 0x00 as the "always passing"
1860 // threshold (Later ATA versions declare all thresholds as "obsolete").
1861 // In practice, threshold value 0 is often used for usage attributes.
1863 return ATTRSTATE_OK
;
1865 // Failed now if current value is below threshold
1866 if (attr
.current
<= threshold
)
1867 return ATTRSTATE_FAILED_NOW
;
1869 // Failed in the past if worst value is below threshold
1870 if (!(defs
[attr
.id
].flags
& ATTRFLAG_NO_WORSTVAL
) && attr
.worst
<= threshold
)
1871 return ATTRSTATE_FAILED_PAST
;
1873 return ATTRSTATE_OK
;
1876 // Get attribute raw value.
1877 uint64_t ata_get_attr_raw_value(const ata_smart_attribute
& attr
,
1878 const ata_vendor_attr_defs
& defs
)
1880 const ata_vendor_attr_defs::entry
& def
= defs
[attr
.id
];
1881 // TODO: Allow Byteorder in DEFAULT entry
1883 // Use default byteorder if not specified
1884 const char * byteorder
= def
.byteorder
;
1886 switch (def
.raw_format
) {
1889 byteorder
= "543210wv"; break;
1892 case RAWFMT_RAW24_DIV_RAW32
:
1893 case RAWFMT_MSEC24_HOUR32
:
1894 byteorder
= "r543210"; break;
1896 byteorder
= "543210"; break;
1900 // Build 64-bit value from selected bytes
1901 uint64_t rawvalue
= 0;
1902 for (int i
= 0; byteorder
[i
]; i
++) {
1904 switch (byteorder
[i
]) {
1905 case '0': b
= attr
.raw
[0]; break;
1906 case '1': b
= attr
.raw
[1]; break;
1907 case '2': b
= attr
.raw
[2]; break;
1908 case '3': b
= attr
.raw
[3]; break;
1909 case '4': b
= attr
.raw
[4]; break;
1910 case '5': b
= attr
.raw
[5]; break;
1911 case 'r': b
= attr
.reserv
; break;
1912 case 'v': b
= attr
.current
; break;
1913 case 'w': b
= attr
.worst
; break;
1914 default : b
= 0; break;
1916 rawvalue
<<= 8; rawvalue
|= b
;
1922 // Helper functions for RAWFMT_TEMPMINMAX
1923 static inline int check_temp_word(unsigned word
)
1926 return 0x11; // >= 0, signed byte or word
1928 return 0x01; // < 0, signed byte
1930 return 0x10; // < 0, signed word
1934 static bool check_temp_range(int t
, unsigned char ut1
, unsigned char ut2
,
1937 int t1
= (signed char)ut1
, t2
= (signed char)ut2
;
1939 int tx
= t1
; t1
= t2
; t2
= tx
;
1942 if ( -60 <= t1
&& t1
<= t
&& t
<= t2
&& t2
<= 120
1943 && !(t1
== -1 && t2
<= 0) ) {
1950 // Format attribute raw value.
1951 std::string
ata_format_attr_raw_value(const ata_smart_attribute
& attr
,
1952 const ata_vendor_attr_defs
& defs
)
1954 // Get 48 bit or 64 bit raw value
1955 uint64_t rawvalue
= ata_get_attr_raw_value(attr
, defs
);
1957 // Split into bytes and words
1958 unsigned char raw
[6];
1959 raw
[0] = (unsigned char) rawvalue
;
1960 raw
[1] = (unsigned char)(rawvalue
>> 8);
1961 raw
[2] = (unsigned char)(rawvalue
>> 16);
1962 raw
[3] = (unsigned char)(rawvalue
>> 24);
1963 raw
[4] = (unsigned char)(rawvalue
>> 32);
1964 raw
[5] = (unsigned char)(rawvalue
>> 40);
1966 word
[0] = raw
[0] | (raw
[1] << 8);
1967 word
[1] = raw
[2] | (raw
[3] << 8);
1968 word
[2] = raw
[4] | (raw
[5] << 8);
1971 ata_attr_raw_format format
= defs
[attr
.id
].raw_format
;
1972 if (format
== RAWFMT_DEFAULT
) {
1973 // Get format from DEFAULT entry
1974 format
= get_default_attr_defs()[attr
.id
].raw_format
;
1975 if (format
== RAWFMT_DEFAULT
)
1976 // Unknown Attribute
1977 format
= RAWFMT_RAW48
;
1984 s
= strprintf("%d %d %d %d %d %d",
1985 raw
[5], raw
[4], raw
[3], raw
[2], raw
[1], raw
[0]);
1989 s
= strprintf("%u %u %u", word
[2], word
[1], word
[0]);
1995 s
= strprintf("%" PRIu64
, rawvalue
);
1999 s
= strprintf("0x%012" PRIx64
, rawvalue
);
2003 s
= strprintf("0x%014" PRIx64
, rawvalue
);
2007 s
= strprintf("0x%016" PRIx64
, rawvalue
);
2010 case RAWFMT_RAW16_OPT_RAW16
:
2011 s
= strprintf("%u", word
[0]);
2012 if (word
[1] || word
[2])
2013 s
+= strprintf(" (%u %u)", word
[2], word
[1]);
2016 case RAWFMT_RAW16_OPT_AVG16
:
2017 s
= strprintf("%u", word
[0]);
2019 s
+= strprintf(" (Average %u)", word
[1]);
2022 case RAWFMT_RAW24_OPT_RAW8
:
2023 s
= strprintf("%u", (unsigned)(rawvalue
& 0x00ffffffULL
));
2024 if (raw
[3] || raw
[4] || raw
[5])
2025 s
+= strprintf(" (%d %d %d)", raw
[5], raw
[4], raw
[3]);
2028 case RAWFMT_RAW24_DIV_RAW24
:
2029 s
= strprintf("%u/%u",
2030 (unsigned)(rawvalue
>> 24), (unsigned)(rawvalue
& 0x00ffffffULL
));
2033 case RAWFMT_RAW24_DIV_RAW32
:
2034 s
= strprintf("%u/%u",
2035 (unsigned)(rawvalue
>> 32), (unsigned)(rawvalue
& 0xffffffffULL
));
2038 case RAWFMT_MIN2HOUR
:
2041 int64_t temp
= word
[0]+(word
[1]<<16);
2042 int64_t tmp1
= temp
/60;
2043 int64_t tmp2
= temp
%60;
2044 s
= strprintf("%" PRIu64
"h+%02" PRIu64
"m", tmp1
, tmp2
);
2046 s
+= strprintf(" (%u)", word
[2]);
2050 case RAWFMT_SEC2HOUR
:
2053 int64_t hours
= rawvalue
/3600;
2054 int64_t minutes
= (rawvalue
-3600*hours
)/60;
2055 int64_t seconds
= rawvalue
%60;
2056 s
= strprintf("%" PRIu64
"h+%02" PRIu64
"m+%02" PRIu64
"s", hours
, minutes
, seconds
);
2060 case RAWFMT_HALFMIN2HOUR
:
2062 // 30-second counter
2063 int64_t hours
= rawvalue
/120;
2064 int64_t minutes
= (rawvalue
-120*hours
)/2;
2065 s
+= strprintf("%" PRIu64
"h+%02" PRIu64
"m", hours
, minutes
);
2069 case RAWFMT_MSEC24_HOUR32
:
2071 // hours + milliseconds
2072 unsigned hours
= (unsigned)(rawvalue
& 0xffffffffULL
);
2073 unsigned milliseconds
= (unsigned)(rawvalue
>> 32);
2074 unsigned seconds
= milliseconds
/ 1000;
2075 s
= strprintf("%uh+%02um+%02u.%03us",
2076 hours
, seconds
/ 60, seconds
% 60, milliseconds
% 1000);
2080 case RAWFMT_TEMPMINMAX
:
2083 // Search for possible min/max values
2084 // [5][4][3][2][1][0] raw[]
2085 // [ 2 ] [ 1 ] [ 0 ] word[]
2086 // xx HH xx LL xx TT (Hitachi/HGST)
2087 // xx LL xx HH xx TT (Kingston SSDs)
2088 // 00 00 HH LL xx TT (Maxtor, Samsung, Seagate, Toshiba)
2089 // 00 00 00 HH LL TT (WDC)
2090 // CC CC HH LL xx TT (WDC, CCCC=over temperature count)
2091 // (xx = 00/ff, possibly sign extension of lower byte)
2093 int t
= (signed char)raw
[0];
2097 int ctw0
= check_temp_word(word
[0]);
2099 if (!word
[1] && ctw0
)
2100 // 00 00 00 00 xx TT
2102 else if (ctw0
&& check_temp_range(t
, raw
[2], raw
[3], lo
, hi
))
2103 // 00 00 HL LH xx TT
2105 else if (!raw
[3] && check_temp_range(t
, raw
[1], raw
[2], lo
, hi
))
2106 // 00 00 00 HL LH TT
2112 if ( (ctw0
& check_temp_word(word
[1]) & check_temp_word(word
[2])) != 0x00
2113 && check_temp_range(t
, raw
[2], raw
[4], lo
, hi
) )
2114 // xx HL xx LH xx TT
2116 else if ( word
[2] < 0x7fff
2117 && check_temp_range(t
, raw
[2], raw
[3], lo
, hi
)
2119 // CC CC HL LH xx TT
2129 s
= strprintf("%d", t
);
2131 case 1: case 2: case 3:
2132 s
= strprintf("%d (Min/Max %d/%d)", t
, lo
, hi
);
2135 s
= strprintf("%d (Min/Max %d/%d #%d)", t
, lo
, hi
, word
[2]);
2138 s
= strprintf("%d (%d %d %d %d %d)", raw
[0], raw
[5], raw
[4], raw
[3], raw
[2], raw
[1]);
2144 case RAWFMT_TEMP10X
:
2145 // ten times temperature in Celsius
2146 s
= strprintf("%d.%d", word
[0]/10, word
[0]%10);
2150 s
= "?"; // Should not happen
2157 // Get attribute name
2158 std::string
ata_get_smart_attr_name(unsigned char id
, const ata_vendor_attr_defs
& defs
,
2161 if (!defs
[id
].name
.empty())
2162 return defs
[id
].name
;
2164 const ata_vendor_attr_defs::entry
& def
= get_default_attr_defs()[id
];
2165 if (def
.name
.empty())
2166 return "Unknown_Attribute";
2167 else if ((def
.flags
& ATTRFLAG_HDD_ONLY
) && rpm
== 1)
2168 return "Unknown_SSD_Attribute";
2169 else if ((def
.flags
& ATTRFLAG_SSD_ONLY
) && rpm
> 1)
2170 return "Unknown_HDD_Attribute";
2176 // Find attribute index for attribute id, -1 if not found.
2177 int ata_find_attr_index(unsigned char id
, const ata_smart_values
& smartval
)
2181 for (int i
= 0; i
< NUMBER_ATA_SMART_ATTRIBUTES
; i
++) {
2182 if (smartval
.vendor_attributes
[i
].id
== id
)
2188 // Return Temperature Attribute raw value selected according to possible
2189 // non-default interpretations. If the Attribute does not exist, return 0
2190 unsigned char ata_return_temperature_value(const ata_smart_values
* data
, const ata_vendor_attr_defs
& defs
)
2192 for (int i
= 0; i
< 4; i
++) {
2193 static const unsigned char ids
[4] = {194, 190, 9, 220};
2194 unsigned char id
= ids
[i
];
2195 const ata_attr_raw_format format
= defs
[id
].raw_format
;
2196 if (!( ((id
== 194 || id
== 190) && format
== RAWFMT_DEFAULT
)
2197 || format
== RAWFMT_TEMPMINMAX
|| format
== RAWFMT_TEMP10X
))
2199 int idx
= ata_find_attr_index(id
, *data
);
2202 uint64_t raw
= ata_get_attr_raw_value(data
->vendor_attributes
[idx
], defs
);
2204 // ignore possible min/max values in high words
2205 if (format
== RAWFMT_TEMP10X
) // -v N,temp10x
2206 temp
= ((unsigned short)raw
+ 5) / 10;
2208 temp
= (unsigned char)raw
;
2209 if (!(0 < temp
&& temp
< 128))
2213 // No valid attribute found
2219 int ataReadSCTStatus(ata_device
* device
, ata_sct_status_response
* sts
)
2221 // read SCT status via SMART log 0xe0
2222 memset(sts
, 0, sizeof(*sts
));
2223 if (smartcommandhandler(device
, READ_LOG
, 0xe0, (char *)sts
)){
2224 pout("Read SCT Status failed: %s\n", device
->get_errmsg());
2228 // swap endian order if needed
2230 swapx(&sts
->format_version
);
2231 swapx(&sts
->sct_version
);
2232 swapx(&sts
->sct_spec
);
2233 swapx(&sts
->ext_status_code
);
2234 swapx(&sts
->action_code
);
2235 swapx(&sts
->function_code
);
2236 swapx(&sts
->over_limit_count
);
2237 swapx(&sts
->under_limit_count
);
2238 swapx(&sts
->smart_status
);
2241 // Check format version
2242 if (!(sts
->format_version
== 2 || sts
->format_version
== 3)) {
2243 pout("Unknown SCT Status format version %u, should be 2 or 3.\n", sts
->format_version
);
2249 // Read SCT Temperature History Table
2250 int ataReadSCTTempHist(ata_device
* device
, ata_sct_temperature_history_table
* tmh
,
2251 ata_sct_status_response
* sts
)
2253 // Initial SCT status must be provided by caller
2255 // Do nothing if other SCT command is executing
2256 if (sts
->ext_status_code
== 0xffff) {
2257 pout("Another SCT command is executing, abort Read Data Table\n"
2258 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2259 sts
->ext_status_code
, sts
->action_code
, sts
->function_code
);
2263 ata_sct_data_table_command cmd
; memset(&cmd
, 0, sizeof(cmd
));
2264 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2265 cmd
.action_code
= 5; // Data table command
2266 cmd
.function_code
= 1; // Read table
2267 cmd
.table_id
= 2; // Temperature History Table
2269 // swap endian order if needed
2270 if (isbigendian()) {
2271 swapx(&cmd
.action_code
);
2272 swapx(&cmd
.function_code
);
2273 swapx(&cmd
.table_id
);
2276 // write command via SMART log page 0xe0
2277 if (smartcommandhandler(device
, WRITE_LOG
, 0xe0, (char *)&cmd
)){
2278 pout("Write SCT Data Table failed: %s\n", device
->get_errmsg());
2282 // read SCT data via SMART log page 0xe1
2283 memset(tmh
, 0, sizeof(*tmh
));
2284 if (smartcommandhandler(device
, READ_LOG
, 0xe1, (char *)tmh
)){
2285 pout("Read SCT Data Table failed: %s\n", device
->get_errmsg());
2289 // re-read and check SCT status
2290 if (ataReadSCTStatus(device
, sts
))
2293 if (!(sts
->ext_status_code
== 0 && sts
->action_code
== 5 && sts
->function_code
== 1)) {
2294 pout("Unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2295 sts
->ext_status_code
, sts
->action_code
, sts
->function_code
);
2299 // swap endian order if needed
2301 swapx(&tmh
->format_version
);
2302 swapx(&tmh
->sampling_period
);
2303 swapx(&tmh
->interval
);
2304 swapx(&tmh
->cb_index
);
2305 swapx(&tmh
->cb_size
);
2310 // Get/Set Write Cache Reordering
2311 int ataGetSetSCTWriteCacheReordering(ata_device
* device
, bool enable
, bool persistent
, bool set
)
2313 // Check initial status
2314 ata_sct_status_response sts
;
2315 if (ataReadSCTStatus(device
, &sts
))
2318 // Do nothing if other SCT command is executing
2319 if (sts
.ext_status_code
== 0xffff) {
2320 pout("Another SCT command is executing, abort Feature Control\n"
2321 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2322 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2326 ata_sct_feature_control_command cmd
; memset(&cmd
, 0, sizeof(cmd
));
2327 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2328 cmd
.action_code
= 4; // Feature Control command
2329 cmd
.function_code
= (set
? 1 : 2); // 1=Set, 2=Get
2330 cmd
.feature_code
= 2; // Enable/Disable Write Cache Reordering
2331 cmd
.state
= (enable
? 1 : 2); // 1 enable, 2 disable
2332 cmd
.option_flags
= (persistent
? 0x01 : 0x00);
2334 // swap endian order if needed
2335 if (isbigendian()) {
2336 swapx(&cmd
.action_code
);
2337 swapx(&cmd
.function_code
);
2338 swapx(&cmd
.feature_code
);
2340 swapx(&cmd
.option_flags
);
2343 // write command via SMART log page 0xe0
2344 // TODO: Debug output
2346 in
.in_regs
.command
= ATA_SMART_CMD
;
2347 in
.in_regs
.lba_high
= SMART_CYL_HI
; in
.in_regs
.lba_mid
= SMART_CYL_LOW
;
2348 in
.in_regs
.features
= ATA_SMART_WRITE_LOG_SECTOR
;
2349 in
.in_regs
.lba_low
= 0xe0;
2350 in
.set_data_out(&cmd
, 1);
2353 // Time limit returned in ATA registers
2354 in
.out_needed
.sector_count
= in
.out_needed
.lba_low
= true;
2357 if (!device
->ata_pass_through(in
, out
)) {
2358 pout("Write SCT (%cet) Feature Control Command failed: %s\n",
2359 (!set
? 'G' : 'S'), device
->get_errmsg());
2362 int state
= out
.out_regs
.sector_count
| (out
.out_regs
.lba_low
<< 8);
2364 // re-read and check SCT status
2365 if (ataReadSCTStatus(device
, &sts
))
2368 if (!(sts
.ext_status_code
== 0 && sts
.action_code
== 4 && sts
.function_code
== (set
? 1 : 2))) {
2369 pout("Unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2370 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2377 // Set SCT Temperature Logging Interval
2378 int ataSetSCTTempInterval(ata_device
* device
, unsigned interval
, bool persistent
)
2380 // Check initial status
2381 ata_sct_status_response sts
;
2382 if (ataReadSCTStatus(device
, &sts
))
2385 // Do nothing if other SCT command is executing
2386 if (sts
.ext_status_code
== 0xffff) {
2387 pout("Another SCT command is executing, abort Feature Control\n"
2388 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2389 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2393 ata_sct_feature_control_command cmd
; memset(&cmd
, 0, sizeof(cmd
));
2394 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2395 cmd
.action_code
= 4; // Feature Control command
2396 cmd
.function_code
= 1; // Set state
2397 cmd
.feature_code
= 3; // Temperature logging interval
2398 cmd
.state
= interval
;
2399 cmd
.option_flags
= (persistent
? 0x01 : 0x00);
2401 // swap endian order if needed
2402 if (isbigendian()) {
2403 swapx(&cmd
.action_code
);
2404 swapx(&cmd
.function_code
);
2405 swapx(&cmd
.feature_code
);
2407 swapx(&cmd
.option_flags
);
2410 // write command via SMART log page 0xe0
2411 if (smartcommandhandler(device
, WRITE_LOG
, 0xe0, (char *)&cmd
)){
2412 pout("Write SCT Feature Control Command failed: %s\n", device
->get_errmsg());
2416 // re-read and check SCT status
2417 if (ataReadSCTStatus(device
, &sts
))
2420 if (!(sts
.ext_status_code
== 0 && sts
.action_code
== 4 && sts
.function_code
== 1)) {
2421 pout("Unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2422 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2428 // Get/Set SCT Error Recovery Control
2429 static int ataGetSetSCTErrorRecoveryControltime(ata_device
* device
, unsigned type
,
2430 bool set
, unsigned short & time_limit
)
2432 // Check initial status
2433 ata_sct_status_response sts
;
2434 if (ataReadSCTStatus(device
, &sts
))
2437 // Do nothing if other SCT command is executing
2438 if (sts
.ext_status_code
== 0xffff) {
2439 pout("Another SCT command is executing, abort Error Recovery Control\n"
2440 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2441 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2445 ata_sct_error_recovery_control_command cmd
; memset(&cmd
, 0, sizeof(cmd
));
2446 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2447 cmd
.action_code
= 3; // Error Recovery Control command
2448 cmd
.function_code
= (set
? 1 : 2); // 1=Set timer, 2=Get timer
2449 cmd
.selection_code
= type
; // 1=Read timer, 2=Write timer
2451 cmd
.time_limit
= time_limit
;
2453 // swap endian order if needed
2454 if (isbigendian()) {
2455 swapx(&cmd
.action_code
);
2456 swapx(&cmd
.function_code
);
2457 swapx(&cmd
.selection_code
);
2458 swapx(&cmd
.time_limit
);
2461 // write command via SMART log page 0xe0
2462 // TODO: Debug output
2464 in
.in_regs
.command
= ATA_SMART_CMD
;
2465 in
.in_regs
.lba_high
= SMART_CYL_HI
; in
.in_regs
.lba_mid
= SMART_CYL_LOW
;
2466 in
.in_regs
.features
= ATA_SMART_WRITE_LOG_SECTOR
;
2467 in
.in_regs
.lba_low
= 0xe0;
2468 in
.set_data_out(&cmd
, 1);
2471 // Time limit returned in ATA registers
2472 in
.out_needed
.sector_count
= in
.out_needed
.lba_low
= true;
2475 if (!device
->ata_pass_through(in
, out
)) {
2476 pout("Write SCT (%cet) Error Recovery Control Command failed: %s\n",
2477 (!set
? 'G' : 'S'), device
->get_errmsg());
2481 // re-read and check SCT status
2482 if (ataReadSCTStatus(device
, &sts
))
2485 if (!(sts
.ext_status_code
== 0 && sts
.action_code
== 3 && sts
.function_code
== (set
? 1 : 2))) {
2486 pout("Unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2487 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2492 // Check whether registers are properly returned by ioctl()
2493 if (!(out
.out_regs
.sector_count
.is_set() && out
.out_regs
.lba_low
.is_set())) {
2494 // TODO: Output register support should be checked within each ata_pass_through()
2495 // implementation before command is issued.
2496 pout("SMART WRITE LOG does not return COUNT and LBA_LOW register\n");
2499 if ( out
.out_regs
.sector_count
== in
.in_regs
.sector_count
2500 && out
.out_regs
.lba_low
== in
.in_regs
.lba_low
) {
2501 // 0xe001 (5734.5s) - this is most likely a broken ATA pass-through implementation
2502 pout("SMART WRITE LOG returns COUNT and LBA_LOW register unchanged\n");
2506 // Return value to caller
2507 time_limit
= out
.out_regs
.sector_count
| (out
.out_regs
.lba_low
<< 8);
2513 // Get SCT Error Recovery Control
2514 int ataGetSCTErrorRecoveryControltime(ata_device
* device
, unsigned type
, unsigned short & time_limit
)
2516 return ataGetSetSCTErrorRecoveryControltime(device
, type
, false/*get*/, time_limit
);
2519 // Set SCT Error Recovery Control
2520 int ataSetSCTErrorRecoveryControltime(ata_device
* device
, unsigned type
, unsigned short time_limit
)
2522 return ataGetSetSCTErrorRecoveryControltime(device
, type
, true/*set*/, time_limit
);
2526 // Print one self-test log entry.
2528 // -1: self-test failed
2529 // 1: extended self-test completed without error
2531 int ataPrintSmartSelfTestEntry(unsigned testnum
, unsigned char test_type
,
2532 unsigned char test_status
,
2533 unsigned short timestamp
,
2534 uint64_t failing_lba
,
2535 bool print_error_only
, bool & print_header
)
2537 // Check status and type for return value
2539 switch (test_status
>> 4) {
2541 if ((test_type
& 0x0f) == 0x02)
2542 retval
= 1; // extended self-test completed without error
2547 retval
= -1; // self-test failed
2551 if (retval
>= 0 && print_error_only
)
2554 std::string msgtest
;
2555 switch (test_type
) {
2556 case 0x00: msgtest
= "Offline"; break;
2557 case 0x01: msgtest
= "Short offline"; break;
2558 case 0x02: msgtest
= "Extended offline"; break;
2559 case 0x03: msgtest
= "Conveyance offline"; break;
2560 case 0x04: msgtest
= "Selective offline"; break;
2561 case 0x7f: msgtest
= "Abort offline test"; break;
2562 case 0x81: msgtest
= "Short captive"; break;
2563 case 0x82: msgtest
= "Extended captive"; break;
2564 case 0x83: msgtest
= "Conveyance captive"; break;
2565 case 0x84: msgtest
= "Selective captive"; break;
2567 if ((0x40 <= test_type
&& test_type
<= 0x7e) || 0x90 <= test_type
)
2568 msgtest
= strprintf("Vendor (0x%02x)", test_type
);
2570 msgtest
= strprintf("Reserved (0x%02x)", test_type
);
2573 std::string msgstat
;
2574 switch (test_status
>> 4) {
2575 case 0x0: msgstat
= "Completed without error"; break;
2576 case 0x1: msgstat
= "Aborted by host"; break;
2577 case 0x2: msgstat
= "Interrupted (host reset)"; break;
2578 case 0x3: msgstat
= "Fatal or unknown error"; break;
2579 case 0x4: msgstat
= "Completed: unknown failure"; break;
2580 case 0x5: msgstat
= "Completed: electrical failure"; break;
2581 case 0x6: msgstat
= "Completed: servo/seek failure"; break;
2582 case 0x7: msgstat
= "Completed: read failure"; break;
2583 case 0x8: msgstat
= "Completed: handling damage??"; break;
2584 case 0xf: msgstat
= "Self-test routine in progress"; break;
2585 default: msgstat
= strprintf("Unknown status (0x%x)", test_status
>> 4);
2588 // Print header once
2590 print_header
= false;
2591 pout("Num Test_Description Status Remaining LifeTime(hours) LBA_of_first_error\n");
2595 if (retval
< 0 && failing_lba
< 0xffffffffffffULL
)
2596 snprintf(msglba
, sizeof(msglba
), "%" PRIu64
, failing_lba
);
2598 msglba
[0] = '-'; msglba
[1] = 0;
2601 pout("#%2u %-19s %-29s %1d0%% %8u %s\n", testnum
,
2602 msgtest
.c_str(), msgstat
.c_str(), test_status
& 0x0f, timestamp
, msglba
);
2607 // Print Smart self-test log, used by smartctl and smartd.
2609 // bottom 8 bits: number of entries found where self-test showed an error
2610 // remaining bits: if nonzero, power on hours of last self-test where error was found
2611 int ataPrintSmartSelfTestlog(const ata_smart_selftestlog
* data
, bool allentries
,
2612 firmwarebug_defs firmwarebugs
)
2615 pout("SMART Self-test log structure revision number %d\n",(int)data
->revnumber
);
2616 if (data
->revnumber
!= 0x0001 && allentries
&& !firmwarebugs
.is_set(BUG_SAMSUNG
))
2617 pout("Warning: ATA Specification requires self-test log structure revision number = 1\n");
2618 if (data
->mostrecenttest
==0){
2620 pout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n");
2624 bool noheaderprinted
= true;
2625 int errcnt
= 0, hours
= 0, igncnt
= 0;
2626 int testno
= 0, ext_ok_testno
= -1;
2629 for (int i
= 20; i
>= 0; i
--) {
2630 // log is a circular buffer
2631 int j
= (i
+data
->mostrecenttest
)%21;
2632 const ata_smart_selftestlog_struct
* log
= data
->selftest_struct
+j
;
2634 if (nonempty(log
, sizeof(*log
))) {
2635 // count entry based on non-empty structures -- needed for
2636 // Seagate only -- other vendors don't have blank entries 'in
2640 // T13/1321D revision 1c: (Data structure Rev #1)
2642 //The failing LBA shall be the LBA of the uncorrectable sector
2643 //that caused the test to fail. If the device encountered more
2644 //than one uncorrectable sector during the test, this field
2645 //shall indicate the LBA of the first uncorrectable sector
2646 //encountered. If the test passed or the test failed for some
2647 //reason other than an uncorrectable sector, the value of this
2648 //field is undefined.
2650 // This is true in ALL ATA-5 specs
2651 uint64_t lba48
= (log
->lbafirstfailure
< 0xffffffff ? log
->lbafirstfailure
: 0xffffffffffffULL
);
2654 int state
= ataPrintSmartSelfTestEntry(testno
,
2655 log
->selftestnumber
, log
->selfteststatus
,
2656 log
->timestamp
, lba48
, !allentries
, noheaderprinted
);
2659 // Self-test showed an error
2660 if (ext_ok_testno
< 0) {
2663 // keep track of time of most recent error
2665 hours
= log
->timestamp
;
2668 // Newer successful extended self-test exits
2671 else if (state
> 0 && ext_ok_testno
< 0) {
2672 // Latest successful extended self-test
2673 ext_ok_testno
= testno
;
2679 pout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
2680 igncnt
, igncnt
+errcnt
, ext_ok_testno
);
2682 if (!allentries
&& !noheaderprinted
)
2685 return ((hours
<< 8) | errcnt
);
2689 /////////////////////////////////////////////////////////////////////////////
2690 // Pseudo-device to parse "smartctl -r ataioctl,2 ..." output and simulate
2691 // an ATA device with same behaviour
2695 class parsed_ata_device
2696 : public /*implements*/ ata_device_with_command_set
2699 parsed_ata_device(smart_interface
* intf
, const char * dev_name
);
2701 virtual ~parsed_ata_device() throw();
2703 virtual bool is_open() const;
2705 virtual bool open();
2707 virtual bool close();
2709 virtual bool ata_identify_is_cached() const;
2712 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2715 // Table of parsed commands, return value, data
2716 struct parsed_ata_command
2718 smart_command_set command
;
2724 enum { max_num_commands
= 32 };
2725 parsed_ata_command m_command_table
[max_num_commands
];
2728 int m_next_replay_command
;
2729 bool m_replay_out_of_sync
;
2730 bool m_ata_identify_is_cached
;
2733 static const char * nextline(const char * s
, int & lineno
)
2735 for (s
+= strcspn(s
, "\r\n"); *s
== '\r' || *s
== '\n'; s
++) {
2736 if (*s
== '\r' && s
[1] == '\n')
2743 static int name2command(const char * s
)
2745 for (int i
= 0; i
< (int)(sizeof(commandstrings
)/sizeof(commandstrings
[0])); i
++) {
2746 if (!strcmp(s
, commandstrings
[i
]))
2752 static bool matchcpy(char * dest
, size_t size
, const char * src
, const regmatch_t
& srcmatch
)
2754 if (srcmatch
.rm_so
< 0)
2756 size_t n
= srcmatch
.rm_eo
- srcmatch
.rm_so
;
2759 memcpy(dest
, src
+ srcmatch
.rm_so
, n
);
2764 static inline int matchtoi(const char * src
, const regmatch_t
& srcmatch
, int defval
)
2766 if (srcmatch
.rm_so
< 0)
2768 return atoi(src
+ srcmatch
.rm_so
);
2771 parsed_ata_device::parsed_ata_device(smart_interface
* intf
, const char * dev_name
)
2772 : smart_device(intf
, dev_name
, "ata", ""),
2774 m_next_replay_command(0),
2775 m_replay_out_of_sync(false),
2776 m_ata_identify_is_cached(false)
2778 memset(m_command_table
, 0, sizeof(m_command_table
));
2781 parsed_ata_device::~parsed_ata_device() throw()
2786 bool parsed_ata_device::is_open() const
2788 return (m_num_commands
> 0);
2791 // Parse stdin and build command table
2792 bool parsed_ata_device::open()
2794 const char * pathname
= get_dev_name();
2795 if (strcmp(pathname
, "-"))
2796 return set_err(EINVAL
);
2797 pathname
= "<stdin>";
2799 char buffer
[64*1024];
2801 while (size
< (int)sizeof(buffer
)) {
2802 int nr
= fread(buffer
, 1, sizeof(buffer
), stdin
);
2808 return set_err(ENOENT
, "%s: Unexpected EOF", pathname
);
2809 if (size
>= (int)sizeof(buffer
))
2810 return set_err(EIO
, "%s: Buffer overflow", pathname
);
2813 // Regex to match output from "-r ataioctl,2"
2814 static const char pattern
[] = "^"
2816 "REPORT-IOCTL: DeviceF?D?=[^ ]+ Command=([A-Z ]*[A-Z])" // (2)
2818 "( InputParameter=([0-9]+))?" // (4 (5))
2820 "( returned (-?[0-9]+)( errno=([0-9]+)[^\r\n]*)?)" // (6 (7) (8 (9)))
2822 "[\r\n]" // EOL match necessary to match optional parts above
2824 "===== \\[([A-Z ]*[A-Z])\\] DATA START " // (10)
2826 " *(En|Dis)abled status cached by OS, " // (11)
2830 const regular_expression
regex(pattern
, REG_EXTENDED
);
2833 const char * errmsg
= 0;
2834 int i
= -1, state
= 0, lineno
= 1;
2835 for (const char * line
= buffer
; *line
; line
= nextline(line
, lineno
)) {
2837 if (!(line
[0] == 'R' || line
[0] == '=' || line
[0] == ' '))
2839 const int nmatch
= 1+11;
2840 regmatch_t match
[nmatch
];
2841 if (!regex
.execute(line
, nmatch
, match
))
2845 if (matchcpy(cmdname
, sizeof(cmdname
), line
, match
[2])) { // "REPORT-IOCTL:... Command=%s ..."
2846 int nc
= name2command(cmdname
);
2848 errmsg
= "Unknown ATA command name"; break;
2850 if (match
[7].rm_so
< 0) { // "returned %d"
2852 if (!(state
== 0 || state
== 2)) {
2853 errmsg
= "Missing REPORT-IOCTL result"; break;
2855 if (++i
>= max_num_commands
) {
2856 errmsg
= "Too many ATA commands"; break;
2858 m_command_table
[i
].command
= (smart_command_set
)nc
;
2859 m_command_table
[i
].select
= matchtoi(line
, match
[5], 0); // "InputParameter=%d"
2864 if (!(state
== 1 && (int)m_command_table
[i
].command
== nc
)) {
2865 errmsg
= "Missing REPORT-IOCTL start"; break;
2867 m_command_table
[i
].retval
= matchtoi(line
, match
[7], -1); // "returned %d"
2868 m_command_table
[i
].errval
= matchtoi(line
, match
[9], 0); // "errno=%d"
2872 else if (matchcpy(cmdname
, sizeof(cmdname
), line
, match
[10])) { // "===== [%s] DATA START "
2873 // Start of sector hexdump
2874 int nc
= name2command(cmdname
);
2875 if (!(state
== (nc
== WRITE_LOG
? 1 : 2) && (int)m_command_table
[i
].command
== nc
)) {
2876 errmsg
= "Unexpected DATA START"; break;
2878 line
= nextline(line
, lineno
);
2879 char * data
= (char *)malloc(512);
2881 for (j
= 0; j
< 32; j
++) {
2883 unsigned u1
, u2
; int n1
= -1;
2884 if (!(sscanf(line
, "%3u-%3u: "
2885 "%2x %2x %2x %2x %2x %2x %2x %2x "
2886 "%2x %2x %2x %2x %2x %2x %2x %2x%n",
2888 b
+ 0, b
+ 1, b
+ 2, b
+ 3, b
+ 4, b
+ 5, b
+ 6, b
+ 7,
2889 b
+ 8, b
+ 9, b
+10, b
+11, b
+12, b
+13, b
+14, b
+15, &n1
) == 18
2890 && n1
>= 56 && u1
== j
*16 && u2
== j
*16+15))
2892 for (unsigned k
= 0; k
< 16; k
++)
2893 data
[j
*16+k
] = b
[k
];
2894 line
= nextline(line
, lineno
);
2898 errmsg
= "Incomplete sector hex dump"; break;
2900 m_command_table
[i
].data
= data
;
2901 if (nc
!= WRITE_LOG
)
2904 else if (match
[11].rm_so
> 0) { // "(En|Dis)abled status cached by OS"
2905 m_ata_identify_is_cached
= true;
2909 if (!(state
== 0 || state
== 2))
2910 errmsg
= "Missing REPORT-IOCTL result";
2912 if (!errmsg
&& i
< 0)
2913 errmsg
= "No information found";
2915 m_num_commands
= i
+1;
2916 m_next_replay_command
= 0;
2917 m_replay_out_of_sync
= false;
2921 return set_err(EIO
, "%s(%d): Syntax error: %s", pathname
, lineno
, errmsg
);
2926 // Report warnings and free command table
2927 bool parsed_ata_device::close()
2929 if (m_replay_out_of_sync
)
2930 pout("REPLAY-IOCTL: Warning: commands replayed out of sync\n");
2931 else if (m_next_replay_command
!= 0)
2932 pout("REPLAY-IOCTL: Warning: %d command(s) not replayed\n", m_num_commands
-m_next_replay_command
);
2934 for (int i
= 0; i
< m_num_commands
; i
++) {
2935 if (m_command_table
[i
].data
) {
2936 free(m_command_table
[i
].data
); m_command_table
[i
].data
= 0;
2940 m_next_replay_command
= 0;
2941 m_replay_out_of_sync
= false;
2946 bool parsed_ata_device::ata_identify_is_cached() const
2948 return m_ata_identify_is_cached
;
2952 // Simulate ATA command from command table
2953 int parsed_ata_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2955 // Find command, try round-robin if out of sync
2956 int i
= m_next_replay_command
;
2957 for (int j
= 0; ; j
++) {
2958 if (j
>= m_num_commands
) {
2959 pout("REPLAY-IOCTL: Warning: Command not found\n");
2963 if (m_command_table
[i
].command
== command
&& m_command_table
[i
].select
== select
)
2965 if (!m_replay_out_of_sync
) {
2966 m_replay_out_of_sync
= true;
2967 pout("REPLAY-IOCTL: Warning: Command #%d is out of sync\n", i
+1);
2969 if (++i
>= m_num_commands
)
2972 m_next_replay_command
= i
;
2973 if (++m_next_replay_command
>= m_num_commands
)
2974 m_next_replay_command
= 0;
2976 // Return command data
2981 case READ_THRESHOLDS
:
2983 if (m_command_table
[i
].data
)
2984 memcpy(data
, m_command_table
[i
].data
, 512);
2987 if (!(m_command_table
[i
].data
&& !memcmp(data
, m_command_table
[i
].data
, 512)))
2988 pout("REPLAY-IOCTL: Warning: WRITE LOG data does not match\n");
2990 case CHECK_POWER_MODE
:
2991 data
[0] = (char)0xff;
2996 if (m_command_table
[i
].errval
)
2997 errno
= m_command_table
[i
].errval
;
2998 return m_command_table
[i
].retval
;
3003 ata_device
* get_parsed_ata_device(smart_interface
* intf
, const char * dev_name
)
3005 return new parsed_ata_device(intf
, dev_name
);