4 * Home page of code is: http://smartmontools.sourceforge.net
6 * Copyright (C) 2002-9 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2008-9 Christian Franke <smartmontools-support@lists.sourceforge.net>
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, write to the Free
18 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 * This code was originally developed as a Senior Thesis by Michael Cornwell
21 * at the Concurrent Systems Laboratory (now part of the Storage Systems
22 * Research Center), Jack Baskin School of Engineering, University of
23 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
38 #include "dev_ata_cmd_set.h" // for parsed_ata_device
40 const char * atacmds_cpp_cvsid
= "$Id: atacmds.cpp 2983 2009-11-14 21:41:41Z chrfranke $"
43 // for passing global control variables
44 extern smartmonctrl
*con
;
46 #define SMART_CYL_LOW 0x4F
47 #define SMART_CYL_HI 0xC2
49 // SMART RETURN STATUS yields SMART_CYL_HI,SMART_CYL_LOW to indicate drive
50 // is healthy and SRET_STATUS_HI_EXCEEDED,SRET_STATUS_MID_EXCEEDED to
51 // indicate that a threshhold exceeded condition has been detected.
52 // Those values (byte pairs) are placed in ATA register "LBA 23:8".
53 #define SRET_STATUS_HI_EXCEEDED 0x2C
54 #define SRET_STATUS_MID_EXCEEDED 0xF4
56 // These Drive Identity tables are taken from hdparm 5.2, and are also
57 // given in the ATA/ATAPI specs for the IDENTIFY DEVICE command. Note
58 // that SMART was first added into the ATA/ATAPI-3 Standard with
59 // Revision 3 of the document, July 25, 1995. Look at the "Document
60 // Status" revision commands at the beginning of
61 // http://www.t13.org/project/d2008r6.pdf to see this.
62 #define NOVAL_0 0x0000
63 #define NOVAL_1 0xffff
64 /* word 81: minor version number */
65 #define MINOR_MAX 0x22
66 static const char * const minor_str
[] = { /* word 81 value: */
67 "Device does not report version", /* 0x0000 */
68 "ATA-1 X3T9.2 781D prior to revision 4", /* 0x0001 */
69 "ATA-1 published, ANSI X3.221-1994", /* 0x0002 */
70 "ATA-1 X3T9.2 781D revision 4", /* 0x0003 */
71 "ATA-2 published, ANSI X3.279-1996", /* 0x0004 */
72 "ATA-2 X3T10 948D prior to revision 2k", /* 0x0005 */
73 "ATA-3 X3T10 2008D revision 1", /* 0x0006 */ /* SMART NOT INCLUDED */
74 "ATA-2 X3T10 948D revision 2k", /* 0x0007 */
75 "ATA-3 X3T10 2008D revision 0", /* 0x0008 */
76 "ATA-2 X3T10 948D revision 3", /* 0x0009 */
77 "ATA-3 published, ANSI X3.298-199x", /* 0x000a */
78 "ATA-3 X3T10 2008D revision 6", /* 0x000b */ /* 1st VERSION WITH SMART */
79 "ATA-3 X3T13 2008D revision 7 and 7a", /* 0x000c */
80 "ATA/ATAPI-4 X3T13 1153D revision 6", /* 0x000d */
81 "ATA/ATAPI-4 T13 1153D revision 13", /* 0x000e */
82 "ATA/ATAPI-4 X3T13 1153D revision 7", /* 0x000f */
83 "ATA/ATAPI-4 T13 1153D revision 18", /* 0x0010 */
84 "ATA/ATAPI-4 T13 1153D revision 15", /* 0x0011 */
85 "ATA/ATAPI-4 published, ANSI NCITS 317-1998", /* 0x0012 */
86 "ATA/ATAPI-5 T13 1321D revision 3", /* 0x0013 */
87 "ATA/ATAPI-4 T13 1153D revision 14", /* 0x0014 */
88 "ATA/ATAPI-5 T13 1321D revision 1", /* 0x0015 */
89 "ATA/ATAPI-5 published, ANSI NCITS 340-2000", /* 0x0016 */
90 "ATA/ATAPI-4 T13 1153D revision 17", /* 0x0017 */
91 "ATA/ATAPI-6 T13 1410D revision 0", /* 0x0018 */
92 "ATA/ATAPI-6 T13 1410D revision 3a", /* 0x0019 */
93 "ATA/ATAPI-7 T13 1532D revision 1", /* 0x001a */
94 "ATA/ATAPI-6 T13 1410D revision 2", /* 0x001b */
95 "ATA/ATAPI-6 T13 1410D revision 1", /* 0x001c */
96 "ATA/ATAPI-7 published, ANSI INCITS 397-2005",/* 0x001d */
97 "ATA/ATAPI-7 T13 1532D revision 0", /* 0x001e */
98 "reserved", /* 0x001f */
99 "reserved", /* 0x0020 */
100 "ATA/ATAPI-7 T13 1532D revision 4a", /* 0x0021 */
101 "ATA/ATAPI-6 published, ANSI INCITS 361-2002" /* 0x0022 */
104 // NOTE ATA/ATAPI-4 REV 4 was the LAST revision where the device
105 // attribute structures were NOT completely vendor specific. So any
106 // disk that is ATA/ATAPI-4 or above can not be trusted to show the
107 // vendor values in sensible format.
109 // Negative values below are because it doesn't support SMART
110 static const int actual_ver
[] = {
112 0, /* 0x0000 WARNING: */
113 1, /* 0x0001 WARNING: */
114 1, /* 0x0002 WARNING: */
115 1, /* 0x0003 WARNING: */
116 2, /* 0x0004 WARNING: This array */
117 2, /* 0x0005 WARNING: corresponds */
118 -3, /*<== */ /* 0x0006 WARNING: *exactly* */
119 2, /* 0x0007 WARNING: to the ATA/ */
120 -3, /*<== */ /* 0x0008 WARNING: ATAPI version */
121 2, /* 0x0009 WARNING: listed in */
122 3, /* 0x000a WARNING: the */
123 3, /* 0x000b WARNING: minor_str */
124 3, /* 0x000c WARNING: array */
125 4, /* 0x000d WARNING: above. */
126 4, /* 0x000e WARNING: */
127 4, /* 0x000f WARNING: If you change */
128 4, /* 0x0010 WARNING: that one, */
129 4, /* 0x0011 WARNING: change this one */
130 4, /* 0x0012 WARNING: too!!! */
131 5, /* 0x0013 WARNING: */
132 4, /* 0x0014 WARNING: */
133 5, /* 0x0015 WARNING: */
134 5, /* 0x0016 WARNING: */
135 4, /* 0x0017 WARNING: */
136 6, /* 0x0018 WARNING: */
137 6, /* 0x0019 WARNING: */
138 7, /* 0x001a WARNING: */
139 6, /* 0x001b WARNING: */
140 6, /* 0x001c WARNING: */
141 7, /* 0x001d WARNING: */
142 7, /* 0x001e WARNING: */
143 0, /* 0x001f WARNING: */
144 0, /* 0x0020 WARNING: */
145 7, /* 0x0021 WARNING: */
146 6 /* 0x0022 WARNING: */
149 // Get ID and increase flag of current pending or offline
150 // uncorrectable attribute.
151 unsigned char get_unc_attr_id(bool offline
, const ata_vendor_attr_defs
& defs
,
154 unsigned char id
= (!offline
? 197 : 198);
155 increase
= !!(defs
[id
].flags
& ATTRFLAG_INCREASING
);
159 #if 0 // TODO: never used
160 // This are the meanings of the Self-test failure checkpoint byte.
161 // This is in the self-test log at offset 4 bytes into the self-test
162 // descriptor and in the SMART READ DATA structure at byte offset
163 // 371. These codes are not well documented. The meanings returned by
164 // this routine are used (at least) by Maxtor and IBM. Returns NULL if
165 // not recognized. Currently the maximum length is 15 bytes.
166 const char *SelfTestFailureCodeName(unsigned char which
){
172 return "Servo_Basic";
174 return "Servo_Random";
176 return "G-list_Scan";
178 return "Handling_Damage";
188 // Table of raw print format names
189 struct format_name_entry
192 ata_attr_raw_format format
;
195 const format_name_entry format_names
[] = {
196 {"raw8" , RAWFMT_RAW8
},
197 {"raw16" , RAWFMT_RAW16
},
198 {"raw48" , RAWFMT_RAW48
},
199 {"hex48" , RAWFMT_HEX48
},
200 {"raw64" , RAWFMT_RAW64
},
201 {"hex64" , RAWFMT_HEX64
},
202 {"raw16(raw16)" , RAWFMT_RAW16_OPT_RAW16
},
203 {"raw16(avg16)" , RAWFMT_RAW16_OPT_AVG16
},
204 {"raw24/raw24" , RAWFMT_RAW24_RAW24
},
205 {"sec2hour" , RAWFMT_SEC2HOUR
},
206 {"min2hour" , RAWFMT_MIN2HOUR
},
207 {"halfmin2hour" , RAWFMT_HALFMIN2HOUR
},
208 {"tempminmax" , RAWFMT_TEMPMINMAX
},
209 {"temp10x" , RAWFMT_TEMP10X
},
212 const unsigned num_format_names
= sizeof(format_names
)/sizeof(format_names
[0]);
214 // Table to map old to new '-v' option arguments
215 const char * map_old_vendor_opts
[][2] = {
216 { "9,halfminutes" , "9,halfmin2hour,Power_On_Half_Minutes"},
217 { "9,minutes" , "9,min2hour,Power_On_Minutes"},
218 { "9,seconds" , "9,sec2hour,Power_On_Seconds"},
219 { "9,temp" , "9,tempminmax,Temperature_Celsius"},
220 {"192,emergencyretractcyclect" , "192,raw48,Emerg_Retract_Cycle_Ct"},
221 {"193,loadunload" , "193,raw24/raw24"},
222 {"194,10xCelsius" , "194,temp10x,Temperature_Celsius_x10"},
223 {"194,unknown" , "194,raw48,Unknown_Attribute"},
224 {"197,increasing" , "197,raw48+,Total_Pending_Sectors"}, // '+' sets flag
225 {"198,offlinescanuncsectorct" , "198,raw48,Offline_Scan_UNC_SectCt"},
226 {"198,increasing" , "198,raw48+,Total_Offl_Uncorrectabl"}, // '+' sets flag
227 {"200,writeerrorcount" , "200,raw48,Write_Error_Count"},
228 {"201,detectedtacount" , "201,raw48,Detected_TA_Count"},
229 {"220,temp" , "220,raw48,Temperature_Celsius"},
232 const unsigned num_old_vendor_opts
= sizeof(map_old_vendor_opts
)/sizeof(map_old_vendor_opts
[0]);
234 // Parse vendor attribute display def (-v option).
235 // Return false on error.
236 bool parse_attribute_def(const char * opt
, ata_vendor_attr_defs
& defs
,
237 ata_vendor_def_prior priority
)
239 // Map old -> new options
241 for (i
= 0; i
< num_old_vendor_opts
; i
++) {
242 if (!strcmp(opt
, map_old_vendor_opts
[i
][0])) {
243 opt
= map_old_vendor_opts
[i
][1];
249 int len
= strlen(opt
);
250 int id
= 0, n1
= -1, n2
= -1;
251 char fmtname
[32+1], attrname
[32+1];
254 if (!( sscanf(opt
, "N,%32[^,]%n,%32[^,]%n", fmtname
, &n1
, attrname
, &n2
) >= 1
255 && (n1
== len
|| n2
== len
)))
259 // "id,format[+][,name]"
260 if (!( sscanf(opt
, "%d,%32[^,]%n,%32[^,]%n", &id
, fmtname
, &n1
, attrname
, &n2
) >= 2
261 && 1 <= id
&& id
<= 255 && (n1
== len
|| n2
== len
)))
268 // For "-v 19[78],increasing" above
269 if (fmtname
[strlen(fmtname
)-1] == '+') {
270 fmtname
[strlen(fmtname
)-1] = 0;
271 flags
= ATTRFLAG_INCREASING
;
276 if (i
>= num_format_names
)
277 return false; // Not found
278 if (!strcmp(fmtname
, format_names
[i
].name
))
281 ata_attr_raw_format format
= format_names
[i
].format
;
283 // 64-bit formats use the normalized value bytes.
284 if (format
== RAWFMT_RAW64
|| format
== RAWFMT_HEX64
)
285 flags
|= ATTRFLAG_NO_NORMVAL
;
288 // "N,format" -> set format for all entries
289 for (i
= 0; i
< MAX_ATTRIBUTE_NUM
; i
++) {
290 if (defs
[i
].priority
>= priority
)
293 defs
[i
].name
= attrname
;
294 defs
[i
].priority
= priority
;
295 defs
[i
].raw_format
= format
;
296 defs
[i
].flags
= flags
;
299 else if (defs
[id
].priority
<= priority
) {
300 // "id,format[,name]"
302 defs
[id
].name
= attrname
;
303 defs
[id
].raw_format
= format
;
304 defs
[id
].priority
= priority
;
305 defs
[id
].flags
= flags
;
312 // Return a multiline string containing a list of valid arguments for
313 // parse_attribute_def(). The strings are preceeded by tabs and followed
314 // (except for the last) by newlines.
315 std::string
create_vendor_attribute_arg_list()
319 for (i
= 0; i
< num_format_names
; i
++)
320 s
+= strprintf("%s\tN,%s[,ATTR_NAME]",
321 (i
>0 ? "\n" : ""), format_names
[i
].name
);
322 for (i
= 0; i
< num_old_vendor_opts
; i
++)
323 s
+= strprintf("\n\t%s", map_old_vendor_opts
[i
][0]);
327 // swap two bytes. Point to low address
328 void swap2(char *location
){
330 *location
=*(location
+1);
335 // swap four bytes. Point to low address
336 void swap4(char *location
){
338 *location
=*(location
+3);
344 // swap eight bytes. Points to low address
345 void swap8(char *location
){
347 *location
=*(location
+7);
350 *(location
+1)=*(location
+6);
356 // Invalidate serial number and adjust checksum in IDENTIFY data
357 static void invalidate_serno(ata_identify_device
* id
){
358 unsigned char sum
= 0;
359 for (unsigned i
= 0; i
< sizeof(id
->serial_no
); i
++) {
360 sum
+= id
->serial_no
[i
]; sum
-= id
->serial_no
[i
] = 'X';
363 bool must_swap
= !!isbigendian();
365 swapx(id
->words088_255
+255-88);
367 if ((id
->words088_255
[255-88] & 0x00ff) == 0x00a5)
368 id
->words088_255
[255-88] += sum
<< 8;
371 swapx(id
->words088_255
+255-88);
375 static const char * const commandstrings
[]={
378 "SMART AUTOMATIC ATTRIBUTE SAVE",
379 "SMART IMMEDIATE OFFLINE",
380 "SMART AUTO OFFLINE",
382 "SMART STATUS CHECK",
383 "SMART READ ATTRIBUTE VALUES",
384 "SMART READ ATTRIBUTE THRESHOLDS",
387 "IDENTIFY PACKET DEVICE",
390 "WARNING (UNDEFINED COMMAND -- CONTACT DEVELOPERS AT " PACKAGE_BUGREPORT
")\n"
394 static const char * preg(const ata_register
& r
, char * buf
)
399 sprintf(buf
, "0x%02x", r
.val()); return buf
;
402 void print_regs(const char * prefix
, const ata_in_regs
& r
, const char * suffix
= "\n")
404 char bufs
[7][4+1+13];
405 pout("%s FR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, CMD=%s%s", prefix
,
406 preg(r
.features
, bufs
[0]), preg(r
.sector_count
, bufs
[1]), preg(r
.lba_low
, bufs
[2]),
407 preg(r
.lba_mid
, bufs
[3]), preg(r
.lba_high
, bufs
[4]), preg(r
.device
, bufs
[5]),
408 preg(r
.command
, bufs
[6]), suffix
);
411 void print_regs(const char * prefix
, const ata_out_regs
& r
, const char * suffix
= "\n")
413 char bufs
[7][4+1+13];
414 pout("%sERR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, STS=%s%s", prefix
,
415 preg(r
.error
, bufs
[0]), preg(r
.sector_count
, bufs
[1]), preg(r
.lba_low
, bufs
[2]),
416 preg(r
.lba_mid
, bufs
[3]), preg(r
.lba_high
, bufs
[4]), preg(r
.device
, bufs
[5]),
417 preg(r
.status
, bufs
[6]), suffix
);
420 static void prettyprint(const unsigned char *p
, const char *name
){
421 pout("\n===== [%s] DATA START (BASE-16) =====\n", name
);
422 for (int i
=0; i
<512; i
+=16, p
+=16)
423 // print complete line to avoid slow tty output and extra lines in syslog.
424 pout("%03d-%03d: %02x %02x %02x %02x %02x %02x %02x %02x "
425 "%02x %02x %02x %02x %02x %02x %02x %02x\n",
427 p
[ 0], p
[ 1], p
[ 2], p
[ 3], p
[ 4], p
[ 5], p
[ 6], p
[ 7],
428 p
[ 8], p
[ 9], p
[10], p
[11], p
[12], p
[13], p
[14], p
[15]);
429 pout("===== [%s] DATA END (512 Bytes) =====\n\n", name
);
432 // This function provides the pretty-print reporting for SMART
433 // commands: it implements the various -r "reporting" options for ATA
435 int smartcommandhandler(ata_device
* device
, smart_command_set command
, int select
, char *data
){
436 // TODO: Rework old stuff below
437 // This conditional is true for commands that return data
438 int getsdata
=(command
==PIDENTIFY
||
441 command
==READ_THRESHOLDS
||
442 command
==READ_VALUES
||
443 command
==CHECK_POWER_MODE
);
445 int sendsdata
=(command
==WRITE_LOG
);
447 // If reporting is enabled, say what the command will be before it's executed
448 if (con
->reportataioctl
){
449 // conditional is true for commands that use parameters
450 int usesparam
=(command
==READ_LOG
||
451 command
==AUTO_OFFLINE
||
453 command
==IMMEDIATE_OFFLINE
||
456 pout("\nREPORT-IOCTL: Device=%s Command=%s", device
->get_dev_name(), commandstrings
[command
]);
458 pout(" InputParameter=%d\n", select
);
463 if ((getsdata
|| sendsdata
) && !data
){
464 pout("REPORT-IOCTL: Unable to execute command %s : data destination address is NULL\n", commandstrings
[command
]);
468 // The reporting is cleaner, and we will find coding bugs faster, if
469 // the commands that failed clearly return empty (zeroed) data
472 if (command
==CHECK_POWER_MODE
)
475 memset(data
, '\0', 512);
479 // if requested, pretty-print the input data structure
480 if (con
->reportataioctl
>1 && sendsdata
)
481 //pout("REPORT-IOCTL: Device=%s Command=%s\n", device->get_dev_name(), commandstrings[command]);
482 prettyprint((unsigned char *)data
, commandstrings
[command
]);
484 // now execute the command
488 // Set common register values
490 default: // SMART commands
491 in
.in_regs
.command
= ATA_SMART_CMD
;
492 in
.in_regs
.lba_high
= SMART_CYL_HI
; in
.in_regs
.lba_mid
= SMART_CYL_LOW
;
494 case IDENTIFY
: case PIDENTIFY
: case CHECK_POWER_MODE
: // Non SMART commands
497 // Set specific values
500 in
.in_regs
.command
= ATA_IDENTIFY_DEVICE
;
501 in
.set_data_in(data
, 1);
504 in
.in_regs
.command
= ATA_IDENTIFY_PACKET_DEVICE
;
505 in
.set_data_in(data
, 1);
507 case CHECK_POWER_MODE
:
508 in
.in_regs
.command
= ATA_CHECK_POWER_MODE
;
509 in
.out_needed
.sector_count
= true; // Powermode returned here
512 in
.in_regs
.features
= ATA_SMART_READ_VALUES
;
513 in
.set_data_in(data
, 1);
515 case READ_THRESHOLDS
:
516 in
.in_regs
.features
= ATA_SMART_READ_THRESHOLDS
;
517 in
.in_regs
.lba_low
= 1; // TODO: CORRECT ???
518 in
.set_data_in(data
, 1);
521 in
.in_regs
.features
= ATA_SMART_READ_LOG_SECTOR
;
522 in
.in_regs
.lba_low
= select
;
523 in
.set_data_in(data
, 1);
526 in
.in_regs
.features
= ATA_SMART_WRITE_LOG_SECTOR
;
527 in
.in_regs
.lba_low
= select
;
528 in
.set_data_out(data
, 1);
531 in
.in_regs
.features
= ATA_SMART_ENABLE
;
532 in
.in_regs
.lba_low
= 1; // TODO: CORRECT ???
535 in
.in_regs
.features
= ATA_SMART_DISABLE
;
536 in
.in_regs
.lba_low
= 1; // TODO: CORRECT ???
539 in
.out_needed
.lba_high
= in
.out_needed
.lba_mid
= true; // Status returned here
541 in
.in_regs
.features
= ATA_SMART_STATUS
;
544 in
.in_regs
.features
= ATA_SMART_AUTO_OFFLINE
;
545 in
.in_regs
.sector_count
= select
; // Caution: Non-DATA command!
548 in
.in_regs
.features
= ATA_SMART_AUTOSAVE
;
549 in
.in_regs
.sector_count
= select
; // Caution: Non-DATA command!
551 case IMMEDIATE_OFFLINE
:
552 in
.in_regs
.features
= ATA_SMART_IMMEDIATE_OFFLINE
;
553 in
.in_regs
.lba_low
= select
;
556 pout("Unrecognized command %d in smartcommandhandler()\n"
557 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
558 device
->set_err(ENOSYS
);
563 if (con
->reportataioctl
)
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"));
569 bool ok
= device
->ata_pass_through(in
, out
);
571 if (con
->reportataioctl
&& out
.out_regs
.is_set())
572 print_regs(" Output: ", out
.out_regs
);
574 if (ok
) switch (command
) {
578 case CHECK_POWER_MODE
:
579 data
[0] = out
.out_regs
.sector_count
;
583 // Cyl low and Cyl high unchanged means "Good SMART status"
584 if ((out
.out_regs
.lba_high
== SMART_CYL_HI
) &&
585 (out
.out_regs
.lba_mid
== SMART_CYL_LOW
))
587 // These values mean "Bad SMART status"
588 else if ((out
.out_regs
.lba_high
== SRET_STATUS_HI_EXCEEDED
) &&
589 (out
.out_regs
.lba_mid
== SRET_STATUS_MID_EXCEEDED
))
591 else if (out
.out_regs
.lba_mid
== SMART_CYL_LOW
) {
593 if (con
->reportataioctl
)
594 pout("SMART STATUS RETURN: half healthy response sequence, "
595 "probable SAT/USB truncation\n");
596 } else if (out
.out_regs
.lba_mid
== SRET_STATUS_MID_EXCEEDED
) {
598 if (con
->reportataioctl
)
599 pout("SMART STATUS RETURN: half unhealthy response sequence, "
600 "probable SAT/USB truncation\n");
602 // We haven't gotten output that makes sense; print out some debugging info
603 pout("Error SMART Status command failed\n"
604 "Please get assistance from %s\n", PACKAGE_HOMEPAGE
);
612 // If requested, invalidate serial number before any printing is done
613 if ((command
== IDENTIFY
|| command
== PIDENTIFY
) && !retval
&& con
->dont_print_serial
)
614 invalidate_serno((ata_identify_device
*)data
);
616 // If reporting is enabled, say what output was produced by the command
617 if (con
->reportataioctl
){
618 if (device
->get_errno())
619 pout("REPORT-IOCTL: Device=%s Command=%s returned %d errno=%d [%s]\n",
620 device
->get_dev_name(), commandstrings
[command
], retval
,
621 device
->get_errno(), device
->get_errmsg());
623 pout("REPORT-IOCTL: Device=%s Command=%s returned %d\n",
624 device
->get_dev_name(), commandstrings
[command
], retval
);
626 // if requested, pretty-print the output data structure
627 if (con
->reportataioctl
>1 && getsdata
) {
628 if (command
==CHECK_POWER_MODE
)
629 pout("Sector Count Register (BASE-16): %02x\n", (unsigned char)(*data
));
631 prettyprint((unsigned char *)data
, commandstrings
[command
]);
635 errno
= device
->get_errno(); // TODO: Callers should not call syserror()
639 // Get number of sectors from IDENTIFY sector. If the drive doesn't
640 // support LBA addressing or has no user writable sectors
641 // (eg, CDROM or DVD) then routine returns zero.
642 uint64_t get_num_sectors(const ata_identify_device
* drive
)
644 unsigned short command_set_2
= drive
->command_set_2
;
645 unsigned short capabilities_0
= drive
->words047_079
[49-47];
646 unsigned short sects_16
= drive
->words047_079
[60-47];
647 unsigned short sects_32
= drive
->words047_079
[61-47];
648 unsigned short lba_16
= drive
->words088_255
[100-88];
649 unsigned short lba_32
= drive
->words088_255
[101-88];
650 unsigned short lba_48
= drive
->words088_255
[102-88];
651 unsigned short lba_64
= drive
->words088_255
[103-88];
654 if (!(capabilities_0
& 0x0200))
657 // if drive supports LBA addressing, determine 32-bit LBA capacity
658 uint64_t lba32
= (unsigned int)sects_32
<< 16 |
659 (unsigned int)sects_16
<< 0 ;
662 // if drive supports 48-bit addressing, determine THAT capacity
663 if ((command_set_2
& 0xc000) == 0x4000 && (command_set_2
& 0x0400))
664 lba64
= (uint64_t)lba_64
<< 48 |
665 (uint64_t)lba_48
<< 32 |
666 (uint64_t)lba_32
<< 16 |
667 (uint64_t)lba_16
<< 0 ;
669 // return the larger of the two possible capacities
670 return (lba32
> lba64
? lba32
: lba64
);
673 // This function computes the checksum of a single disk sector (512
674 // bytes). Returns zero if checksum is OK, nonzero if the checksum is
675 // incorrect. The size (512) is correct for all SMART structures.
676 unsigned char checksum(const void * data
)
678 unsigned char sum
= 0;
679 for (int i
= 0; i
< 512; i
++)
680 sum
+= ((const unsigned char *)data
)[i
];
684 // Copies n bytes (or n-1 if n is odd) from in to out, but swaps adjacents
686 static void swapbytes(char * out
, const char * in
, size_t n
)
688 for (size_t i
= 0; i
< n
; i
+= 2) {
694 // Copies in to out, but removes leading and trailing whitespace.
695 static void trim(char * out
, const char * in
)
697 // Find the first non-space character (maybe none).
700 for (i
= 0; in
[i
]; i
++)
701 if (!isspace((int)in
[i
])) {
707 // There are no non-space characters.
712 // Find the last non-space character.
713 for (i
= strlen(in
)-1; i
>= first
&& isspace((int)in
[i
]); i
--)
717 strncpy(out
, in
+first
, last
-first
+1);
718 out
[last
-first
+1] = '\0';
721 // Convenience function for formatting strings from ata_identify_device
722 void format_ata_string(char * out
, const char * in
, int n
, bool fix_swap
)
724 bool must_swap
= !fix_swap
;
726 /* NetBSD kernel delivers IDENTIFY data in host byte order (but all else is LE) */
728 must_swap
= !must_swap
;
736 swapbytes(tmp
, in
, n
);
741 // returns -1 if command fails or the device is in Sleep mode, else
742 // value of Sector Count register. Sector Count result values:
743 // 00h device is in Standby mode.
744 // 80h device is in Idle mode.
745 // FFh device is in Active mode or Idle mode.
747 int ataCheckPowerMode(ata_device
* device
) {
748 unsigned char result
;
750 if ((smartcommandhandler(device
, CHECK_POWER_MODE
, 0, (char *)&result
)))
753 if (result
!=0 && result
!=0x80 && result
!=0xff)
754 pout("ataCheckPowerMode(): ATA CHECK POWER MODE returned unknown Sector Count Register value %02x\n", result
);
762 // Reads current Device Identity info (512 bytes) into buf. Returns 0
763 // if all OK. Returns -1 if no ATA Device identity can be
764 // established. Returns >0 if Device is ATA Packet Device (not SMART
765 // capable). The value of the integer helps identify the type of
766 // Packet device, which is useful so that the user can connect the
767 // formal device number with whatever object is inside their computer.
768 int ataReadHDIdentity (ata_device
* device
, struct ata_identify_device
*buf
){
769 unsigned short *rawshort
=(unsigned short *)buf
;
770 unsigned char *rawbyte
=(unsigned char *)buf
;
772 // See if device responds either to IDENTIFY DEVICE or IDENTIFY
774 if ((smartcommandhandler(device
, IDENTIFY
, 0, (char *)buf
))){
775 if (smartcommandhandler(device
, PIDENTIFY
, 0, (char *)buf
)){
781 // if machine is big-endian, swap byte order as needed
782 // NetBSD kernel delivers IDENTIFY data in host byte order
786 // swap various capability words that are needed
788 swap2((char *)(buf
->words047_079
+i
));
790 for (i
=80; i
<=87; i
++)
791 swap2((char *)(rawshort
+i
));
793 for (i
=0; i
<168; i
++)
794 swap2((char *)(buf
->words088_255
+i
));
798 // If there is a checksum there, validate it
799 if ((rawshort
[255] & 0x00ff) == 0x00a5 && checksum(rawbyte
))
800 checksumwarning("Drive Identity Structure");
802 // If this is a PACKET DEVICE, return device type
803 if (rawbyte
[1] & 0x80)
804 return 1+(rawbyte
[1] & 0x1f);
806 // Not a PACKET DEVICE
810 // Returns ATA version as an integer, and a pointer to a string
811 // describing which revision. Note that Revision 0 of ATA-3 does NOT
812 // support SMART. For this one case we return -3 rather than +3 as
813 // the version number. See notes above.
814 int ataVersionInfo(const char ** description
, const ata_identify_device
* drive
, unsigned short * minor
)
816 // check that arrays at the top of this file are defined
818 if (sizeof(minor_str
) != sizeof(char *)*(1+MINOR_MAX
)){
819 pout("Internal error in ataVersionInfo(). minor_str[] size %d\n"
820 "is not consistent with value of MINOR_MAX+1 = %d\n",
821 (int)(sizeof(minor_str
)/sizeof(char *)), MINOR_MAX
+1);
825 if (sizeof(actual_ver
) != sizeof(int)*(1+MINOR_MAX
)){
826 pout("Internal error in ataVersionInfo(). actual_ver[] size %d\n"
827 "is not consistent with value of MINOR_MAX = %d\n",
828 (int)(sizeof(actual_ver
)/sizeof(int)), MINOR_MAX
+1);
833 // get major and minor ATA revision numbers
834 unsigned short major
= drive
->major_rev_num
;
835 *minor
=drive
->minor_rev_num
;
837 // First check if device has ANY ATA version information in it
838 if (major
==NOVAL_0
|| major
==NOVAL_1
) {
843 // The minor revision number has more information - try there first
844 if (*minor
&& (*minor
<=MINOR_MAX
)){
845 int std
= actual_ver
[*minor
];
847 *description
=minor_str
[*minor
];
852 // Try new ATA-8 minor revision numbers (Table 31 of T13/1699-D Revision 6)
853 // (not in actual_ver/minor_str to avoid large sparse tables)
856 case 0x0027: desc
= "ATA-8-ACS revision 3c"; break;
857 case 0x0028: desc
= "ATA-8-ACS revision 6"; break;
858 case 0x0029: desc
= "ATA-8-ACS revision 4"; break;
859 case 0x0033: desc
= "ATA-8-ACS revision 3e"; break;
860 case 0x0039: desc
= "ATA-8-ACS revision 4c"; break;
861 case 0x0042: desc
= "ATA-8-ACS revision 3f"; break;
862 case 0x0052: desc
= "ATA-8-ACS revision 3b"; break;
863 case 0x0107: desc
= "ATA-8-ACS revision 2d"; break;
864 default: desc
= 0; break;
871 // HDPARM has a very complicated algorithm from here on. Since SMART only
872 // exists on ATA-3 and later standards, let's punt on this. If you don't
873 // like it, please fix it. The code's in CVS.
876 if (major
& (0x1<<i
))
886 // returns 1 if SMART supported, 0 if SMART unsupported, -1 if can't tell
887 int ataSmartSupport(const ata_identify_device
* drive
)
889 unsigned short word82
=drive
->command_set_1
;
890 unsigned short word83
=drive
->command_set_2
;
892 // check if words 82/83 contain valid info
893 if ((word83
>>14) == 0x01)
894 // return value of SMART support bit
895 return word82
& 0x0001;
897 // since we can're rely on word 82, we don't know if SMART supported
901 // returns 1 if SMART enabled, 0 if SMART disabled, -1 if can't tell
902 int ataIsSmartEnabled(const ata_identify_device
* drive
)
904 unsigned short word85
=drive
->cfs_enable_1
;
905 unsigned short word87
=drive
->csf_default
;
907 // check if words 85/86/87 contain valid info
908 if ((word87
>>14) == 0x01)
909 // return value of SMART enabled bit
910 return word85
& 0x0001;
912 // Since we can't rely word85, we don't know if SMART is enabled.
917 // Reads SMART attributes into *data
918 int ataReadSmartValues(ata_device
* device
, struct ata_smart_values
*data
){
920 if (smartcommandhandler(device
, READ_VALUES
, 0, (char *)data
)){
921 syserror("Error SMART Values Read failed");
927 checksumwarning("SMART Attribute Data Structure");
929 // swap endian order if needed
932 swap2((char *)&(data
->revnumber
));
933 swap2((char *)&(data
->total_time_to_complete_off_line
));
934 swap2((char *)&(data
->smart_capability
));
935 for (i
=0; i
<NUMBER_ATA_SMART_ATTRIBUTES
; i
++){
936 struct ata_smart_attribute
*x
=data
->vendor_attributes
+i
;
937 swap2((char *)&(x
->flags
));
945 // This corrects some quantities that are byte reversed in the SMART
947 static void fixsamsungselftestlog(ata_smart_selftestlog
* data
)
949 // bytes 508/509 (numbered from 0) swapped (swap of self-test index
950 // with one byte of reserved.
951 swap2((char *)&(data
->mostrecenttest
));
953 // LBA low register (here called 'selftestnumber", containing
954 // information about the TYPE of the self-test) is byte swapped with
955 // Self-test execution status byte. These are bytes N, N+1 in the
957 for (int i
= 0; i
< 21; i
++)
958 swap2((char *)&(data
->selftest_struct
[i
].selftestnumber
));
963 // Reads the Self Test Log (log #6)
964 int ataReadSelfTestLog (ata_device
* device
, ata_smart_selftestlog
* data
,
965 unsigned char fix_firmwarebug
)
968 // get data from device
969 if (smartcommandhandler(device
, READ_LOG
, 0x06, (char *)data
)){
970 syserror("Error SMART Error Self-Test Log Read failed");
974 // compute its checksum, and issue a warning if needed
976 checksumwarning("SMART Self-Test Log Structure");
978 // fix firmware bugs in self-test log
979 if (fix_firmwarebug
== FIX_SAMSUNG
)
980 fixsamsungselftestlog(data
);
982 // swap endian order if needed
985 swap2((char*)&(data
->revnumber
));
986 for (i
=0; i
<21; i
++){
987 struct ata_smart_selftestlog_struct
*x
=data
->selftest_struct
+i
;
988 swap2((char *)&(x
->timestamp
));
989 swap4((char *)&(x
->lbafirstfailure
));
996 // Print checksum warning for multi sector log
997 static void check_multi_sector_sum(const void * data
, unsigned nsectors
, const char * msg
)
1000 for (unsigned i
= 0; i
< nsectors
; i
++) {
1001 if (checksum((const unsigned char *)data
+ i
*512))
1006 checksumwarning(msg
);
1008 checksumwarning(strprintf("%s (%u/%u)", msg
, errs
, nsectors
).c_str());
1012 // Read SMART Extended Self-test Log
1013 bool ataReadExtSelfTestLog(ata_device
* device
, ata_smart_extselftestlog
* log
,
1016 if (!ataReadLogExt(device
, 0x07, 0x00, 0, log
, nsectors
))
1019 check_multi_sector_sum(log
, nsectors
, "SMART Extended Self-test Log Structure");
1021 if (isbigendian()) {
1022 swapx(&log
->log_desc_index
);
1023 for (unsigned i
= 0; i
< nsectors
; i
++) {
1024 for (unsigned j
= 0; j
< 19; j
++)
1025 swapx(&log
->log_descs
[i
].timestamp
);
1032 // Read GP Log page(s)
1033 bool ataReadLogExt(ata_device
* device
, unsigned char logaddr
,
1034 unsigned char features
, unsigned page
,
1035 void * data
, unsigned nsectors
)
1038 in
.in_regs
.command
= ATA_READ_LOG_EXT
;
1039 in
.in_regs
.features
= features
; // log specific
1040 in
.set_data_in_48bit(data
, nsectors
);
1041 in
.in_regs
.lba_low
= logaddr
;
1042 in
.in_regs
.lba_mid_16
= page
;
1044 if (!device
->ata_pass_through(in
)) { // TODO: Debug output
1045 if (nsectors
<= 1) {
1046 pout("ATA_READ_LOG_EXT (addr=0x%02x:0x%02x, page=%u, n=%u) failed: %s\n",
1047 logaddr
, features
, page
, nsectors
, device
->get_errmsg());
1051 // Recurse to retry with single sectors,
1052 // multi-sector reads may not be supported by ioctl.
1053 for (unsigned i
= 0; i
< nsectors
; i
++) {
1054 if (!ataReadLogExt(device
, logaddr
,
1056 (char *)data
+ 512*i
, 1))
1064 // Read SMART Log page(s)
1065 bool ataReadSmartLog(ata_device
* device
, unsigned char logaddr
,
1066 void * data
, unsigned nsectors
)
1069 in
.in_regs
.command
= ATA_SMART_CMD
;
1070 in
.in_regs
.features
= ATA_SMART_READ_LOG_SECTOR
;
1071 in
.set_data_in(data
, nsectors
);
1072 in
.in_regs
.lba_high
= SMART_CYL_HI
;
1073 in
.in_regs
.lba_mid
= SMART_CYL_LOW
;
1074 in
.in_regs
.lba_low
= logaddr
;
1076 if (!device
->ata_pass_through(in
)) { // TODO: Debug output
1077 pout("ATA_SMART_READ_LOG failed: %s\n", device
->get_errmsg());
1085 // Reads the SMART or GPL Log Directory (log #0)
1086 int ataReadLogDirectory(ata_device
* device
, ata_smart_log_directory
* data
, bool gpl
)
1088 if (!gpl
) { // SMART Log directory
1089 if (smartcommandhandler(device
, READ_LOG
, 0x00, (char *)data
))
1092 else { // GP Log directory
1093 if (!ataReadLogExt(device
, 0x00, 0x00, 0, data
, 1))
1097 // swap endian order if needed
1099 swapx(&data
->logversion
);
1105 // Reads the selective self-test log (log #9)
1106 int ataReadSelectiveSelfTestLog(ata_device
* device
, struct ata_selective_self_test_log
*data
){
1108 // get data from device
1109 if (smartcommandhandler(device
, READ_LOG
, 0x09, (char *)data
)){
1110 syserror("Error SMART Read Selective Self-Test Log failed");
1114 // compute its checksum, and issue a warning if needed
1116 checksumwarning("SMART Selective Self-Test Log Structure");
1118 // swap endian order if needed
1121 swap2((char *)&(data
->logversion
));
1123 swap8((char *)&(data
->span
[i
].start
));
1124 swap8((char *)&(data
->span
[i
].end
));
1126 swap8((char *)&(data
->currentlba
));
1127 swap2((char *)&(data
->currentspan
));
1128 swap2((char *)&(data
->flags
));
1129 swap2((char *)&(data
->pendingtime
));
1132 if (data
->logversion
!= 1)
1133 pout("Note: selective self-test log revision number (%d) not 1 implies that no selective self-test has ever been run\n", data
->logversion
);
1138 // Writes the selective self-test log (log #9)
1139 int ataWriteSelectiveSelfTestLog(ata_device
* device
, ata_selective_selftest_args
& args
,
1140 const ata_smart_values
* sv
, uint64_t num_sectors
)
1142 // Disk size must be known
1144 pout("Disk size is unknown, unable to check selective self-test spans\n");
1149 struct ata_selective_self_test_log sstlog
, *data
=&sstlog
;
1150 unsigned char *ptr
=(unsigned char *)data
;
1151 if (ataReadSelectiveSelfTestLog(device
, data
)) {
1152 pout("Since Read failed, will not attempt to WRITE Selective Self-test Log\n");
1157 data
->logversion
= 1;
1159 // Host is NOT allowed to write selective self-test log if a selective
1160 // self-test is in progress.
1161 if (0<data
->currentspan
&& data
->currentspan
<6 && ((sv
->self_test_exec_status
)>>4)==15) {
1162 pout("Error SMART Selective or other Self-Test in progress.\n");
1166 // Set start/end values based on old spans for special -t select,... options
1168 for (i
= 0; i
< args
.num_spans
; i
++) {
1169 int mode
= args
.span
[i
].mode
;
1170 uint64_t start
= args
.span
[i
].start
;
1171 uint64_t end
= args
.span
[i
].end
;
1172 if (mode
== SEL_CONT
) {// redo or next dependig on last test status
1173 switch (sv
->self_test_exec_status
>> 4) {
1174 case 1: case 2: // Aborted/Interrupted by host
1175 pout("Continue Selective Self-Test: Redo last span\n");
1178 default: // All others
1179 pout("Continue Selective Self-Test: Start next span\n");
1185 case SEL_RANGE
: // -t select,START-END
1187 case SEL_REDO
: // -t select,redo... => Redo current
1188 start
= data
->span
[i
].start
;
1189 if (end
> 0) { // -t select,redo+SIZE
1190 end
--; end
+= start
; // [oldstart, oldstart+SIZE)
1192 else // -t select,redo
1193 end
= data
->span
[i
].end
; // [oldstart, oldend]
1195 case SEL_NEXT
: // -t select,next... => Do next
1196 if (data
->span
[i
].end
== 0) {
1197 start
= end
= 0; break; // skip empty spans
1199 start
= data
->span
[i
].end
+ 1;
1200 if (start
>= num_sectors
)
1201 start
= 0; // wrap around
1202 if (end
> 0) { // -t select,next+SIZE
1203 end
--; end
+= start
; // (oldend, oldend+SIZE]
1205 else { // -t select,next
1206 uint64_t oldsize
= data
->span
[i
].end
- data
->span
[i
].start
+ 1;
1207 end
= start
+ oldsize
- 1; // (oldend, oldend+oldsize]
1208 if (end
>= num_sectors
) {
1209 // Adjust size to allow round-robin testing without future size decrease
1210 uint64_t spans
= (num_sectors
+ oldsize
-1) / oldsize
;
1211 uint64_t newsize
= (num_sectors
+ spans
-1) / spans
;
1212 uint64_t newstart
= num_sectors
- newsize
, newend
= num_sectors
- 1;
1213 pout("Span %d changed from %"PRIu64
"-%"PRIu64
" (%"PRIu64
" sectors)\n",
1214 i
, start
, end
, oldsize
);
1215 pout(" to %"PRIu64
"-%"PRIu64
" (%"PRIu64
" sectors) (%"PRIu64
" spans)\n",
1216 newstart
, newend
, newsize
, spans
);
1217 start
= newstart
; end
= newend
;
1222 pout("ataWriteSelectiveSelfTestLog: Invalid mode %d\n", mode
);
1226 if (start
< num_sectors
&& num_sectors
<= end
) {
1227 if (end
!= ~(uint64_t)0) // -t select,N-max
1228 pout("Size of self-test span %d decreased according to disk size\n", i
);
1229 end
= num_sectors
- 1;
1231 if (!(start
<= end
&& end
< num_sectors
)) {
1232 pout("Invalid selective self-test span %d: %"PRIu64
"-%"PRIu64
" (%"PRIu64
" sectors)\n",
1233 i
, start
, end
, num_sectors
);
1236 // Return the actual mode and range to caller.
1237 args
.span
[i
].mode
= mode
;
1238 args
.span
[i
].start
= start
;
1239 args
.span
[i
].end
= end
;
1244 memset(data
->span
+i
, 0, sizeof(struct test_span
));
1246 // Set spans for testing
1247 for (i
= 0; i
< args
.num_spans
; i
++){
1248 data
->span
[i
].start
= args
.span
[i
].start
;
1249 data
->span
[i
].end
= args
.span
[i
].end
;
1252 // host must initialize to zero before initiating selective self-test
1254 data
->currentspan
=0;
1256 // Perform off-line scan after selective test?
1257 if (args
.scan_after_select
== 1)
1259 data
->flags
&= ~SELECTIVE_FLAG_DOSCAN
;
1260 else if (args
.scan_after_select
== 2)
1262 data
->flags
|= SELECTIVE_FLAG_DOSCAN
;
1264 // Must clear active and pending flags before writing
1265 data
->flags
&= ~(SELECTIVE_FLAG_ACTIVE
);
1266 data
->flags
&= ~(SELECTIVE_FLAG_PENDING
);
1268 // modify pending time?
1269 if (args
.pending_time
)
1270 data
->pendingtime
= (unsigned short)(args
.pending_time
-1);
1272 // Set checksum to zero, then compute checksum
1274 unsigned char cksum
=0;
1275 for (i
=0; i
<512; i
++)
1279 data
->checksum
=cksum
;
1281 // swap endian order if needed
1283 swap2((char *)&(data
->logversion
));
1284 for (int i
=0;i
<5;i
++){
1285 swap8((char *)&(data
->span
[i
].start
));
1286 swap8((char *)&(data
->span
[i
].end
));
1288 swap8((char *)&(data
->currentlba
));
1289 swap2((char *)&(data
->currentspan
));
1290 swap2((char *)&(data
->flags
));
1291 swap2((char *)&(data
->pendingtime
));
1294 // write new selective self-test log
1295 if (smartcommandhandler(device
, WRITE_LOG
, 0x09, (char *)data
)){
1296 syserror("Error Write Selective Self-Test Log failed");
1303 // This corrects some quantities that are byte reversed in the SMART
1305 static void fixsamsungerrorlog(ata_smart_errorlog
* data
)
1307 // FIXED IN SAMSUNG -25 FIRMWARE???
1308 // Device error count in bytes 452-3
1309 swap2((char *)&(data
->ata_error_count
));
1311 // FIXED IN SAMSUNG -22a FIRMWARE
1312 // step through 5 error log data structures
1313 for (int i
= 0; i
< 5; i
++){
1314 // step through 5 command data structures
1315 for (int j
= 0; j
< 5; j
++)
1316 // Command data structure 4-byte millisec timestamp. These are
1317 // bytes (N+8, N+9, N+10, N+11).
1318 swap4((char *)&(data
->errorlog_struct
[i
].commands
[j
].timestamp
));
1319 // Error data structure two-byte hour life timestamp. These are
1320 // bytes (N+28, N+29).
1321 swap2((char *)&(data
->errorlog_struct
[i
].error_struct
.timestamp
));
1326 // NEEDED ONLY FOR SAMSUNG -22 (some) -23 AND -24?? FIRMWARE
1327 static void fixsamsungerrorlog2(ata_smart_errorlog
* data
)
1329 // Device error count in bytes 452-3
1330 swap2((char *)&(data
->ata_error_count
));
1334 // Reads the Summary SMART Error Log (log #1). The Comprehensive SMART
1335 // Error Log is #2, and the Extended Comprehensive SMART Error log is
1337 int ataReadErrorLog (ata_device
* device
, ata_smart_errorlog
*data
,
1338 unsigned char fix_firmwarebug
)
1341 // get data from device
1342 if (smartcommandhandler(device
, READ_LOG
, 0x01, (char *)data
)){
1343 syserror("Error SMART Error Log Read failed");
1347 // compute its checksum, and issue a warning if needed
1349 checksumwarning("SMART ATA Error Log Structure");
1351 // Some disks have the byte order reversed in some SMART Summary
1352 // Error log entries
1353 if (fix_firmwarebug
== FIX_SAMSUNG
)
1354 fixsamsungerrorlog(data
);
1355 else if (fix_firmwarebug
== FIX_SAMSUNG2
)
1356 fixsamsungerrorlog2(data
);
1358 // swap endian order if needed
1362 // Device error count in bytes 452-3
1363 swap2((char *)&(data
->ata_error_count
));
1365 // step through 5 error log data structures
1366 for (i
=0; i
<5; i
++){
1367 // step through 5 command data structures
1369 // Command data structure 4-byte millisec timestamp
1370 swap4((char *)&(data
->errorlog_struct
[i
].commands
[j
].timestamp
));
1371 // Error data structure life timestamp
1372 swap2((char *)&(data
->errorlog_struct
[i
].error_struct
.timestamp
));
1379 // Read Extended Comprehensive Error Log
1380 bool ataReadExtErrorLog(ata_device
* device
, ata_smart_exterrlog
* log
,
1383 if (!ataReadLogExt(device
, 0x03, 0x00, 0, log
, nsectors
))
1386 check_multi_sector_sum(log
, nsectors
, "SMART Extended Comprehensive Error Log Structure");
1388 if (isbigendian()) {
1389 swapx(&log
->device_error_count
);
1390 swapx(&log
->error_log_index
);
1392 for (unsigned i
= 0; i
< nsectors
; i
++) {
1393 for (unsigned j
= 0; j
< 4; j
++)
1394 swapx(&log
->error_logs
[i
].commands
[j
].timestamp
);
1395 swapx(&log
->error_logs
[i
].error
.timestamp
);
1403 int ataReadSmartThresholds (ata_device
* device
, struct ata_smart_thresholds_pvt
*data
){
1405 // get data from device
1406 if (smartcommandhandler(device
, READ_THRESHOLDS
, 0, (char *)data
)){
1407 syserror("Error SMART Thresholds Read failed");
1411 // compute its checksum, and issue a warning if needed
1413 checksumwarning("SMART Attribute Thresholds Structure");
1415 // swap endian order if needed
1417 swap2((char *)&(data
->revnumber
));
1422 int ataEnableSmart (ata_device
* device
){
1423 if (smartcommandhandler(device
, ENABLE
, 0, NULL
)){
1424 syserror("Error SMART Enable failed");
1430 int ataDisableSmart (ata_device
* device
){
1432 if (smartcommandhandler(device
, DISABLE
, 0, NULL
)){
1433 syserror("Error SMART Disable failed");
1439 int ataEnableAutoSave(ata_device
* device
){
1440 if (smartcommandhandler(device
, AUTOSAVE
, 241, NULL
)){
1441 syserror("Error SMART Enable Auto-save failed");
1447 int ataDisableAutoSave(ata_device
* device
){
1449 if (smartcommandhandler(device
, AUTOSAVE
, 0, NULL
)){
1450 syserror("Error SMART Disable Auto-save failed");
1456 // In *ALL* ATA standards the Enable/Disable AutoOffline command is
1457 // marked "OBSOLETE". It is defined in SFF-8035i Revision 2, and most
1458 // vendors still support it for backwards compatibility. IBM documents
1459 // it for some drives.
1460 int ataEnableAutoOffline (ata_device
* device
){
1462 /* timer hard coded to 4 hours */
1463 if (smartcommandhandler(device
, AUTO_OFFLINE
, 248, NULL
)){
1464 syserror("Error SMART Enable Automatic Offline failed");
1470 // Another Obsolete Command. See comments directly above, associated
1471 // with the corresponding Enable command.
1472 int ataDisableAutoOffline (ata_device
* device
){
1474 if (smartcommandhandler(device
, AUTO_OFFLINE
, 0, NULL
)){
1475 syserror("Error SMART Disable Automatic Offline failed");
1481 // If SMART is enabled, supported, and working, then this call is
1482 // guaranteed to return 1, else zero. Note that it should return 1
1483 // regardless of whether the disk's SMART status is 'healthy' or
1485 int ataDoesSmartWork(ata_device
* device
){
1486 int retval
=smartcommandhandler(device
, STATUS
, 0, NULL
);
1494 // This function uses a different interface (DRIVE_TASK) than the
1495 // other commands in this file.
1496 int ataSmartStatus2(ata_device
* device
){
1497 return smartcommandhandler(device
, STATUS_CHECK
, 0, NULL
);
1500 // This is the way to execute ALL tests: offline, short self-test,
1501 // extended self test, with and without captive mode, etc.
1502 // TODO: Move to ataprint.cpp ?
1503 int ataSmartTest(ata_device
* device
, int testtype
, const ata_selective_selftest_args
& selargs
,
1504 const ata_smart_values
* sv
, uint64_t num_sectors
)
1506 char cmdmsg
[128]; const char *type
, *captive
;
1507 int errornum
, cap
, retval
, select
=0;
1509 // Boolean, if set, says test is captive
1510 cap
=testtype
& CAPTIVE_MASK
;
1512 // Set up strings that describe the type of test
1518 if (testtype
==OFFLINE_FULL_SCAN
)
1520 else if (testtype
==SHORT_SELF_TEST
|| testtype
==SHORT_CAPTIVE_SELF_TEST
)
1521 type
="Short self-test";
1522 else if (testtype
==EXTEND_SELF_TEST
|| testtype
==EXTEND_CAPTIVE_SELF_TEST
)
1523 type
="Extended self-test";
1524 else if (testtype
==CONVEYANCE_SELF_TEST
|| testtype
==CONVEYANCE_CAPTIVE_SELF_TEST
)
1525 type
="Conveyance self-test";
1526 else if ((select
=(testtype
==SELECTIVE_SELF_TEST
|| testtype
==SELECTIVE_CAPTIVE_SELF_TEST
)))
1527 type
="Selective self-test";
1529 type
="[Unrecognized] self-test";
1531 // If doing a selective self-test, first use WRITE_LOG to write the
1532 // selective self-test log.
1533 ata_selective_selftest_args selargs_io
= selargs
; // filled with info about actual spans
1534 if (select
&& (retval
= ataWriteSelectiveSelfTestLog(device
, selargs_io
, sv
, num_sectors
))) {
1536 pout("Can't start selective self-test without aborting current test: use '-X' option to smartctl.\n");
1540 // Print ouf message that we are sending the command to test
1541 if (testtype
==ABORT_SELF_TEST
)
1542 sprintf(cmdmsg
,"Abort SMART off-line mode self-test routine");
1544 sprintf(cmdmsg
,"Execute SMART %s routine immediately in %s mode",type
,captive
);
1545 pout("Sending command: \"%s\".\n",cmdmsg
);
1549 pout("SPAN STARTING_LBA ENDING_LBA\n");
1550 for (i
= 0; i
< selargs_io
.num_spans
; i
++)
1551 pout(" %d %20"PRId64
" %20"PRId64
"\n", i
,
1552 selargs_io
.span
[i
].start
,
1553 selargs_io
.span
[i
].end
);
1556 // Now send the command to test
1557 errornum
=smartcommandhandler(device
, IMMEDIATE_OFFLINE
, testtype
, NULL
);
1559 if (errornum
&& !(cap
&& errno
==EIO
)){
1561 sprintf(errormsg
,"Command \"%s\" failed",cmdmsg
);
1567 // Since the command succeeded, tell user
1568 if (testtype
==ABORT_SELF_TEST
)
1569 pout("Self-testing aborted!\n");
1571 pout("Drive command \"%s\" successful.\nTesting has begun.\n",cmdmsg
);
1575 /* Test Time Functions */
1576 int TestTime(const ata_smart_values
*data
, int testtype
)
1579 case OFFLINE_FULL_SCAN
:
1580 return (int) data
->total_time_to_complete_off_line
;
1581 case SHORT_SELF_TEST
:
1582 case SHORT_CAPTIVE_SELF_TEST
:
1583 return (int) data
->short_test_completion_time
;
1584 case EXTEND_SELF_TEST
:
1585 case EXTEND_CAPTIVE_SELF_TEST
:
1586 return (int) data
->extend_test_completion_time
;
1587 case CONVEYANCE_SELF_TEST
:
1588 case CONVEYANCE_CAPTIVE_SELF_TEST
:
1589 return (int) data
->conveyance_test_completion_time
;
1595 // This function tells you both about the ATA error log and the
1596 // self-test error log capability (introduced in ATA-5). The bit is
1597 // poorly documented in the ATA/ATAPI standard. Starting with ATA-6,
1598 // SMART error logging is also indicated in bit 0 of DEVICE IDENTIFY
1599 // word 84 and 87. Top two bits must match the pattern 01. BEFORE
1600 // ATA-6 these top two bits still had to match the pattern 01, but the
1601 // remaining bits were reserved (==0).
1602 int isSmartErrorLogCapable (const ata_smart_values
* data
, const ata_identify_device
* identity
)
1604 unsigned short word84
=identity
->command_set_extension
;
1605 unsigned short word87
=identity
->csf_default
;
1606 int isata6
=identity
->major_rev_num
& (0x01<<6);
1607 int isata7
=identity
->major_rev_num
& (0x01<<7);
1609 if ((isata6
|| isata7
) && (word84
>>14) == 0x01 && (word84
& 0x01))
1612 if ((isata6
|| isata7
) && (word87
>>14) == 0x01 && (word87
& 0x01))
1615 // otherwise we'll use the poorly documented capability bit
1616 return data
->errorlog_capability
& 0x01;
1619 // See previous function. If the error log exists then the self-test
1620 // log should (must?) also exist.
1621 int isSmartTestLogCapable (const ata_smart_values
* data
, const ata_identify_device
*identity
)
1623 unsigned short word84
=identity
->command_set_extension
;
1624 unsigned short word87
=identity
->csf_default
;
1625 int isata6
=identity
->major_rev_num
& (0x01<<6);
1626 int isata7
=identity
->major_rev_num
& (0x01<<7);
1628 if ((isata6
|| isata7
) && (word84
>>14) == 0x01 && (word84
& 0x02))
1631 if ((isata6
|| isata7
) && (word87
>>14) == 0x01 && (word87
& 0x02))
1635 // otherwise we'll use the poorly documented capability bit
1636 return data
->errorlog_capability
& 0x01;
1640 int isGeneralPurposeLoggingCapable(const ata_identify_device
*identity
)
1642 unsigned short word84
=identity
->command_set_extension
;
1643 unsigned short word87
=identity
->csf_default
;
1645 // If bit 14 of word 84 is set to one and bit 15 of word 84 is
1646 // cleared to zero, the contents of word 84 contains valid support
1647 // information. If not, support information is not valid in this
1649 if ((word84
>>14) == 0x01)
1650 // If bit 5 of word 84 is set to one, the device supports the
1651 // General Purpose Logging feature set.
1652 return (word84
& (0x01 << 5));
1654 // If bit 14 of word 87 is set to one and bit 15 of word 87 is
1655 // cleared to zero, the contents of words (87:85) contain valid
1656 // information. If not, information is not valid in these words.
1657 if ((word87
>>14) == 0x01)
1658 // If bit 5 of word 87 is set to one, the device supports
1659 // the General Purpose Logging feature set.
1660 return (word87
& (0x01 << 5));
1667 // SMART self-test capability is also indicated in bit 1 of DEVICE
1668 // IDENTIFY word 87 (if top two bits of word 87 match pattern 01).
1669 // However this was only introduced in ATA-6 (but self-test log was in
1671 int isSupportExecuteOfflineImmediate(const ata_smart_values
*data
)
1673 return data
->offline_data_collection_capability
& 0x01;
1676 // Note in the ATA-5 standard, the following bit is listed as "Vendor
1677 // Specific". So it may not be reliable. The only use of this that I
1678 // have found is in IBM drives, where it is well-documented. See for
1679 // example page 170, section 13.32.1.18 of the IBM Travelstar 40GNX
1680 // hard disk drive specifications page 164 Revision 1.1 22 Apr 2002.
1681 int isSupportAutomaticTimer(const ata_smart_values
* data
)
1683 return data
->offline_data_collection_capability
& 0x02;
1685 int isSupportOfflineAbort(const ata_smart_values
*data
)
1687 return data
->offline_data_collection_capability
& 0x04;
1689 int isSupportOfflineSurfaceScan(const ata_smart_values
* data
)
1691 return data
->offline_data_collection_capability
& 0x08;
1693 int isSupportSelfTest (const ata_smart_values
* data
)
1695 return data
->offline_data_collection_capability
& 0x10;
1697 int isSupportConveyanceSelfTest(const ata_smart_values
* data
)
1699 return data
->offline_data_collection_capability
& 0x20;
1701 int isSupportSelectiveSelfTest(const ata_smart_values
* data
)
1703 return data
->offline_data_collection_capability
& 0x40;
1706 // Get attribute state
1707 ata_attr_state
ata_get_attr_state(const ata_smart_attribute
& attr
,
1708 const ata_smart_threshold_entry
& thre
,
1709 const ata_vendor_attr_defs
& defs
)
1712 return ATTRSTATE_NON_EXISTING
;
1714 // Normalized values (current,worst,threshold) not valid
1715 // if specified by '-v' option.
1716 // (Some SSD disks uses these bytes to store raw value).
1717 if (defs
[attr
.id
].flags
& ATTRFLAG_NO_NORMVAL
)
1718 return ATTRSTATE_NO_NORMVAL
;
1720 // No threshold if thresholds cannot be read.
1721 if (!thre
.id
&& !thre
.threshold
)
1722 return ATTRSTATE_NO_THRESHOLD
;
1724 // Bad threshold if id's don't match
1725 if (attr
.id
!= thre
.id
)
1726 return ATTRSTATE_BAD_THRESHOLD
;
1728 // Don't report a failed attribute if its threshold is 0.
1729 // ATA-3 (X3T13/2008D Revision 7b) declares 0x00 as the "always passing"
1730 // threshold (Later ATA versions declare all thresholds as "obsolete").
1731 // In practice, threshold value 0 is often used for usage attributes.
1732 if (!thre
.threshold
)
1733 return ATTRSTATE_OK
;
1735 // Failed now if current value is below threshold
1736 if (attr
.current
<= thre
.threshold
)
1737 return ATTRSTATE_FAILED_NOW
;
1739 // Failed in the passed if worst value is below threshold
1740 if (attr
.worst
<= thre
.threshold
)
1741 return ATTRSTATE_FAILED_PAST
;
1743 return ATTRSTATE_OK
;
1746 // Get default raw value print format
1747 static ata_attr_raw_format
get_default_raw_format(unsigned char id
)
1750 case 3: // Spin-up time
1751 return RAWFMT_RAW16_OPT_AVG16
;
1753 case 5: // Reallocated sector count
1754 case 196: // Reallocated event count
1755 return RAWFMT_RAW16_OPT_RAW16
;
1757 case 190: // Temperature
1759 return RAWFMT_TEMPMINMAX
;
1762 return RAWFMT_RAW48
;
1766 // Get attribute raw value.
1767 uint64_t ata_get_attr_raw_value(const ata_smart_attribute
& attr
,
1768 const ata_vendor_attr_defs
& defs
)
1770 // Get 48 bit raw value
1771 const unsigned char * raw
= attr
.raw
;
1776 | ((uint64_t)raw
[3] << 24)
1777 | ((uint64_t)raw
[4] << 32)
1778 | ((uint64_t)raw
[5] << 40);
1780 if (defs
[attr
.id
].flags
& ATTRFLAG_NO_NORMVAL
) {
1781 // Some SSD vendors use bytes 3-10 from the Attribute
1782 // Data Structure to store a 64-bit raw value.
1784 rawvalue
|= attr
.worst
;
1786 rawvalue
|= attr
.current
;
1792 // Format attribute raw value.
1793 std::string
ata_format_attr_raw_value(const ata_smart_attribute
& attr
,
1794 const ata_vendor_attr_defs
& defs
)
1796 // Get 48 bit or64 bit raw value
1797 uint64_t rawvalue
= ata_get_attr_raw_value(attr
, defs
);
1800 const unsigned char * raw
= attr
.raw
;
1802 word
[0] = raw
[0] | (raw
[1] << 8);
1803 word
[1] = raw
[2] | (raw
[3] << 8);
1804 word
[2] = raw
[4] | (raw
[5] << 8);
1807 ata_attr_raw_format format
= defs
[attr
.id
].raw_format
;
1808 if (format
== RAWFMT_DEFAULT
)
1809 format
= get_default_raw_format(attr
.id
);
1815 s
= strprintf("%d %d %d %d %d %d",
1816 raw
[5], raw
[4], raw
[3], raw
[2], raw
[1], raw
[0]);
1820 s
= strprintf("%u %u %u", word
[2], word
[1], word
[0]);
1824 s
= strprintf("%"PRIu64
, rawvalue
);
1828 s
= strprintf("0x%012"PRIx64
, rawvalue
);
1832 s
= strprintf("%"PRIu64
, rawvalue
);
1836 s
= strprintf("0x%016"PRIx64
, rawvalue
);
1839 case RAWFMT_RAW16_OPT_RAW16
:
1840 s
= strprintf("%u", word
[0]);
1841 if (word
[1] || word
[2])
1842 s
+= strprintf(" (%u, %u)", word
[2], word
[1]);
1845 case RAWFMT_RAW16_OPT_AVG16
:
1846 s
= strprintf("%u", word
[0]);
1848 s
+= strprintf(" (Average %u)", word
[1]);
1851 case RAWFMT_RAW24_RAW24
:
1852 s
= strprintf("%d/%d",
1853 raw
[0] | (raw
[1]<<8) | (raw
[2]<<16),
1854 raw
[3] | (raw
[4]<<8) | (raw
[5]<<16));
1857 case RAWFMT_MIN2HOUR
:
1860 int64_t temp
= word
[0]+(word
[1]<<16);
1861 int64_t tmp1
= temp
/60;
1862 int64_t tmp2
= temp
%60;
1863 s
= strprintf("%"PRIu64
"h+%02"PRIu64
"m", tmp1
, tmp2
);
1865 s
+= strprintf(" (%u)", word
[2]);
1869 case RAWFMT_SEC2HOUR
:
1872 int64_t hours
= rawvalue
/3600;
1873 int64_t minutes
= (rawvalue
-3600*hours
)/60;
1874 int64_t seconds
= rawvalue
%60;
1875 s
= strprintf("%"PRIu64
"h+%02"PRIu64
"m+%02"PRIu64
"s", hours
, minutes
, seconds
);
1879 case RAWFMT_HALFMIN2HOUR
:
1881 // 30-second counter
1882 int64_t hours
= rawvalue
/120;
1883 int64_t minutes
= (rawvalue
-120*hours
)/2;
1884 s
+= strprintf("%"PRIu64
"h+%02"PRIu64
"m", hours
, minutes
);
1888 case RAWFMT_TEMPMINMAX
:
1890 s
= strprintf("%u", word
[0]);
1891 if (word
[1] || word
[2]) {
1892 unsigned lo
= ~0, hi
= ~0;
1894 // 00 HH 00 LL 00 TT (IBM)
1895 hi
= word
[2]; lo
= word
[1];
1897 else if (!word
[2]) {
1898 // 00 00 HH LL 00 TT (Maxtor)
1899 hi
= raw
[3]; lo
= raw
[2];
1902 unsigned t
= lo
; lo
= hi
; hi
= t
;
1904 if (lo
<= word
[0] && word
[0] <= hi
)
1905 s
+= strprintf(" (Lifetime Min/Max %u/%u)", lo
, hi
);
1907 s
+= strprintf(" (%d %d %d %d)", raw
[5], raw
[4], raw
[3], raw
[2]);
1911 case RAWFMT_TEMP10X
:
1912 // ten times temperature in Celsius
1913 s
= strprintf("%d.%d", word
[0]/10, word
[0]%10);
1917 s
= "?"; // Should not happen
1924 // Attribute names shouldn't be longer than 23 chars, otherwise they break the
1925 // output of smartctl.
1926 static const char * get_default_attr_name(unsigned char id
)
1930 return "Raw_Read_Error_Rate";
1932 return "Throughput_Performance";
1934 return "Spin_Up_Time";
1936 return "Start_Stop_Count";
1938 return "Reallocated_Sector_Ct";
1940 return "Read_Channel_Margin";
1942 return "Seek_Error_Rate";
1944 return "Seek_Time_Performance";
1946 return "Power_On_Hours";
1948 return "Spin_Retry_Count";
1950 return "Calibration_Retry_Count";
1952 return "Power_Cycle_Count";
1954 return "Read_Soft_Error_Rate";
1956 return "Program_Fail_Count_Chip";
1958 return "Erase_Fail_Count_Chip";
1960 return "Wear_Leveling_Count";
1962 return "Used_Rsvd_Blk_Cnt_Chip";
1964 return "Used_Rsvd_Blk_Cnt_Tot";
1966 return "Unused_Rsvd_Blk_Cnt_Tot";
1968 return "Program_Fail_Cnt_Total";
1970 return "Erase_Fail_Count_Total";
1972 return "Runtime_Bad_Block";
1974 return "End-to-End_Error";
1976 return "Reported_Uncorrect";
1978 return "Command_Timeout";
1980 return "High_Fly_Writes";
1982 // Western Digital uses this for temperature.
1983 // It's identical to Attribute 194 except that it
1984 // has a failure threshold set to correspond to the
1985 // max allowed operating temperature of the drive, which
1986 // is typically 55C. So if this attribute has failed
1987 // in the past, it indicates that the drive temp exceeded
1988 // 55C sometime in the past.
1989 return "Airflow_Temperature_Cel";
1991 return "G-Sense_Error_Rate";
1993 return "Power-Off_Retract_Count";
1995 return "Load_Cycle_Count";
1997 return "Temperature_Celsius";
1999 // Fujitsu: "ECC_On_The_Fly_Count";
2000 return "Hardware_ECC_Recovered";
2002 return "Reallocated_Event_Count";
2004 return "Current_Pending_Sector";
2006 return "Offline_Uncorrectable";
2008 return "UDMA_CRC_Error_Count";
2011 return "Multi_Zone_Error_Rate";
2013 return "Soft_Read_Error_Rate";
2015 // Fujitsu: "TA_Increase_Count"
2016 return "Data_Address_Mark_Errs";
2019 return "Run_Out_Cancel";
2020 // Maxtor: ECC Errors
2022 // Fujitsu: "Shock_Count_Write_Opern"
2023 return "Soft_ECC_Correction";
2025 // Fujitsu: "Shock_Rate_Write_Opern"
2026 return "Thermal_Asperity_Rate";
2029 return "Flying_Height";
2032 return "Spin_High_Current";
2038 return "Offline_Seek_Performnce";
2040 return "Disk_Shift";
2042 return "G-Sense_Error_Rate";
2044 return "Loaded_Hours";
2046 return "Load_Retry_Count";
2048 return "Load_Friction";
2050 return "Load_Cycle_Count";
2052 return "Load-in_Time";
2054 return "Torq-amp_Count";
2056 return "Power-off_Retract_Count";
2058 // seen in IBM DTPA-353750
2059 return "Head_Amplitude";
2061 return "Temperature_Celsius";
2063 // seen in Intel X25-E SSD
2064 return "Available_Reservd_Space";
2066 // seen in Intel X25-E SSD
2067 return "Media_Wearout_Indicator";
2069 return "Head_Flying_Hours";
2071 return "Total_LBAs_Written";
2073 return "Total_LBAs_Read";
2075 return "Read_Error_Retry_Rate";
2077 return "Free_Fall_Sensor";
2079 return "Unknown_Attribute";
2083 // Get attribute name
2084 std::string
ata_get_smart_attr_name(unsigned char id
, const ata_vendor_attr_defs
& defs
)
2086 if (!defs
[id
].name
.empty())
2087 return defs
[id
].name
;
2089 return get_default_attr_name(id
);
2092 // Find attribute index for attribute id, -1 if not found.
2093 int ata_find_attr_index(unsigned char id
, const ata_smart_values
& smartval
)
2097 for (int i
= 0; i
< NUMBER_ATA_SMART_ATTRIBUTES
; i
++) {
2098 if (smartval
.vendor_attributes
[i
].id
== id
)
2104 // Return Temperature Attribute raw value selected according to possible
2105 // non-default interpretations. If the Attribute does not exist, return 0
2106 unsigned char ata_return_temperature_value(const ata_smart_values
* data
, const ata_vendor_attr_defs
& defs
)
2108 for (int i
= 0; i
< 3; i
++) {
2109 static const unsigned char ids
[3] = {194, 9, 220};
2110 unsigned char id
= ids
[i
];
2111 const ata_attr_raw_format format
= defs
[id
].raw_format
;
2112 if (!( (id
== 194 && format
== RAWFMT_DEFAULT
)
2113 || format
== RAWFMT_TEMPMINMAX
|| format
== RAWFMT_TEMP10X
))
2115 int idx
= ata_find_attr_index(id
, *data
);
2118 uint64_t raw
= ata_get_attr_raw_value(data
->vendor_attributes
[idx
], defs
);
2119 unsigned temp
= (unsigned short)raw
; // ignore possible min/max values in high words
2120 if (format
== RAWFMT_TEMP10X
) // -v N,temp10x
2121 temp
= (temp
+5) / 10;
2122 if (!(0 < temp
&& temp
<= 255))
2126 // No valid attribute found
2132 int ataReadSCTStatus(ata_device
* device
, ata_sct_status_response
* sts
)
2134 // read SCT status via SMART log 0xe0
2135 memset(sts
, 0, sizeof(*sts
));
2136 if (smartcommandhandler(device
, READ_LOG
, 0xe0, (char *)sts
)){
2137 syserror("Error Read SCT Status failed");
2141 // swap endian order if needed
2143 swapx(&sts
->format_version
);
2144 swapx(&sts
->sct_version
);
2145 swapx(&sts
->sct_spec
);
2146 swapx(&sts
->ext_status_code
);
2147 swapx(&sts
->action_code
);
2148 swapx(&sts
->function_code
);
2149 swapx(&sts
->over_limit_count
);
2150 swapx(&sts
->under_limit_count
);
2153 // Check format version
2154 if (!(sts
->format_version
== 2 || sts
->format_version
== 3)) {
2155 pout("Error unknown SCT Status format version %u, should be 2 or 3.\n", sts
->format_version
);
2161 // Read SCT Temperature History Table and Status
2162 int ataReadSCTTempHist(ata_device
* device
, ata_sct_temperature_history_table
* tmh
,
2163 ata_sct_status_response
* sts
)
2165 // Check initial status
2166 if (ataReadSCTStatus(device
, sts
))
2169 // Do nothing if other SCT command is executing
2170 if (sts
->ext_status_code
== 0xffff) {
2171 pout("Another SCT command is executing, abort Read Data Table\n"
2172 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2173 sts
->ext_status_code
, sts
->action_code
, sts
->function_code
);
2177 ata_sct_data_table_command cmd
; memset(&cmd
, 0, sizeof(cmd
));
2178 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2179 cmd
.action_code
= 5; // Data table command
2180 cmd
.function_code
= 1; // Read table
2181 cmd
.table_id
= 2; // Temperature History Table
2183 // write command via SMART log page 0xe0
2184 if (smartcommandhandler(device
, WRITE_LOG
, 0xe0, (char *)&cmd
)){
2185 syserror("Error Write SCT Data Table command failed");
2189 // read SCT data via SMART log page 0xe1
2190 memset(tmh
, 0, sizeof(*tmh
));
2191 if (smartcommandhandler(device
, READ_LOG
, 0xe1, (char *)tmh
)){
2192 syserror("Error Read SCT Data Table failed");
2196 // re-read and check SCT status
2197 if (ataReadSCTStatus(device
, sts
))
2200 if (!(sts
->ext_status_code
== 0 && sts
->action_code
== 5 && sts
->function_code
== 1)) {
2201 pout("Error unexcepted SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2202 sts
->ext_status_code
, sts
->action_code
, sts
->function_code
);
2206 // swap endian order if needed
2208 swapx(&tmh
->format_version
);
2209 swapx(&tmh
->sampling_period
);
2210 swapx(&tmh
->interval
);
2213 // Check format version
2214 if (tmh
->format_version
!= 2) {
2215 pout("Error unknown SCT Temperature History Format Version (%u), should be 2.\n", tmh
->format_version
);
2221 // Set SCT Temperature Logging Interval
2222 int ataSetSCTTempInterval(ata_device
* device
, unsigned interval
, bool persistent
)
2224 // Check initial status
2225 ata_sct_status_response sts
;
2226 if (ataReadSCTStatus(device
, &sts
))
2229 // Do nothing if other SCT command is executing
2230 if (sts
.ext_status_code
== 0xffff) {
2231 pout("Another SCT command is executing, abort Feature Control\n"
2232 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2233 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2237 ata_sct_feature_control_command cmd
; memset(&cmd
, 0, sizeof(cmd
));
2238 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2239 cmd
.action_code
= 4; // Feature Control command
2240 cmd
.function_code
= 1; // Set state
2241 cmd
.feature_code
= 3; // Temperature logging interval
2242 cmd
.state
= interval
;
2243 cmd
.option_flags
= (persistent
? 0x01 : 0x00);
2245 // write command via SMART log page 0xe0
2246 if (smartcommandhandler(device
, WRITE_LOG
, 0xe0, (char *)&cmd
)){
2247 syserror("Error Write SCT Feature Control Command failed");
2251 // re-read and check SCT status
2252 if (ataReadSCTStatus(device
, &sts
))
2255 if (!(sts
.ext_status_code
== 0 && sts
.action_code
== 4 && sts
.function_code
== 1)) {
2256 pout("Error unexcepted SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2257 sts
.ext_status_code
, sts
.action_code
, sts
.function_code
);
2263 // Print one self-test log entry.
2264 // Returns true if self-test showed an error.
2265 bool ataPrintSmartSelfTestEntry(unsigned testnum
, unsigned char test_type
,
2266 unsigned char test_status
,
2267 unsigned short timestamp
,
2268 uint64_t failing_lba
,
2269 bool print_error_only
, bool & print_header
)
2271 const char * msgtest
;
2272 switch (test_type
) {
2273 case 0x00: msgtest
= "Offline"; break;
2274 case 0x01: msgtest
= "Short offline"; break;
2275 case 0x02: msgtest
= "Extended offline"; break;
2276 case 0x03: msgtest
= "Conveyance offline"; break;
2277 case 0x04: msgtest
= "Selective offline"; break;
2278 case 0x7f: msgtest
= "Abort offline test"; break;
2279 case 0x81: msgtest
= "Short captive"; break;
2280 case 0x82: msgtest
= "Extended captive"; break;
2281 case 0x83: msgtest
= "Conveyance captive"; break;
2282 case 0x84: msgtest
= "Selective captive"; break;
2284 if ((0x40 <= test_type
&& test_type
<= 0x7e) || 0x90 <= test_type
)
2285 msgtest
= "Vendor offline";
2287 msgtest
= "Reserved offline";
2290 bool is_error
= false;
2291 const char * msgstat
;
2292 switch (test_status
>> 4) {
2293 case 0x0: msgstat
= "Completed without error"; break;
2294 case 0x1: msgstat
= "Aborted by host"; break;
2295 case 0x2: msgstat
= "Interrupted (host reset)"; break;
2296 case 0x3: msgstat
= "Fatal or unknown error"; is_error
= true; break;
2297 case 0x4: msgstat
= "Completed: unknown failure"; is_error
= true; break;
2298 case 0x5: msgstat
= "Completed: electrical failure"; is_error
= true; break;
2299 case 0x6: msgstat
= "Completed: servo/seek failure"; is_error
= true; break;
2300 case 0x7: msgstat
= "Completed: read failure"; is_error
= true; break;
2301 case 0x8: msgstat
= "Completed: handling damage??"; is_error
= true; break;
2302 case 0xf: msgstat
= "Self-test routine in progress"; break;
2303 default: msgstat
= "Unknown/reserved test status";
2306 if (!is_error
&& print_error_only
)
2309 // Print header once
2311 print_header
= false;
2312 pout("Num Test_Description Status Remaining LifeTime(hours) LBA_of_first_error\n");
2316 if (is_error
&& failing_lba
< 0xffffffffffffULL
)
2317 snprintf(msglba
, sizeof(msglba
), "%"PRIu64
, failing_lba
);
2319 strcpy(msglba
, "-");
2321 pout("#%2u %-19s %-29s %1d0%% %8u %s\n", testnum
, msgtest
, msgstat
,
2322 test_status
& 0x0f, timestamp
, msglba
);
2327 // Print Smart self-test log, used by smartctl and smartd.
2329 // bottom 8 bits: number of entries found where self-test showed an error
2330 // remaining bits: if nonzero, power on hours of last self-test where error was found
2331 int ataPrintSmartSelfTestlog(const ata_smart_selftestlog
* data
, bool allentries
,
2332 unsigned char fix_firmwarebug
)
2335 pout("SMART Self-test log structure revision number %d\n",(int)data
->revnumber
);
2336 if ((data
->revnumber
!=0x0001) && allentries
&& fix_firmwarebug
!= FIX_SAMSUNG
)
2337 pout("Warning: ATA Specification requires self-test log structure revision number = 1\n");
2338 if (data
->mostrecenttest
==0){
2340 pout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n\n");
2344 bool noheaderprinted
= true;
2345 int retval
=0, hours
=0, testno
=0;
2348 for (int i
= 20; i
>= 0; i
--) {
2349 // log is a circular buffer
2350 int j
= (i
+data
->mostrecenttest
)%21;
2351 const ata_smart_selftestlog_struct
* log
= data
->selftest_struct
+j
;
2353 if (nonempty(log
, sizeof(*log
))) {
2354 // count entry based on non-empty structures -- needed for
2355 // Seagate only -- other vendors don't have blank entries 'in
2359 // T13/1321D revision 1c: (Data structure Rev #1)
2361 //The failing LBA shall be the LBA of the uncorrectable sector
2362 //that caused the test to fail. If the device encountered more
2363 //than one uncorrectable sector during the test, this field
2364 //shall indicate the LBA of the first uncorrectable sector
2365 //encountered. If the test passed or the test failed for some
2366 //reason other than an uncorrectable sector, the value of this
2367 //field is undefined.
2369 // This is true in ALL ATA-5 specs
2370 uint64_t lba48
= (log
->lbafirstfailure
< 0xffffffff ? log
->lbafirstfailure
: 0xffffffffffffULL
);
2373 bool errorfound
= ataPrintSmartSelfTestEntry(testno
,
2374 log
->selftestnumber
, log
->selfteststatus
, log
->timestamp
,
2375 lba48
, !allentries
, noheaderprinted
);
2377 // keep track of time of most recent error
2378 if (errorfound
&& !hours
)
2379 hours
=log
->timestamp
;
2382 if (!allentries
&& retval
)
2386 return (retval
| hours
);
2390 /////////////////////////////////////////////////////////////////////////////
2391 // Pseudo-device to parse "smartctl -r ataioctl,2 ..." output and simulate
2392 // an ATA device with same behaviour
2396 class parsed_ata_device
2397 : public /*implements*/ ata_device_with_command_set
2400 parsed_ata_device(smart_interface
* intf
, const char * dev_name
);
2402 virtual ~parsed_ata_device() throw();
2404 virtual bool is_open() const;
2406 virtual bool open();
2408 virtual bool close();
2410 virtual bool ata_identify_is_cached() const;
2413 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2416 // Table of parsed commands, return value, data
2417 struct parsed_ata_command
2419 smart_command_set command
;
2425 enum { max_num_commands
= 32 };
2426 parsed_ata_command m_command_table
[max_num_commands
];
2429 int m_next_replay_command
;
2430 bool m_replay_out_of_sync
;
2431 bool m_ata_identify_is_cached
;
2434 static const char * nextline(const char * s
, int & lineno
)
2436 for (s
+= strcspn(s
, "\r\n"); *s
== '\r' || *s
== '\n'; s
++) {
2437 if (*s
== '\r' && s
[1] == '\n')
2444 static int name2command(const char * s
)
2446 for (int i
= 0; i
< (int)(sizeof(commandstrings
)/sizeof(commandstrings
[0])); i
++) {
2447 if (!strcmp(s
, commandstrings
[i
]))
2453 static bool matchcpy(char * dest
, size_t size
, const char * src
, const regmatch_t
& srcmatch
)
2455 if (srcmatch
.rm_so
< 0)
2457 size_t n
= srcmatch
.rm_eo
- srcmatch
.rm_so
;
2460 memcpy(dest
, src
+ srcmatch
.rm_so
, n
);
2465 static inline int matchtoi(const char * src
, const regmatch_t
& srcmatch
, int defval
)
2467 if (srcmatch
.rm_so
< 0)
2469 return atoi(src
+ srcmatch
.rm_so
);
2472 parsed_ata_device::parsed_ata_device(smart_interface
* intf
, const char * dev_name
)
2473 : smart_device(intf
, dev_name
, "ata", ""),
2475 m_next_replay_command(0),
2476 m_replay_out_of_sync(false),
2477 m_ata_identify_is_cached(false)
2479 memset(m_command_table
, 0, sizeof(m_command_table
));
2482 parsed_ata_device::~parsed_ata_device() throw()
2487 bool parsed_ata_device::is_open() const
2489 return (m_num_commands
> 0);
2492 // Parse stdin and build command table
2493 bool parsed_ata_device::open()
2495 const char * pathname
= get_dev_name();
2496 if (strcmp(pathname
, "-"))
2497 return set_err(EINVAL
);
2498 pathname
= "<stdin>";
2500 char buffer
[64*1024];
2502 while (size
< (int)sizeof(buffer
)) {
2503 int nr
= fread(buffer
, 1, sizeof(buffer
), stdin
);
2509 return set_err(ENOENT
, "%s: Unexpected EOF", pathname
);
2510 if (size
>= (int)sizeof(buffer
))
2511 return set_err(EIO
, "%s: Buffer overflow", pathname
);
2514 // Regex to match output from "-r ataioctl,2"
2515 static const char pattern
[] = "^"
2517 "REPORT-IOCTL: DeviceF?D?=[^ ]+ Command=([A-Z ]*[A-Z])" // (2)
2519 "( InputParameter=([0-9]+))?" // (4 (5))
2521 "( returned (-?[0-9]+)( errno=([0-9]+)[^\r\n]*)?)" // (6 (7) (8 (9)))
2523 "[\r\n]" // EOL match necessary to match optional parts above
2525 "===== \\[([A-Z ]*[A-Z])\\] DATA START " // (10)
2527 " *(En|Dis)abled status cached by OS, " // (11)
2531 regular_expression regex
;
2532 if (!regex
.compile(pattern
, REG_EXTENDED
))
2533 return set_err(EIO
, "invalid regex");
2536 const char * errmsg
= 0;
2537 int i
= -1, state
= 0, lineno
= 1;
2538 for (const char * line
= buffer
; *line
; line
= nextline(line
, lineno
)) {
2540 if (!(line
[0] == 'R' || line
[0] == '=' || line
[0] == ' '))
2542 const int nmatch
= 1+11;
2543 regmatch_t match
[nmatch
];
2544 if (!regex
.execute(line
, nmatch
, match
))
2548 if (matchcpy(cmdname
, sizeof(cmdname
), line
, match
[2])) { // "REPORT-IOCTL:... Command=%s ..."
2549 int nc
= name2command(cmdname
);
2551 errmsg
= "Unknown ATA command name"; break;
2553 if (match
[7].rm_so
< 0) { // "returned %d"
2555 if (!(state
== 0 || state
== 2)) {
2556 errmsg
= "Missing REPORT-IOCTL result"; break;
2558 if (++i
>= max_num_commands
) {
2559 errmsg
= "Too many ATA commands"; break;
2561 m_command_table
[i
].command
= (smart_command_set
)nc
;
2562 m_command_table
[i
].select
= matchtoi(line
, match
[5], 0); // "InputParameter=%d"
2567 if (!(state
== 1 && (int)m_command_table
[i
].command
== nc
)) {
2568 errmsg
= "Missing REPORT-IOCTL start"; break;
2570 m_command_table
[i
].retval
= matchtoi(line
, match
[7], -1); // "returned %d"
2571 m_command_table
[i
].errval
= matchtoi(line
, match
[9], 0); // "errno=%d"
2575 else if (matchcpy(cmdname
, sizeof(cmdname
), line
, match
[10])) { // "===== [%s] DATA START "
2576 // Start of sector hexdump
2577 int nc
= name2command(cmdname
);
2578 if (!(state
== (nc
== WRITE_LOG
? 1 : 2) && (int)m_command_table
[i
].command
== nc
)) {
2579 errmsg
= "Unexpected DATA START"; break;
2581 line
= nextline(line
, lineno
);
2582 char * data
= (char *)malloc(512);
2584 for (j
= 0; j
< 32; j
++) {
2586 unsigned u1
, u2
; int n1
= -1;
2587 if (!(sscanf(line
, "%3u-%3u: "
2588 "%2x %2x %2x %2x %2x %2x %2x %2x "
2589 "%2x %2x %2x %2x %2x %2x %2x %2x%n",
2591 b
+ 0, b
+ 1, b
+ 2, b
+ 3, b
+ 4, b
+ 5, b
+ 6, b
+ 7,
2592 b
+ 8, b
+ 9, b
+10, b
+11, b
+12, b
+13, b
+14, b
+15, &n1
) == 18
2593 && n1
>= 56 && u1
== j
*16 && u2
== j
*16+15))
2595 for (unsigned k
= 0; k
< 16; k
++)
2596 data
[j
*16+k
] = b
[k
];
2597 line
= nextline(line
, lineno
);
2601 errmsg
= "Incomplete sector hex dump"; break;
2603 m_command_table
[i
].data
= data
;
2604 if (nc
!= WRITE_LOG
)
2607 else if (match
[11].rm_so
> 0) { // "(En|Dis)abled status cached by OS"
2608 m_ata_identify_is_cached
= true;
2612 if (!(state
== 0 || state
== 2))
2613 errmsg
= "Missing REPORT-IOCTL result";
2615 if (!errmsg
&& i
< 0)
2616 errmsg
= "No information found";
2618 m_num_commands
= i
+1;
2619 m_next_replay_command
= 0;
2620 m_replay_out_of_sync
= false;
2624 return set_err(EIO
, "%s(%d): Syntax error: %s", pathname
, lineno
, errmsg
);
2629 // Report warnings and free command table
2630 bool parsed_ata_device::close()
2632 if (m_replay_out_of_sync
)
2633 pout("REPLAY-IOCTL: Warning: commands replayed out of sync\n");
2634 else if (m_next_replay_command
!= 0)
2635 pout("REPLAY-IOCTL: Warning: %d command(s) not replayed\n", m_num_commands
-m_next_replay_command
);
2637 for (int i
= 0; i
< m_num_commands
; i
++) {
2638 if (m_command_table
[i
].data
) {
2639 free(m_command_table
[i
].data
); m_command_table
[i
].data
= 0;
2643 m_next_replay_command
= 0;
2644 m_replay_out_of_sync
= false;
2649 bool parsed_ata_device::ata_identify_is_cached() const
2651 return m_ata_identify_is_cached
;
2655 // Simulate ATA command from command table
2656 int parsed_ata_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2658 // Find command, try round-robin if out of sync
2659 int i
= m_next_replay_command
;
2660 for (int j
= 0; ; j
++) {
2661 if (j
>= m_num_commands
) {
2662 pout("REPLAY-IOCTL: Warning: Command not found\n");
2666 if (m_command_table
[i
].command
== command
&& m_command_table
[i
].select
== select
)
2668 if (!m_replay_out_of_sync
) {
2669 m_replay_out_of_sync
= true;
2670 pout("REPLAY-IOCTL: Warning: Command #%d is out of sync\n", i
+1);
2672 if (++i
>= m_num_commands
)
2675 m_next_replay_command
= i
;
2676 if (++m_next_replay_command
>= m_num_commands
)
2677 m_next_replay_command
= 0;
2679 // Return command data
2684 case READ_THRESHOLDS
:
2686 if (m_command_table
[i
].data
)
2687 memcpy(data
, m_command_table
[i
].data
, 512);
2690 if (!(m_command_table
[i
].data
&& !memcmp(data
, m_command_table
[i
].data
, 512)))
2691 pout("REPLAY-IOCTL: Warning: WRITE LOG data does not match\n");
2693 case CHECK_POWER_MODE
:
2694 data
[0] = (char)0xff;
2699 if (m_command_table
[i
].errval
)
2700 errno
= m_command_table
[i
].errval
;
2701 return m_command_table
[i
].retval
;
2706 ata_device
* get_parsed_ata_device(smart_interface
* intf
, const char * dev_name
)
2708 return new parsed_ata_device(intf
, dev_name
);