]> git.proxmox.com Git - mirror_smartmontools-debian.git/blob - atacmds.cpp
Imported Upstream version 5.39.1+svn3060
[mirror_smartmontools-debian.git] / atacmds.cpp
1 /*
2 * atacmds.cpp
3 *
4 * Home page of code is: http://smartmontools.sourceforge.net
5 *
6 * Copyright (C) 2002-10 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2008-10 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>
10 *
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)
14 * any later version.
15 *
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.
19 *
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/
24 *
25 */
26
27 #include <stdio.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <stdlib.h>
31 #include <ctype.h>
32
33 #include "config.h"
34 #include "int64.h"
35 #include "atacmds.h"
36 #include "extern.h"
37 #include "utility.h"
38 #include "dev_ata_cmd_set.h" // for parsed_ata_device
39
40 const char * atacmds_cpp_cvsid = "$Id: atacmds.cpp 3040 2010-01-18 20:57:39Z chrfranke $"
41 ATACMDS_H_CVSID;
42
43 // for passing global control variables
44 extern smartmonctrl *con;
45
46 #define SMART_CYL_LOW 0x4F
47 #define SMART_CYL_HI 0xC2
48
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
55
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/Documents/UploadedDocuments/project/d2008r7b-ATA-3.pdf
62 // to see this.
63 #define NOVAL_0 0x0000
64 #define NOVAL_1 0xffff
65 /* word 81: minor version number */
66 #define MINOR_MAX 0x22
67 static const char * const minor_str[] = { /* word 81 value: */
68 "Device does not report version", /* 0x0000 */
69 "ATA-1 X3T9.2 781D prior to revision 4", /* 0x0001 */
70 "ATA-1 published, ANSI X3.221-1994", /* 0x0002 */
71 "ATA-1 X3T9.2 781D revision 4", /* 0x0003 */
72 "ATA-2 published, ANSI X3.279-1996", /* 0x0004 */
73 "ATA-2 X3T10 948D prior to revision 2k", /* 0x0005 */
74 "ATA-3 X3T10 2008D revision 1", /* 0x0006 */ /* SMART NOT INCLUDED */
75 "ATA-2 X3T10 948D revision 2k", /* 0x0007 */
76 "ATA-3 X3T10 2008D revision 0", /* 0x0008 */
77 "ATA-2 X3T10 948D revision 3", /* 0x0009 */
78 "ATA-3 published, ANSI X3.298-199x", /* 0x000a */
79 "ATA-3 X3T10 2008D revision 6", /* 0x000b */ /* 1st VERSION WITH SMART */
80 "ATA-3 X3T13 2008D revision 7 and 7a", /* 0x000c */
81 "ATA/ATAPI-4 X3T13 1153D revision 6", /* 0x000d */
82 "ATA/ATAPI-4 T13 1153D revision 13", /* 0x000e */
83 "ATA/ATAPI-4 X3T13 1153D revision 7", /* 0x000f */
84 "ATA/ATAPI-4 T13 1153D revision 18", /* 0x0010 */
85 "ATA/ATAPI-4 T13 1153D revision 15", /* 0x0011 */
86 "ATA/ATAPI-4 published, ANSI NCITS 317-1998", /* 0x0012 */
87 "ATA/ATAPI-5 T13 1321D revision 3", /* 0x0013 */
88 "ATA/ATAPI-4 T13 1153D revision 14", /* 0x0014 */
89 "ATA/ATAPI-5 T13 1321D revision 1", /* 0x0015 */
90 "ATA/ATAPI-5 published, ANSI NCITS 340-2000", /* 0x0016 */
91 "ATA/ATAPI-4 T13 1153D revision 17", /* 0x0017 */
92 "ATA/ATAPI-6 T13 1410D revision 0", /* 0x0018 */
93 "ATA/ATAPI-6 T13 1410D revision 3a", /* 0x0019 */
94 "ATA/ATAPI-7 T13 1532D revision 1", /* 0x001a */
95 "ATA/ATAPI-6 T13 1410D revision 2", /* 0x001b */
96 "ATA/ATAPI-6 T13 1410D revision 1", /* 0x001c */
97 "ATA/ATAPI-7 published, ANSI INCITS 397-2005",/* 0x001d */
98 "ATA/ATAPI-7 T13 1532D revision 0", /* 0x001e */
99 "reserved", /* 0x001f */
100 "reserved", /* 0x0020 */
101 "ATA/ATAPI-7 T13 1532D revision 4a", /* 0x0021 */
102 "ATA/ATAPI-6 published, ANSI INCITS 361-2002" /* 0x0022 */
103 };
104
105 // NOTE ATA/ATAPI-4 REV 4 was the LAST revision where the device
106 // attribute structures were NOT completely vendor specific. So any
107 // disk that is ATA/ATAPI-4 or above can not be trusted to show the
108 // vendor values in sensible format.
109
110 // Negative values below are because it doesn't support SMART
111 static const int actual_ver[] = {
112 /* word 81 value: */
113 0, /* 0x0000 WARNING: */
114 1, /* 0x0001 WARNING: */
115 1, /* 0x0002 WARNING: */
116 1, /* 0x0003 WARNING: */
117 2, /* 0x0004 WARNING: This array */
118 2, /* 0x0005 WARNING: corresponds */
119 -3, /*<== */ /* 0x0006 WARNING: *exactly* */
120 2, /* 0x0007 WARNING: to the ATA/ */
121 -3, /*<== */ /* 0x0008 WARNING: ATAPI version */
122 2, /* 0x0009 WARNING: listed in */
123 3, /* 0x000a WARNING: the */
124 3, /* 0x000b WARNING: minor_str */
125 3, /* 0x000c WARNING: array */
126 4, /* 0x000d WARNING: above. */
127 4, /* 0x000e WARNING: */
128 4, /* 0x000f WARNING: If you change */
129 4, /* 0x0010 WARNING: that one, */
130 4, /* 0x0011 WARNING: change this one */
131 4, /* 0x0012 WARNING: too!!! */
132 5, /* 0x0013 WARNING: */
133 4, /* 0x0014 WARNING: */
134 5, /* 0x0015 WARNING: */
135 5, /* 0x0016 WARNING: */
136 4, /* 0x0017 WARNING: */
137 6, /* 0x0018 WARNING: */
138 6, /* 0x0019 WARNING: */
139 7, /* 0x001a WARNING: */
140 6, /* 0x001b WARNING: */
141 6, /* 0x001c WARNING: */
142 7, /* 0x001d WARNING: */
143 7, /* 0x001e WARNING: */
144 0, /* 0x001f WARNING: */
145 0, /* 0x0020 WARNING: */
146 7, /* 0x0021 WARNING: */
147 6 /* 0x0022 WARNING: */
148 };
149
150 // Get ID and increase flag of current pending or offline
151 // uncorrectable attribute.
152 unsigned char get_unc_attr_id(bool offline, const ata_vendor_attr_defs & defs,
153 bool & increase)
154 {
155 unsigned char id = (!offline ? 197 : 198);
156 increase = !!(defs[id].flags & ATTRFLAG_INCREASING);
157 return id;
158 }
159
160 #if 0 // TODO: never used
161 // This are the meanings of the Self-test failure checkpoint byte.
162 // This is in the self-test log at offset 4 bytes into the self-test
163 // descriptor and in the SMART READ DATA structure at byte offset
164 // 371. These codes are not well documented. The meanings returned by
165 // this routine are used (at least) by Maxtor and IBM. Returns NULL if
166 // not recognized. Currently the maximum length is 15 bytes.
167 const char *SelfTestFailureCodeName(unsigned char which){
168
169 switch (which) {
170 case 0:
171 return "Write_Test";
172 case 1:
173 return "Servo_Basic";
174 case 2:
175 return "Servo_Random";
176 case 3:
177 return "G-list_Scan";
178 case 4:
179 return "Handling_Damage";
180 case 5:
181 return "Read_Scan";
182 default:
183 return NULL;
184 }
185 }
186 #endif
187
188
189 // Table of raw print format names
190 struct format_name_entry
191 {
192 const char * name;
193 ata_attr_raw_format format;
194 };
195
196 const format_name_entry format_names[] = {
197 {"raw8" , RAWFMT_RAW8},
198 {"raw16" , RAWFMT_RAW16},
199 {"raw48" , RAWFMT_RAW48},
200 {"hex48" , RAWFMT_HEX48},
201 {"raw64" , RAWFMT_RAW64},
202 {"hex64" , RAWFMT_HEX64},
203 {"raw16(raw16)" , RAWFMT_RAW16_OPT_RAW16},
204 {"raw16(avg16)" , RAWFMT_RAW16_OPT_AVG16},
205 {"raw24/raw24" , RAWFMT_RAW24_RAW24},
206 {"sec2hour" , RAWFMT_SEC2HOUR},
207 {"min2hour" , RAWFMT_MIN2HOUR},
208 {"halfmin2hour" , RAWFMT_HALFMIN2HOUR},
209 {"tempminmax" , RAWFMT_TEMPMINMAX},
210 {"temp10x" , RAWFMT_TEMP10X},
211 };
212
213 const unsigned num_format_names = sizeof(format_names)/sizeof(format_names[0]);
214
215 // Table to map old to new '-v' option arguments
216 const char * map_old_vendor_opts[][2] = {
217 { "9,halfminutes" , "9,halfmin2hour,Power_On_Half_Minutes"},
218 { "9,minutes" , "9,min2hour,Power_On_Minutes"},
219 { "9,seconds" , "9,sec2hour,Power_On_Seconds"},
220 { "9,temp" , "9,tempminmax,Temperature_Celsius"},
221 {"192,emergencyretractcyclect" , "192,raw48,Emerg_Retract_Cycle_Ct"},
222 {"193,loadunload" , "193,raw24/raw24"},
223 {"194,10xCelsius" , "194,temp10x,Temperature_Celsius_x10"},
224 {"194,unknown" , "194,raw48,Unknown_Attribute"},
225 {"197,increasing" , "197,raw48+,Total_Pending_Sectors"}, // '+' sets flag
226 {"198,offlinescanuncsectorct" , "198,raw48,Offline_Scan_UNC_SectCt"},
227 {"198,increasing" , "198,raw48+,Total_Offl_Uncorrectabl"}, // '+' sets flag
228 {"200,writeerrorcount" , "200,raw48,Write_Error_Count"},
229 {"201,detectedtacount" , "201,raw48,Detected_TA_Count"},
230 {"220,temp" , "220,raw48,Temperature_Celsius"},
231 };
232
233 const unsigned num_old_vendor_opts = sizeof(map_old_vendor_opts)/sizeof(map_old_vendor_opts[0]);
234
235 // Parse vendor attribute display def (-v option).
236 // Return false on error.
237 bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
238 ata_vendor_def_prior priority)
239 {
240 // Map old -> new options
241 unsigned i;
242 for (i = 0; i < num_old_vendor_opts; i++) {
243 if (!strcmp(opt, map_old_vendor_opts[i][0])) {
244 opt = map_old_vendor_opts[i][1];
245 break;
246 }
247 }
248
249 // Parse option
250 int len = strlen(opt);
251 int id = 0, n1 = -1, n2 = -1;
252 char fmtname[32+1], attrname[32+1];
253 if (opt[0] == 'N') {
254 // "N,format"
255 if (!( sscanf(opt, "N,%32[^,]%n,%32[^,]%n", fmtname, &n1, attrname, &n2) >= 1
256 && (n1 == len || n2 == len)))
257 return false;
258 }
259 else {
260 // "id,format[+][,name]"
261 if (!( sscanf(opt, "%d,%32[^,]%n,%32[^,]%n", &id, fmtname, &n1, attrname, &n2) >= 2
262 && 1 <= id && id <= 255 && (n1 == len || n2 == len)))
263 return false;
264 }
265 if (n1 == len)
266 attrname[0] = 0;
267
268 unsigned flags = 0;
269 // For "-v 19[78],increasing" above
270 if (fmtname[strlen(fmtname)-1] == '+') {
271 fmtname[strlen(fmtname)-1] = 0;
272 flags = ATTRFLAG_INCREASING;
273 }
274
275 // Split "format[:byteorder]"
276 char byteorder[8+1] = "";
277 if (strchr(fmtname, ':')) {
278 if (!( sscanf(fmtname, "%*[^:]%n:%8[012345rvwz]%n", &n1, byteorder, &n2) >= 1
279 && n2 == (int)strlen(fmtname)))
280 return false;
281 fmtname[n1] = 0;
282 if (strchr(byteorder, 'v'))
283 flags |= (ATTRFLAG_NO_NORMVAL|ATTRFLAG_NO_WORSTVAL);
284 if (strchr(byteorder, 'w'))
285 flags |= ATTRFLAG_NO_WORSTVAL;
286 }
287
288 // Find format name
289 for (i = 0; ; i++) {
290 if (i >= num_format_names)
291 return false; // Not found
292 if (!strcmp(fmtname, format_names[i].name))
293 break;
294 }
295 ata_attr_raw_format format = format_names[i].format;
296
297 // 64-bit formats use the normalized and worst value bytes.
298 if (!*byteorder && (format == RAWFMT_RAW64 || format == RAWFMT_HEX64))
299 flags |= (ATTRFLAG_NO_NORMVAL|ATTRFLAG_NO_WORSTVAL);
300
301 if (!id) {
302 // "N,format" -> set format for all entries
303 for (i = 0; i < MAX_ATTRIBUTE_NUM; i++) {
304 if (defs[i].priority >= priority)
305 continue;
306 if (attrname[0])
307 defs[i].name = attrname;
308 defs[i].priority = priority;
309 defs[i].raw_format = format;
310 defs[i].flags = flags;
311 strcpy(defs[i].byteorder, byteorder);
312 }
313 }
314 else if (defs[id].priority <= priority) {
315 // "id,format[,name]"
316 if (attrname[0])
317 defs[id].name = attrname;
318 defs[id].raw_format = format;
319 defs[id].priority = priority;
320 defs[id].flags = flags;
321 strcpy(defs[id].byteorder, byteorder);
322 }
323
324 return true;
325 }
326
327
328 // Return a multiline string containing a list of valid arguments for
329 // parse_attribute_def(). The strings are preceeded by tabs and followed
330 // (except for the last) by newlines.
331 std::string create_vendor_attribute_arg_list()
332 {
333 std::string s;
334 unsigned i;
335 for (i = 0; i < num_format_names; i++)
336 s += strprintf("%s\tN,%s[:012345rvwz][,ATTR_NAME]",
337 (i>0 ? "\n" : ""), format_names[i].name);
338 for (i = 0; i < num_old_vendor_opts; i++)
339 s += strprintf("\n\t%s", map_old_vendor_opts[i][0]);
340 return s;
341 }
342
343 // swap two bytes. Point to low address
344 void swap2(char *location){
345 char tmp=*location;
346 *location=*(location+1);
347 *(location+1)=tmp;
348 return;
349 }
350
351 // swap four bytes. Point to low address
352 void swap4(char *location){
353 char tmp=*location;
354 *location=*(location+3);
355 *(location+3)=tmp;
356 swap2(location+1);
357 return;
358 }
359
360 // swap eight bytes. Points to low address
361 void swap8(char *location){
362 char tmp=*location;
363 *location=*(location+7);
364 *(location+7)=tmp;
365 tmp=*(location+1);
366 *(location+1)=*(location+6);
367 *(location+6)=tmp;
368 swap4(location+2);
369 return;
370 }
371
372 // Invalidate serial number and adjust checksum in IDENTIFY data
373 static void invalidate_serno(ata_identify_device * id){
374 unsigned char sum = 0;
375 for (unsigned i = 0; i < sizeof(id->serial_no); i++) {
376 sum += id->serial_no[i]; sum -= id->serial_no[i] = 'X';
377 }
378 #ifndef __NetBSD__
379 bool must_swap = !!isbigendian();
380 if (must_swap)
381 swapx(id->words088_255+255-88);
382 #endif
383 if ((id->words088_255[255-88] & 0x00ff) == 0x00a5)
384 id->words088_255[255-88] += sum << 8;
385 #ifndef __NetBSD__
386 if (must_swap)
387 swapx(id->words088_255+255-88);
388 #endif
389 }
390
391 static const char * const commandstrings[]={
392 "SMART ENABLE",
393 "SMART DISABLE",
394 "SMART AUTOMATIC ATTRIBUTE SAVE",
395 "SMART IMMEDIATE OFFLINE",
396 "SMART AUTO OFFLINE",
397 "SMART STATUS",
398 "SMART STATUS CHECK",
399 "SMART READ ATTRIBUTE VALUES",
400 "SMART READ ATTRIBUTE THRESHOLDS",
401 "SMART READ LOG",
402 "IDENTIFY DEVICE",
403 "IDENTIFY PACKET DEVICE",
404 "CHECK POWER MODE",
405 "SMART WRITE LOG",
406 "WARNING (UNDEFINED COMMAND -- CONTACT DEVELOPERS AT " PACKAGE_BUGREPORT ")\n"
407 };
408
409
410 static const char * preg(const ata_register & r, char * buf)
411 {
412 if (!r.is_set())
413 //return "n/a ";
414 return "....";
415 sprintf(buf, "0x%02x", r.val()); return buf;
416 }
417
418 void print_regs(const char * prefix, const ata_in_regs & r, const char * suffix = "\n")
419 {
420 char bufs[7][4+1+13];
421 pout("%s FR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, CMD=%s%s", prefix,
422 preg(r.features, bufs[0]), preg(r.sector_count, bufs[1]), preg(r.lba_low, bufs[2]),
423 preg(r.lba_mid, bufs[3]), preg(r.lba_high, bufs[4]), preg(r.device, bufs[5]),
424 preg(r.command, bufs[6]), suffix);
425 }
426
427 void print_regs(const char * prefix, const ata_out_regs & r, const char * suffix = "\n")
428 {
429 char bufs[7][4+1+13];
430 pout("%sERR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, STS=%s%s", prefix,
431 preg(r.error, bufs[0]), preg(r.sector_count, bufs[1]), preg(r.lba_low, bufs[2]),
432 preg(r.lba_mid, bufs[3]), preg(r.lba_high, bufs[4]), preg(r.device, bufs[5]),
433 preg(r.status, bufs[6]), suffix);
434 }
435
436 static void prettyprint(const unsigned char *p, const char *name){
437 pout("\n===== [%s] DATA START (BASE-16) =====\n", name);
438 for (int i=0; i<512; i+=16, p+=16)
439 #define P(n) (isprint((int)(p[n]))?(int)(p[n]):'.')
440 // print complete line to avoid slow tty output and extra lines in syslog.
441 pout("%03d-%03d: %02x %02x %02x %02x %02x %02x %02x %02x "
442 "%02x %02x %02x %02x %02x %02x %02x %02x"
443 " |%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c|"
444 "%c",
445 i, i+16-1,
446 p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
447 p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15],
448 P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
449 P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15),
450 '\n');
451 #undef P
452 pout("===== [%s] DATA END (512 Bytes) =====\n\n", name);
453 }
454
455 // This function provides the pretty-print reporting for SMART
456 // commands: it implements the various -r "reporting" options for ATA
457 // ioctls.
458 int smartcommandhandler(ata_device * device, smart_command_set command, int select, char *data){
459 // TODO: Rework old stuff below
460 // This conditional is true for commands that return data
461 int getsdata=(command==PIDENTIFY ||
462 command==IDENTIFY ||
463 command==READ_LOG ||
464 command==READ_THRESHOLDS ||
465 command==READ_VALUES ||
466 command==CHECK_POWER_MODE);
467
468 int sendsdata=(command==WRITE_LOG);
469
470 // If reporting is enabled, say what the command will be before it's executed
471 if (con->reportataioctl){
472 // conditional is true for commands that use parameters
473 int usesparam=(command==READ_LOG ||
474 command==AUTO_OFFLINE ||
475 command==AUTOSAVE ||
476 command==IMMEDIATE_OFFLINE ||
477 command==WRITE_LOG);
478
479 pout("\nREPORT-IOCTL: Device=%s Command=%s", device->get_dev_name(), commandstrings[command]);
480 if (usesparam)
481 pout(" InputParameter=%d\n", select);
482 else
483 pout("\n");
484 }
485
486 if ((getsdata || sendsdata) && !data){
487 pout("REPORT-IOCTL: Unable to execute command %s : data destination address is NULL\n", commandstrings[command]);
488 return -1;
489 }
490
491 // The reporting is cleaner, and we will find coding bugs faster, if
492 // the commands that failed clearly return empty (zeroed) data
493 // structures
494 if (getsdata) {
495 if (command==CHECK_POWER_MODE)
496 data[0]=0;
497 else
498 memset(data, '\0', 512);
499 }
500
501
502 // if requested, pretty-print the input data structure
503 if (con->reportataioctl>1 && sendsdata)
504 //pout("REPORT-IOCTL: Device=%s Command=%s\n", device->get_dev_name(), commandstrings[command]);
505 prettyprint((unsigned char *)data, commandstrings[command]);
506
507 // now execute the command
508 int retval = -1;
509 {
510 ata_cmd_in in;
511 // Set common register values
512 switch (command) {
513 default: // SMART commands
514 in.in_regs.command = ATA_SMART_CMD;
515 in.in_regs.lba_high = SMART_CYL_HI; in.in_regs.lba_mid = SMART_CYL_LOW;
516 break;
517 case IDENTIFY: case PIDENTIFY: case CHECK_POWER_MODE: // Non SMART commands
518 break;
519 }
520 // Set specific values
521 switch (command) {
522 case IDENTIFY:
523 in.in_regs.command = ATA_IDENTIFY_DEVICE;
524 in.set_data_in(data, 1);
525 break;
526 case PIDENTIFY:
527 in.in_regs.command = ATA_IDENTIFY_PACKET_DEVICE;
528 in.set_data_in(data, 1);
529 break;
530 case CHECK_POWER_MODE:
531 in.in_regs.command = ATA_CHECK_POWER_MODE;
532 in.out_needed.sector_count = true; // Powermode returned here
533 break;
534 case READ_VALUES:
535 in.in_regs.features = ATA_SMART_READ_VALUES;
536 in.set_data_in(data, 1);
537 break;
538 case READ_THRESHOLDS:
539 in.in_regs.features = ATA_SMART_READ_THRESHOLDS;
540 in.in_regs.lba_low = 1; // TODO: CORRECT ???
541 in.set_data_in(data, 1);
542 break;
543 case READ_LOG:
544 in.in_regs.features = ATA_SMART_READ_LOG_SECTOR;
545 in.in_regs.lba_low = select;
546 in.set_data_in(data, 1);
547 break;
548 case WRITE_LOG:
549 in.in_regs.features = ATA_SMART_WRITE_LOG_SECTOR;
550 in.in_regs.lba_low = select;
551 in.set_data_out(data, 1);
552 break;
553 case ENABLE:
554 in.in_regs.features = ATA_SMART_ENABLE;
555 in.in_regs.lba_low = 1; // TODO: CORRECT ???
556 break;
557 case DISABLE:
558 in.in_regs.features = ATA_SMART_DISABLE;
559 in.in_regs.lba_low = 1; // TODO: CORRECT ???
560 break;
561 case STATUS_CHECK:
562 in.out_needed.lba_high = in.out_needed.lba_mid = true; // Status returned here
563 case STATUS:
564 in.in_regs.features = ATA_SMART_STATUS;
565 break;
566 case AUTO_OFFLINE:
567 in.in_regs.features = ATA_SMART_AUTO_OFFLINE;
568 in.in_regs.sector_count = select; // Caution: Non-DATA command!
569 break;
570 case AUTOSAVE:
571 in.in_regs.features = ATA_SMART_AUTOSAVE;
572 in.in_regs.sector_count = select; // Caution: Non-DATA command!
573 break;
574 case IMMEDIATE_OFFLINE:
575 in.in_regs.features = ATA_SMART_IMMEDIATE_OFFLINE;
576 in.in_regs.lba_low = select;
577 break;
578 default:
579 pout("Unrecognized command %d in smartcommandhandler()\n"
580 "Please contact " PACKAGE_BUGREPORT "\n", command);
581 device->set_err(ENOSYS);
582 errno = ENOSYS;
583 return -1;
584 }
585
586 if (con->reportataioctl)
587 print_regs(" Input: ", in.in_regs,
588 (in.direction==ata_cmd_in::data_in ? " IN\n":
589 in.direction==ata_cmd_in::data_out ? " OUT\n":"\n"));
590
591 ata_cmd_out out;
592 bool ok = device->ata_pass_through(in, out);
593
594 if (con->reportataioctl && out.out_regs.is_set())
595 print_regs(" Output: ", out.out_regs);
596
597 if (ok) switch (command) {
598 default:
599 retval = 0;
600 break;
601 case CHECK_POWER_MODE:
602 data[0] = out.out_regs.sector_count;
603 retval = 0;
604 break;
605 case STATUS_CHECK:
606 // Cyl low and Cyl high unchanged means "Good SMART status"
607 if ((out.out_regs.lba_high == SMART_CYL_HI) &&
608 (out.out_regs.lba_mid == SMART_CYL_LOW))
609 retval = 0;
610 // These values mean "Bad SMART status"
611 else if ((out.out_regs.lba_high == SRET_STATUS_HI_EXCEEDED) &&
612 (out.out_regs.lba_mid == SRET_STATUS_MID_EXCEEDED))
613 retval = 1;
614 else if (out.out_regs.lba_mid == SMART_CYL_LOW) {
615 retval = 0;
616 if (con->reportataioctl)
617 pout("SMART STATUS RETURN: half healthy response sequence, "
618 "probable SAT/USB truncation\n");
619 } else if (out.out_regs.lba_mid == SRET_STATUS_MID_EXCEEDED) {
620 retval = 1;
621 if (con->reportataioctl)
622 pout("SMART STATUS RETURN: half unhealthy response sequence, "
623 "probable SAT/USB truncation\n");
624 } else {
625 // We haven't gotten output that makes sense; print out some debugging info
626 pout("Error 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 errno = EIO;
631 retval = -1;
632 }
633 break;
634 }
635 }
636
637 // If requested, invalidate serial number before any printing is done
638 if ((command == IDENTIFY || command == PIDENTIFY) && !retval && con->dont_print_serial)
639 invalidate_serno((ata_identify_device *)data);
640
641 // If reporting is enabled, say what output was produced by the command
642 if (con->reportataioctl){
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());
647 else
648 pout("REPORT-IOCTL: Device=%s Command=%s returned %d\n",
649 device->get_dev_name(), commandstrings[command], retval);
650
651 // if requested, pretty-print the output data structure
652 if (con->reportataioctl>1 && getsdata) {
653 if (command==CHECK_POWER_MODE)
654 pout("Sector Count Register (BASE-16): %02x\n", (unsigned char)(*data));
655 else
656 prettyprint((unsigned char *)data, commandstrings[command]);
657 }
658 }
659
660 errno = device->get_errno(); // TODO: Callers should not call syserror()
661 return retval;
662 }
663
664 // Get number of sectors from IDENTIFY sector. If the drive doesn't
665 // support LBA addressing or has no user writable sectors
666 // (eg, CDROM or DVD) then routine returns zero.
667 uint64_t get_num_sectors(const ata_identify_device * drive)
668 {
669 unsigned short command_set_2 = drive->command_set_2;
670 unsigned short capabilities_0 = drive->words047_079[49-47];
671 unsigned short sects_16 = drive->words047_079[60-47];
672 unsigned short sects_32 = drive->words047_079[61-47];
673 unsigned short lba_16 = drive->words088_255[100-88];
674 unsigned short lba_32 = drive->words088_255[101-88];
675 unsigned short lba_48 = drive->words088_255[102-88];
676 unsigned short lba_64 = drive->words088_255[103-88];
677
678 // LBA support?
679 if (!(capabilities_0 & 0x0200))
680 return 0; // No
681
682 // if drive supports LBA addressing, determine 32-bit LBA capacity
683 uint64_t lba32 = (unsigned int)sects_32 << 16 |
684 (unsigned int)sects_16 << 0 ;
685
686 uint64_t lba64 = 0;
687 // if drive supports 48-bit addressing, determine THAT capacity
688 if ((command_set_2 & 0xc000) == 0x4000 && (command_set_2 & 0x0400))
689 lba64 = (uint64_t)lba_64 << 48 |
690 (uint64_t)lba_48 << 32 |
691 (uint64_t)lba_32 << 16 |
692 (uint64_t)lba_16 << 0 ;
693
694 // return the larger of the two possible capacities
695 return (lba32 > lba64 ? lba32 : lba64);
696 }
697
698 // This function computes the checksum of a single disk sector (512
699 // bytes). Returns zero if checksum is OK, nonzero if the checksum is
700 // incorrect. The size (512) is correct for all SMART structures.
701 unsigned char checksum(const void * data)
702 {
703 unsigned char sum = 0;
704 for (int i = 0; i < 512; i++)
705 sum += ((const unsigned char *)data)[i];
706 return sum;
707 }
708
709 // Copies n bytes (or n-1 if n is odd) from in to out, but swaps adjacents
710 // bytes.
711 static void swapbytes(char * out, const char * in, size_t n)
712 {
713 for (size_t i = 0; i < n; i += 2) {
714 out[i] = in[i+1];
715 out[i+1] = in[i];
716 }
717 }
718
719 // Copies in to out, but removes leading and trailing whitespace.
720 static void trim(char * out, const char * in)
721 {
722 // Find the first non-space character (maybe none).
723 int first = -1;
724 int i;
725 for (i = 0; in[i]; i++)
726 if (!isspace((int)in[i])) {
727 first = i;
728 break;
729 }
730
731 if (first == -1) {
732 // There are no non-space characters.
733 out[0] = '\0';
734 return;
735 }
736
737 // Find the last non-space character.
738 for (i = strlen(in)-1; i >= first && isspace((int)in[i]); i--)
739 ;
740 int last = i;
741
742 strncpy(out, in+first, last-first+1);
743 out[last-first+1] = '\0';
744 }
745
746 // Convenience function for formatting strings from ata_identify_device
747 void format_ata_string(char * out, const char * in, int n, bool fix_swap)
748 {
749 bool must_swap = !fix_swap;
750 #ifdef __NetBSD__
751 /* NetBSD kernel delivers IDENTIFY data in host byte order (but all else is LE) */
752 if (isbigendian())
753 must_swap = !must_swap;
754 #endif
755
756 char tmp[65];
757 n = n > 64 ? 64 : n;
758 if (!must_swap)
759 strncpy(tmp, in, n);
760 else
761 swapbytes(tmp, in, n);
762 tmp[n] = '\0';
763 trim(out, tmp);
764 }
765
766 // returns -1 if command fails or the device is in Sleep mode, else
767 // value of Sector Count register. Sector Count result values:
768 // 00h device is in Standby mode.
769 // 80h device is in Idle mode.
770 // FFh device is in Active mode or Idle mode.
771
772 int ataCheckPowerMode(ata_device * device) {
773 unsigned char result;
774
775 if ((smartcommandhandler(device, CHECK_POWER_MODE, 0, (char *)&result)))
776 return -1;
777
778 if (result!=0 && result!=0x80 && result!=0xff)
779 pout("ataCheckPowerMode(): ATA CHECK POWER MODE returned unknown Sector Count Register value %02x\n", result);
780
781 return (int)result;
782 }
783
784
785
786
787 // Reads current Device Identity info (512 bytes) into buf. Returns 0
788 // if all OK. Returns -1 if no ATA Device identity can be
789 // established. Returns >0 if Device is ATA Packet Device (not SMART
790 // capable). The value of the integer helps identify the type of
791 // Packet device, which is useful so that the user can connect the
792 // formal device number with whatever object is inside their computer.
793 int ataReadHDIdentity (ata_device * device, struct ata_identify_device *buf){
794 unsigned short *rawshort=(unsigned short *)buf;
795 unsigned char *rawbyte =(unsigned char *)buf;
796
797 // See if device responds either to IDENTIFY DEVICE or IDENTIFY
798 // PACKET DEVICE
799 if ((smartcommandhandler(device, IDENTIFY, 0, (char *)buf))){
800 if (smartcommandhandler(device, PIDENTIFY, 0, (char *)buf)){
801 return -1;
802 }
803 }
804
805 #ifndef __NetBSD__
806 // if machine is big-endian, swap byte order as needed
807 // NetBSD kernel delivers IDENTIFY data in host byte order
808 if (isbigendian()){
809 int i;
810
811 // swap various capability words that are needed
812 for (i=0; i<33; i++)
813 swap2((char *)(buf->words047_079+i));
814
815 for (i=80; i<=87; i++)
816 swap2((char *)(rawshort+i));
817
818 for (i=0; i<168; i++)
819 swap2((char *)(buf->words088_255+i));
820 }
821 #endif
822
823 // If there is a checksum there, validate it
824 if ((rawshort[255] & 0x00ff) == 0x00a5 && checksum(rawbyte))
825 checksumwarning("Drive Identity Structure");
826
827 // If this is a PACKET DEVICE, return device type
828 if (rawbyte[1] & 0x80)
829 return 1+(rawbyte[1] & 0x1f);
830
831 // Not a PACKET DEVICE
832 return 0;
833 }
834
835 // Returns ATA version as an integer, and a pointer to a string
836 // describing which revision. Note that Revision 0 of ATA-3 does NOT
837 // support SMART. For this one case we return -3 rather than +3 as
838 // the version number. See notes above.
839 int ataVersionInfo(const char ** description, const ata_identify_device * drive, unsigned short * minor)
840 {
841 // check that arrays at the top of this file are defined
842 // consistently
843 if (sizeof(minor_str) != sizeof(char *)*(1+MINOR_MAX)){
844 pout("Internal error in ataVersionInfo(). minor_str[] size %d\n"
845 "is not consistent with value of MINOR_MAX+1 = %d\n",
846 (int)(sizeof(minor_str)/sizeof(char *)), MINOR_MAX+1);
847 fflush(NULL);
848 abort();
849 }
850 if (sizeof(actual_ver) != sizeof(int)*(1+MINOR_MAX)){
851 pout("Internal error in ataVersionInfo(). actual_ver[] size %d\n"
852 "is not consistent with value of MINOR_MAX = %d\n",
853 (int)(sizeof(actual_ver)/sizeof(int)), MINOR_MAX+1);
854 fflush(NULL);
855 abort();
856 }
857
858 // get major and minor ATA revision numbers
859 unsigned short major = drive->major_rev_num;
860 *minor=drive->minor_rev_num;
861
862 // First check if device has ANY ATA version information in it
863 if (major==NOVAL_0 || major==NOVAL_1) {
864 *description=NULL;
865 return 0; // No info found
866 }
867
868 // The minor revision number has more information - try there first
869 if (*minor && (*minor<=MINOR_MAX)){
870 int std = actual_ver[*minor];
871 if (std) {
872 *description=minor_str[*minor];
873 return std;
874 }
875 }
876
877 // Try new ATA-8 minor revision numbers (Table 31 of T13/1699-D Revision 6)
878 // (not in actual_ver/minor_str to avoid large sparse tables)
879 const char *desc;
880 switch (*minor) {
881 case 0x0027: desc = "ATA-8-ACS revision 3c"; break;
882 case 0x0028: desc = "ATA-8-ACS revision 6"; break;
883 case 0x0029: desc = "ATA-8-ACS revision 4"; break;
884 case 0x0033: desc = "ATA-8-ACS revision 3e"; break;
885 case 0x0039: desc = "ATA-8-ACS revision 4c"; break;
886 case 0x0042: desc = "ATA-8-ACS revision 3f"; break;
887 case 0x0052: desc = "ATA-8-ACS revision 3b"; break;
888 case 0x0107: desc = "ATA-8-ACS revision 2d"; break;
889 default: desc = 0; break;
890 }
891 if (desc) {
892 *description = desc;
893 return 8;
894 }
895
896 // HDPARM has a very complicated algorithm from here on. Since SMART only
897 // exists on ATA-3 and later standards, let's punt on this. If you don't
898 // like it, please fix it. The code's in CVS.
899 int i;
900 for (i=15; i>0; i--)
901 if (major & (0x1<<i))
902 break;
903
904 *description=NULL;
905 if (i==0)
906 return 1;
907 else
908 return i;
909 }
910
911 // returns 1 if SMART supported, 0 if SMART unsupported, -1 if can't tell
912 int ataSmartSupport(const ata_identify_device * drive)
913 {
914 unsigned short word82=drive->command_set_1;
915 unsigned short word83=drive->command_set_2;
916
917 // check if words 82/83 contain valid info
918 if ((word83>>14) == 0x01)
919 // return value of SMART support bit
920 return word82 & 0x0001;
921
922 // since we can're rely on word 82, we don't know if SMART supported
923 return -1;
924 }
925
926 // returns 1 if SMART enabled, 0 if SMART disabled, -1 if can't tell
927 int ataIsSmartEnabled(const ata_identify_device * drive)
928 {
929 unsigned short word85=drive->cfs_enable_1;
930 unsigned short word87=drive->csf_default;
931
932 // check if words 85/86/87 contain valid info
933 if ((word87>>14) == 0x01)
934 // return value of SMART enabled bit
935 return word85 & 0x0001;
936
937 // Since we can't rely word85, we don't know if SMART is enabled.
938 return -1;
939 }
940
941
942 // Reads SMART attributes into *data
943 int ataReadSmartValues(ata_device * device, struct ata_smart_values *data){
944
945 if (smartcommandhandler(device, READ_VALUES, 0, (char *)data)){
946 syserror("Error SMART Values Read failed");
947 return -1;
948 }
949
950 // compute checksum
951 if (checksum(data))
952 checksumwarning("SMART Attribute Data Structure");
953
954 // swap endian order if needed
955 if (isbigendian()){
956 int i;
957 swap2((char *)&(data->revnumber));
958 swap2((char *)&(data->total_time_to_complete_off_line));
959 swap2((char *)&(data->smart_capability));
960 for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++){
961 struct ata_smart_attribute *x=data->vendor_attributes+i;
962 swap2((char *)&(x->flags));
963 }
964 }
965
966 return 0;
967 }
968
969
970 // This corrects some quantities that are byte reversed in the SMART
971 // SELF TEST LOG
972 static void fixsamsungselftestlog(ata_smart_selftestlog * data)
973 {
974 // bytes 508/509 (numbered from 0) swapped (swap of self-test index
975 // with one byte of reserved.
976 swap2((char *)&(data->mostrecenttest));
977
978 // LBA low register (here called 'selftestnumber", containing
979 // information about the TYPE of the self-test) is byte swapped with
980 // Self-test execution status byte. These are bytes N, N+1 in the
981 // entries.
982 for (int i = 0; i < 21; i++)
983 swap2((char *)&(data->selftest_struct[i].selftestnumber));
984
985 return;
986 }
987
988 // Reads the Self Test Log (log #6)
989 int ataReadSelfTestLog (ata_device * device, ata_smart_selftestlog * data,
990 unsigned char fix_firmwarebug)
991 {
992
993 // get data from device
994 if (smartcommandhandler(device, READ_LOG, 0x06, (char *)data)){
995 syserror("Error SMART Error Self-Test Log Read failed");
996 return -1;
997 }
998
999 // compute its checksum, and issue a warning if needed
1000 if (checksum(data))
1001 checksumwarning("SMART Self-Test Log Structure");
1002
1003 // fix firmware bugs in self-test log
1004 if (fix_firmwarebug == FIX_SAMSUNG)
1005 fixsamsungselftestlog(data);
1006
1007 // swap endian order if needed
1008 if (isbigendian()){
1009 int i;
1010 swap2((char*)&(data->revnumber));
1011 for (i=0; i<21; i++){
1012 struct ata_smart_selftestlog_struct *x=data->selftest_struct+i;
1013 swap2((char *)&(x->timestamp));
1014 swap4((char *)&(x->lbafirstfailure));
1015 }
1016 }
1017
1018 return 0;
1019 }
1020
1021 // Print checksum warning for multi sector log
1022 static void check_multi_sector_sum(const void * data, unsigned nsectors, const char * msg)
1023 {
1024 unsigned errs = 0;
1025 for (unsigned i = 0; i < nsectors; i++) {
1026 if (checksum((const unsigned char *)data + i*512))
1027 errs++;
1028 }
1029 if (errs > 0) {
1030 if (nsectors == 1)
1031 checksumwarning(msg);
1032 else
1033 checksumwarning(strprintf("%s (%u/%u)", msg, errs, nsectors).c_str());
1034 }
1035 }
1036
1037 // Read SMART Extended Self-test Log
1038 bool ataReadExtSelfTestLog(ata_device * device, ata_smart_extselftestlog * log,
1039 unsigned nsectors)
1040 {
1041 if (!ataReadLogExt(device, 0x07, 0x00, 0, log, nsectors))
1042 return false;
1043
1044 check_multi_sector_sum(log, nsectors, "SMART Extended Self-test Log Structure");
1045
1046 if (isbigendian()) {
1047 swapx(&log->log_desc_index);
1048 for (unsigned i = 0; i < nsectors; i++) {
1049 for (unsigned j = 0; j < 19; j++)
1050 swapx(&log->log_descs[i].timestamp);
1051 }
1052 }
1053 return true;
1054 }
1055
1056
1057 // Read GP Log page(s)
1058 bool ataReadLogExt(ata_device * device, unsigned char logaddr,
1059 unsigned char features, unsigned page,
1060 void * data, unsigned nsectors)
1061 {
1062 ata_cmd_in in;
1063 in.in_regs.command = ATA_READ_LOG_EXT;
1064 in.in_regs.features = features; // log specific
1065 in.set_data_in_48bit(data, nsectors);
1066 in.in_regs.lba_low = logaddr;
1067 in.in_regs.lba_mid_16 = page;
1068
1069 if (!device->ata_pass_through(in)) { // TODO: Debug output
1070 if (nsectors <= 1) {
1071 pout("ATA_READ_LOG_EXT (addr=0x%02x:0x%02x, page=%u, n=%u) failed: %s\n",
1072 logaddr, features, page, nsectors, device->get_errmsg());
1073 return false;
1074 }
1075
1076 // Recurse to retry with single sectors,
1077 // multi-sector reads may not be supported by ioctl.
1078 for (unsigned i = 0; i < nsectors; i++) {
1079 if (!ataReadLogExt(device, logaddr,
1080 features, page + i,
1081 (char *)data + 512*i, 1))
1082 return false;
1083 }
1084 }
1085
1086 return true;
1087 }
1088
1089 // Read SMART Log page(s)
1090 bool ataReadSmartLog(ata_device * device, unsigned char logaddr,
1091 void * data, unsigned nsectors)
1092 {
1093 ata_cmd_in in;
1094 in.in_regs.command = ATA_SMART_CMD;
1095 in.in_regs.features = ATA_SMART_READ_LOG_SECTOR;
1096 in.set_data_in(data, nsectors);
1097 in.in_regs.lba_high = SMART_CYL_HI;
1098 in.in_regs.lba_mid = SMART_CYL_LOW;
1099 in.in_regs.lba_low = logaddr;
1100
1101 if (!device->ata_pass_through(in)) { // TODO: Debug output
1102 pout("ATA_SMART_READ_LOG failed: %s\n", device->get_errmsg());
1103 return false;
1104 }
1105 return true;
1106 }
1107
1108
1109
1110 // Reads the SMART or GPL Log Directory (log #0)
1111 int ataReadLogDirectory(ata_device * device, ata_smart_log_directory * data, bool gpl)
1112 {
1113 if (!gpl) { // SMART Log directory
1114 if (smartcommandhandler(device, READ_LOG, 0x00, (char *)data))
1115 return -1;
1116 }
1117 else { // GP Log directory
1118 if (!ataReadLogExt(device, 0x00, 0x00, 0, data, 1))
1119 return -1;
1120 }
1121
1122 // swap endian order if needed
1123 if (isbigendian())
1124 swapx(&data->logversion);
1125
1126 return 0;
1127 }
1128
1129
1130 // Reads the selective self-test log (log #9)
1131 int ataReadSelectiveSelfTestLog(ata_device * device, struct ata_selective_self_test_log *data){
1132
1133 // get data from device
1134 if (smartcommandhandler(device, READ_LOG, 0x09, (char *)data)){
1135 syserror("Error SMART Read Selective Self-Test Log failed");
1136 return -1;
1137 }
1138
1139 // compute its checksum, and issue a warning if needed
1140 if (checksum(data))
1141 checksumwarning("SMART Selective Self-Test Log Structure");
1142
1143 // swap endian order if needed
1144 if (isbigendian()){
1145 int i;
1146 swap2((char *)&(data->logversion));
1147 for (i=0;i<5;i++){
1148 swap8((char *)&(data->span[i].start));
1149 swap8((char *)&(data->span[i].end));
1150 }
1151 swap8((char *)&(data->currentlba));
1152 swap2((char *)&(data->currentspan));
1153 swap2((char *)&(data->flags));
1154 swap2((char *)&(data->pendingtime));
1155 }
1156
1157 if (data->logversion != 1)
1158 pout("Note: selective self-test log revision number (%d) not 1 implies that no selective self-test has ever been run\n", data->logversion);
1159
1160 return 0;
1161 }
1162
1163 // Writes the selective self-test log (log #9)
1164 int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_args & args,
1165 const ata_smart_values * sv, uint64_t num_sectors)
1166 {
1167 // Disk size must be known
1168 if (!num_sectors) {
1169 pout("Disk size is unknown, unable to check selective self-test spans\n");
1170 return -1;
1171 }
1172
1173 // Read log
1174 struct ata_selective_self_test_log sstlog, *data=&sstlog;
1175 unsigned char *ptr=(unsigned char *)data;
1176 if (ataReadSelectiveSelfTestLog(device, data)) {
1177 pout("Since Read failed, will not attempt to WRITE Selective Self-test Log\n");
1178 return -1;
1179 }
1180
1181 // Set log version
1182 data->logversion = 1;
1183
1184 // Host is NOT allowed to write selective self-test log if a selective
1185 // self-test is in progress.
1186 if (0<data->currentspan && data->currentspan<6 && ((sv->self_test_exec_status)>>4)==15) {
1187 pout("Error SMART Selective or other Self-Test in progress.\n");
1188 return -4;
1189 }
1190
1191 // Set start/end values based on old spans for special -t select,... options
1192 int i;
1193 for (i = 0; i < args.num_spans; i++) {
1194 int mode = args.span[i].mode;
1195 uint64_t start = args.span[i].start;
1196 uint64_t end = args.span[i].end;
1197 if (mode == SEL_CONT) {// redo or next dependig on last test status
1198 switch (sv->self_test_exec_status >> 4) {
1199 case 1: case 2: // Aborted/Interrupted by host
1200 pout("Continue Selective Self-Test: Redo last span\n");
1201 mode = SEL_REDO;
1202 break;
1203 default: // All others
1204 pout("Continue Selective Self-Test: Start next span\n");
1205 mode = SEL_NEXT;
1206 break;
1207 }
1208 }
1209 switch (mode) {
1210 case SEL_RANGE: // -t select,START-END
1211 break;
1212 case SEL_REDO: // -t select,redo... => Redo current
1213 start = data->span[i].start;
1214 if (end > 0) { // -t select,redo+SIZE
1215 end--; end += start; // [oldstart, oldstart+SIZE)
1216 }
1217 else // -t select,redo
1218 end = data->span[i].end; // [oldstart, oldend]
1219 break;
1220 case SEL_NEXT: // -t select,next... => Do next
1221 if (data->span[i].end == 0) {
1222 start = end = 0; break; // skip empty spans
1223 }
1224 start = data->span[i].end + 1;
1225 if (start >= num_sectors)
1226 start = 0; // wrap around
1227 if (end > 0) { // -t select,next+SIZE
1228 end--; end += start; // (oldend, oldend+SIZE]
1229 }
1230 else { // -t select,next
1231 uint64_t oldsize = data->span[i].end - data->span[i].start + 1;
1232 end = start + oldsize - 1; // (oldend, oldend+oldsize]
1233 if (end >= num_sectors) {
1234 // Adjust size to allow round-robin testing without future size decrease
1235 uint64_t spans = (num_sectors + oldsize-1) / oldsize;
1236 uint64_t newsize = (num_sectors + spans-1) / spans;
1237 uint64_t newstart = num_sectors - newsize, newend = num_sectors - 1;
1238 pout("Span %d changed from %"PRIu64"-%"PRIu64" (%"PRIu64" sectors)\n",
1239 i, start, end, oldsize);
1240 pout(" to %"PRIu64"-%"PRIu64" (%"PRIu64" sectors) (%"PRIu64" spans)\n",
1241 newstart, newend, newsize, spans);
1242 start = newstart; end = newend;
1243 }
1244 }
1245 break;
1246 default:
1247 pout("ataWriteSelectiveSelfTestLog: Invalid mode %d\n", mode);
1248 return -1;
1249 }
1250 // Range check
1251 if (start < num_sectors && num_sectors <= end) {
1252 if (end != ~(uint64_t)0) // -t select,N-max
1253 pout("Size of self-test span %d decreased according to disk size\n", i);
1254 end = num_sectors - 1;
1255 }
1256 if (!(start <= end && end < num_sectors)) {
1257 pout("Invalid selective self-test span %d: %"PRIu64"-%"PRIu64" (%"PRIu64" sectors)\n",
1258 i, start, end, num_sectors);
1259 return -1;
1260 }
1261 // Return the actual mode and range to caller.
1262 args.span[i].mode = mode;
1263 args.span[i].start = start;
1264 args.span[i].end = end;
1265 }
1266
1267 // Clear spans
1268 for (i=0; i<5; i++)
1269 memset(data->span+i, 0, sizeof(struct test_span));
1270
1271 // Set spans for testing
1272 for (i = 0; i < args.num_spans; i++){
1273 data->span[i].start = args.span[i].start;
1274 data->span[i].end = args.span[i].end;
1275 }
1276
1277 // host must initialize to zero before initiating selective self-test
1278 data->currentlba=0;
1279 data->currentspan=0;
1280
1281 // Perform off-line scan after selective test?
1282 if (args.scan_after_select == 1)
1283 // NO
1284 data->flags &= ~SELECTIVE_FLAG_DOSCAN;
1285 else if (args.scan_after_select == 2)
1286 // YES
1287 data->flags |= SELECTIVE_FLAG_DOSCAN;
1288
1289 // Must clear active and pending flags before writing
1290 data->flags &= ~(SELECTIVE_FLAG_ACTIVE);
1291 data->flags &= ~(SELECTIVE_FLAG_PENDING);
1292
1293 // modify pending time?
1294 if (args.pending_time)
1295 data->pendingtime = (unsigned short)(args.pending_time-1);
1296
1297 // Set checksum to zero, then compute checksum
1298 data->checksum=0;
1299 unsigned char cksum=0;
1300 for (i=0; i<512; i++)
1301 cksum+=ptr[i];
1302 cksum=~cksum;
1303 cksum+=1;
1304 data->checksum=cksum;
1305
1306 // swap endian order if needed
1307 if (isbigendian()){
1308 swap2((char *)&(data->logversion));
1309 for (int i=0;i<5;i++){
1310 swap8((char *)&(data->span[i].start));
1311 swap8((char *)&(data->span[i].end));
1312 }
1313 swap8((char *)&(data->currentlba));
1314 swap2((char *)&(data->currentspan));
1315 swap2((char *)&(data->flags));
1316 swap2((char *)&(data->pendingtime));
1317 }
1318
1319 // write new selective self-test log
1320 if (smartcommandhandler(device, WRITE_LOG, 0x09, (char *)data)){
1321 syserror("Error Write Selective Self-Test Log failed");
1322 return -3;
1323 }
1324
1325 return 0;
1326 }
1327
1328 // This corrects some quantities that are byte reversed in the SMART
1329 // ATA ERROR LOG.
1330 static void fixsamsungerrorlog(ata_smart_errorlog * data)
1331 {
1332 // FIXED IN SAMSUNG -25 FIRMWARE???
1333 // Device error count in bytes 452-3
1334 swap2((char *)&(data->ata_error_count));
1335
1336 // FIXED IN SAMSUNG -22a FIRMWARE
1337 // step through 5 error log data structures
1338 for (int i = 0; i < 5; i++){
1339 // step through 5 command data structures
1340 for (int j = 0; j < 5; j++)
1341 // Command data structure 4-byte millisec timestamp. These are
1342 // bytes (N+8, N+9, N+10, N+11).
1343 swap4((char *)&(data->errorlog_struct[i].commands[j].timestamp));
1344 // Error data structure two-byte hour life timestamp. These are
1345 // bytes (N+28, N+29).
1346 swap2((char *)&(data->errorlog_struct[i].error_struct.timestamp));
1347 }
1348 return;
1349 }
1350
1351 // NEEDED ONLY FOR SAMSUNG -22 (some) -23 AND -24?? FIRMWARE
1352 static void fixsamsungerrorlog2(ata_smart_errorlog * data)
1353 {
1354 // Device error count in bytes 452-3
1355 swap2((char *)&(data->ata_error_count));
1356 return;
1357 }
1358
1359 // Reads the Summary SMART Error Log (log #1). The Comprehensive SMART
1360 // Error Log is #2, and the Extended Comprehensive SMART Error log is
1361 // #3
1362 int ataReadErrorLog (ata_device * device, ata_smart_errorlog *data,
1363 unsigned char fix_firmwarebug)
1364 {
1365
1366 // get data from device
1367 if (smartcommandhandler(device, READ_LOG, 0x01, (char *)data)){
1368 syserror("Error SMART Error Log Read failed");
1369 return -1;
1370 }
1371
1372 // compute its checksum, and issue a warning if needed
1373 if (checksum(data))
1374 checksumwarning("SMART ATA Error Log Structure");
1375
1376 // Some disks have the byte order reversed in some SMART Summary
1377 // Error log entries
1378 if (fix_firmwarebug == FIX_SAMSUNG)
1379 fixsamsungerrorlog(data);
1380 else if (fix_firmwarebug == FIX_SAMSUNG2)
1381 fixsamsungerrorlog2(data);
1382
1383 // swap endian order if needed
1384 if (isbigendian()){
1385 int i,j;
1386
1387 // Device error count in bytes 452-3
1388 swap2((char *)&(data->ata_error_count));
1389
1390 // step through 5 error log data structures
1391 for (i=0; i<5; i++){
1392 // step through 5 command data structures
1393 for (j=0; j<5; j++)
1394 // Command data structure 4-byte millisec timestamp
1395 swap4((char *)&(data->errorlog_struct[i].commands[j].timestamp));
1396 // Error data structure life timestamp
1397 swap2((char *)&(data->errorlog_struct[i].error_struct.timestamp));
1398 }
1399 }
1400
1401 return 0;
1402 }
1403
1404 // Read Extended Comprehensive Error Log
1405 bool ataReadExtErrorLog(ata_device * device, ata_smart_exterrlog * log,
1406 unsigned nsectors)
1407 {
1408 if (!ataReadLogExt(device, 0x03, 0x00, 0, log, nsectors))
1409 return false;
1410
1411 check_multi_sector_sum(log, nsectors, "SMART Extended Comprehensive Error Log Structure");
1412
1413 if (isbigendian()) {
1414 swapx(&log->device_error_count);
1415 swapx(&log->error_log_index);
1416
1417 for (unsigned i = 0; i < nsectors; i++) {
1418 for (unsigned j = 0; j < 4; j++)
1419 swapx(&log->error_logs[i].commands[j].timestamp);
1420 swapx(&log->error_logs[i].error.timestamp);
1421 }
1422 }
1423
1424 return true;
1425 }
1426
1427
1428 int ataReadSmartThresholds (ata_device * device, struct ata_smart_thresholds_pvt *data){
1429
1430 // get data from device
1431 if (smartcommandhandler(device, READ_THRESHOLDS, 0, (char *)data)){
1432 syserror("Error SMART Thresholds Read failed");
1433 return -1;
1434 }
1435
1436 // compute its checksum, and issue a warning if needed
1437 if (checksum(data))
1438 checksumwarning("SMART Attribute Thresholds Structure");
1439
1440 // swap endian order if needed
1441 if (isbigendian())
1442 swap2((char *)&(data->revnumber));
1443
1444 return 0;
1445 }
1446
1447 int ataEnableSmart (ata_device * device ){
1448 if (smartcommandhandler(device, ENABLE, 0, NULL)){
1449 syserror("Error SMART Enable failed");
1450 return -1;
1451 }
1452 return 0;
1453 }
1454
1455 int ataDisableSmart (ata_device * device ){
1456
1457 if (smartcommandhandler(device, DISABLE, 0, NULL)){
1458 syserror("Error SMART Disable failed");
1459 return -1;
1460 }
1461 return 0;
1462 }
1463
1464 int ataEnableAutoSave(ata_device * device){
1465 if (smartcommandhandler(device, AUTOSAVE, 241, NULL)){
1466 syserror("Error SMART Enable Auto-save failed");
1467 return -1;
1468 }
1469 return 0;
1470 }
1471
1472 int ataDisableAutoSave(ata_device * device){
1473
1474 if (smartcommandhandler(device, AUTOSAVE, 0, NULL)){
1475 syserror("Error SMART Disable Auto-save failed");
1476 return -1;
1477 }
1478 return 0;
1479 }
1480
1481 // In *ALL* ATA standards the Enable/Disable AutoOffline command is
1482 // marked "OBSOLETE". It is defined in SFF-8035i Revision 2, and most
1483 // vendors still support it for backwards compatibility. IBM documents
1484 // it for some drives.
1485 int ataEnableAutoOffline (ata_device * device){
1486
1487 /* timer hard coded to 4 hours */
1488 if (smartcommandhandler(device, AUTO_OFFLINE, 248, NULL)){
1489 syserror("Error SMART Enable Automatic Offline failed");
1490 return -1;
1491 }
1492 return 0;
1493 }
1494
1495 // Another Obsolete Command. See comments directly above, associated
1496 // with the corresponding Enable command.
1497 int ataDisableAutoOffline (ata_device * device){
1498
1499 if (smartcommandhandler(device, AUTO_OFFLINE, 0, NULL)){
1500 syserror("Error SMART Disable Automatic Offline failed");
1501 return -1;
1502 }
1503 return 0;
1504 }
1505
1506 // If SMART is enabled, supported, and working, then this call is
1507 // guaranteed to return 1, else zero. Note that it should return 1
1508 // regardless of whether the disk's SMART status is 'healthy' or
1509 // 'failing'.
1510 int ataDoesSmartWork(ata_device * device){
1511 int retval=smartcommandhandler(device, STATUS, 0, NULL);
1512
1513 if (-1 == retval)
1514 return 0;
1515
1516 return 1;
1517 }
1518
1519 // This function uses a different interface (DRIVE_TASK) than the
1520 // other commands in this file.
1521 int ataSmartStatus2(ata_device * device){
1522 return smartcommandhandler(device, STATUS_CHECK, 0, NULL);
1523 }
1524
1525 // This is the way to execute ALL tests: offline, short self-test,
1526 // extended self test, with and without captive mode, etc.
1527 // TODO: Move to ataprint.cpp ?
1528 int ataSmartTest(ata_device * device, int testtype, const ata_selective_selftest_args & selargs,
1529 const ata_smart_values * sv, uint64_t num_sectors)
1530 {
1531 char cmdmsg[128]; const char *type, *captive;
1532 int errornum, cap, retval, select=0;
1533
1534 // Boolean, if set, says test is captive
1535 cap=testtype & CAPTIVE_MASK;
1536
1537 // Set up strings that describe the type of test
1538 if (cap)
1539 captive="captive";
1540 else
1541 captive="off-line";
1542
1543 if (testtype==OFFLINE_FULL_SCAN)
1544 type="off-line";
1545 else if (testtype==SHORT_SELF_TEST || testtype==SHORT_CAPTIVE_SELF_TEST)
1546 type="Short self-test";
1547 else if (testtype==EXTEND_SELF_TEST || testtype==EXTEND_CAPTIVE_SELF_TEST)
1548 type="Extended self-test";
1549 else if (testtype==CONVEYANCE_SELF_TEST || testtype==CONVEYANCE_CAPTIVE_SELF_TEST)
1550 type="Conveyance self-test";
1551 else if ((select=(testtype==SELECTIVE_SELF_TEST || testtype==SELECTIVE_CAPTIVE_SELF_TEST)))
1552 type="Selective self-test";
1553 else
1554 type="[Unrecognized] self-test";
1555
1556 // If doing a selective self-test, first use WRITE_LOG to write the
1557 // selective self-test log.
1558 ata_selective_selftest_args selargs_io = selargs; // filled with info about actual spans
1559 if (select && (retval = ataWriteSelectiveSelfTestLog(device, selargs_io, sv, num_sectors))) {
1560 if (retval==-4)
1561 pout("Can't start selective self-test without aborting current test: use '-X' option to smartctl.\n");
1562 return retval;
1563 }
1564
1565 // Print ouf message that we are sending the command to test
1566 if (testtype==ABORT_SELF_TEST)
1567 sprintf(cmdmsg,"Abort SMART off-line mode self-test routine");
1568 else
1569 sprintf(cmdmsg,"Execute SMART %s routine immediately in %s mode",type,captive);
1570 pout("Sending command: \"%s\".\n",cmdmsg);
1571
1572 if (select) {
1573 int i;
1574 pout("SPAN STARTING_LBA ENDING_LBA\n");
1575 for (i = 0; i < selargs_io.num_spans; i++)
1576 pout(" %d %20"PRId64" %20"PRId64"\n", i,
1577 selargs_io.span[i].start,
1578 selargs_io.span[i].end);
1579 }
1580
1581 // Now send the command to test
1582 errornum=smartcommandhandler(device, IMMEDIATE_OFFLINE, testtype, NULL);
1583
1584 if (errornum && !(cap && errno==EIO)){
1585 char errormsg[128];
1586 sprintf(errormsg,"Command \"%s\" failed",cmdmsg);
1587 syserror(errormsg);
1588 pout("\n");
1589 return -1;
1590 }
1591
1592 // Since the command succeeded, tell user
1593 if (testtype==ABORT_SELF_TEST)
1594 pout("Self-testing aborted!\n");
1595 else
1596 pout("Drive command \"%s\" successful.\nTesting has begun.\n",cmdmsg);
1597 return 0;
1598 }
1599
1600 /* Test Time Functions */
1601 int TestTime(const ata_smart_values *data, int testtype)
1602 {
1603 switch (testtype){
1604 case OFFLINE_FULL_SCAN:
1605 return (int) data->total_time_to_complete_off_line;
1606 case SHORT_SELF_TEST:
1607 case SHORT_CAPTIVE_SELF_TEST:
1608 return (int) data->short_test_completion_time;
1609 case EXTEND_SELF_TEST:
1610 case EXTEND_CAPTIVE_SELF_TEST:
1611 return (int) data->extend_test_completion_time;
1612 case CONVEYANCE_SELF_TEST:
1613 case CONVEYANCE_CAPTIVE_SELF_TEST:
1614 return (int) data->conveyance_test_completion_time;
1615 default:
1616 return 0;
1617 }
1618 }
1619
1620 // This function tells you both about the ATA error log and the
1621 // self-test error log capability (introduced in ATA-5). The bit is
1622 // poorly documented in the ATA/ATAPI standard. Starting with ATA-6,
1623 // SMART error logging is also indicated in bit 0 of DEVICE IDENTIFY
1624 // word 84 and 87. Top two bits must match the pattern 01. BEFORE
1625 // ATA-6 these top two bits still had to match the pattern 01, but the
1626 // remaining bits were reserved (==0).
1627 int isSmartErrorLogCapable (const ata_smart_values * data, const ata_identify_device * identity)
1628 {
1629 unsigned short word84=identity->command_set_extension;
1630 unsigned short word87=identity->csf_default;
1631 int isata6=identity->major_rev_num & (0x01<<6);
1632 int isata7=identity->major_rev_num & (0x01<<7);
1633
1634 if ((isata6 || isata7) && (word84>>14) == 0x01 && (word84 & 0x01))
1635 return 1;
1636
1637 if ((isata6 || isata7) && (word87>>14) == 0x01 && (word87 & 0x01))
1638 return 1;
1639
1640 // otherwise we'll use the poorly documented capability bit
1641 return data->errorlog_capability & 0x01;
1642 }
1643
1644 // See previous function. If the error log exists then the self-test
1645 // log should (must?) also exist.
1646 int isSmartTestLogCapable (const ata_smart_values * data, const ata_identify_device *identity)
1647 {
1648 unsigned short word84=identity->command_set_extension;
1649 unsigned short word87=identity->csf_default;
1650 int isata6=identity->major_rev_num & (0x01<<6);
1651 int isata7=identity->major_rev_num & (0x01<<7);
1652
1653 if ((isata6 || isata7) && (word84>>14) == 0x01 && (word84 & 0x02))
1654 return 1;
1655
1656 if ((isata6 || isata7) && (word87>>14) == 0x01 && (word87 & 0x02))
1657 return 1;
1658
1659
1660 // otherwise we'll use the poorly documented capability bit
1661 return data->errorlog_capability & 0x01;
1662 }
1663
1664
1665 int isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
1666 {
1667 unsigned short word84=identity->command_set_extension;
1668 unsigned short word87=identity->csf_default;
1669
1670 // If bit 14 of word 84 is set to one and bit 15 of word 84 is
1671 // cleared to zero, the contents of word 84 contains valid support
1672 // information. If not, support information is not valid in this
1673 // word.
1674 if ((word84>>14) == 0x01)
1675 // If bit 5 of word 84 is set to one, the device supports the
1676 // General Purpose Logging feature set.
1677 return (word84 & (0x01 << 5));
1678
1679 // If bit 14 of word 87 is set to one and bit 15 of word 87 is
1680 // cleared to zero, the contents of words (87:85) contain valid
1681 // information. If not, information is not valid in these words.
1682 if ((word87>>14) == 0x01)
1683 // If bit 5 of word 87 is set to one, the device supports
1684 // the General Purpose Logging feature set.
1685 return (word87 & (0x01 << 5));
1686
1687 // not capable
1688 return 0;
1689 }
1690
1691
1692 // SMART self-test capability is also indicated in bit 1 of DEVICE
1693 // IDENTIFY word 87 (if top two bits of word 87 match pattern 01).
1694 // However this was only introduced in ATA-6 (but self-test log was in
1695 // ATA-5).
1696 int isSupportExecuteOfflineImmediate(const ata_smart_values *data)
1697 {
1698 return data->offline_data_collection_capability & 0x01;
1699 }
1700
1701 // Note in the ATA-5 standard, the following bit is listed as "Vendor
1702 // Specific". So it may not be reliable. The only use of this that I
1703 // have found is in IBM drives, where it is well-documented. See for
1704 // example page 170, section 13.32.1.18 of the IBM Travelstar 40GNX
1705 // hard disk drive specifications page 164 Revision 1.1 22 Apr 2002.
1706 int isSupportAutomaticTimer(const ata_smart_values * data)
1707 {
1708 return data->offline_data_collection_capability & 0x02;
1709 }
1710 int isSupportOfflineAbort(const ata_smart_values *data)
1711 {
1712 return data->offline_data_collection_capability & 0x04;
1713 }
1714 int isSupportOfflineSurfaceScan(const ata_smart_values * data)
1715 {
1716 return data->offline_data_collection_capability & 0x08;
1717 }
1718 int isSupportSelfTest (const ata_smart_values * data)
1719 {
1720 return data->offline_data_collection_capability & 0x10;
1721 }
1722 int isSupportConveyanceSelfTest(const ata_smart_values * data)
1723 {
1724 return data->offline_data_collection_capability & 0x20;
1725 }
1726 int isSupportSelectiveSelfTest(const ata_smart_values * data)
1727 {
1728 return data->offline_data_collection_capability & 0x40;
1729 }
1730
1731 // Get attribute state
1732 ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr,
1733 const ata_smart_threshold_entry & thre,
1734 const ata_vendor_attr_defs & defs)
1735 {
1736 if (!attr.id)
1737 return ATTRSTATE_NON_EXISTING;
1738
1739 // Normalized values (current,worst,threshold) not valid
1740 // if specified by '-v' option.
1741 // (Some SSD disks uses these bytes to store raw value).
1742 if (defs[attr.id].flags & ATTRFLAG_NO_NORMVAL)
1743 return ATTRSTATE_NO_NORMVAL;
1744
1745 // No threshold if thresholds cannot be read.
1746 if (!thre.id && !thre.threshold)
1747 return ATTRSTATE_NO_THRESHOLD;
1748
1749 // Bad threshold if id's don't match
1750 if (attr.id != thre.id)
1751 return ATTRSTATE_BAD_THRESHOLD;
1752
1753 // Don't report a failed attribute if its threshold is 0.
1754 // ATA-3 (X3T13/2008D Revision 7b) declares 0x00 as the "always passing"
1755 // threshold (Later ATA versions declare all thresholds as "obsolete").
1756 // In practice, threshold value 0 is often used for usage attributes.
1757 if (!thre.threshold)
1758 return ATTRSTATE_OK;
1759
1760 // Failed now if current value is below threshold
1761 if (attr.current <= thre.threshold)
1762 return ATTRSTATE_FAILED_NOW;
1763
1764 // Failed in the past if worst value is below threshold
1765 if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL) && attr.worst <= thre.threshold)
1766 return ATTRSTATE_FAILED_PAST;
1767
1768 return ATTRSTATE_OK;
1769 }
1770
1771 // Get default raw value print format
1772 static ata_attr_raw_format get_default_raw_format(unsigned char id)
1773 {
1774 switch (id) {
1775 case 3: // Spin-up time
1776 return RAWFMT_RAW16_OPT_AVG16;
1777
1778 case 5: // Reallocated sector count
1779 case 196: // Reallocated event count
1780 return RAWFMT_RAW16_OPT_RAW16;
1781
1782 case 190: // Temperature
1783 case 194:
1784 return RAWFMT_TEMPMINMAX;
1785
1786 default:
1787 return RAWFMT_RAW48;
1788 }
1789 }
1790
1791 // Get attribute raw value.
1792 uint64_t ata_get_attr_raw_value(const ata_smart_attribute & attr,
1793 const ata_vendor_attr_defs & defs)
1794 {
1795 const ata_vendor_attr_defs::entry & def = defs[attr.id];
1796
1797 // Use default byteorder if not specified
1798 const char * byteorder = def.byteorder;
1799 if (!*byteorder) {
1800 if (def.raw_format == RAWFMT_RAW64 || def.raw_format == RAWFMT_HEX64)
1801 byteorder = "543210wv";
1802 else
1803 byteorder = "543210";
1804 }
1805
1806 // Build 64-bit value from selected bytes
1807 uint64_t rawvalue = 0;
1808 for (int i = 0; byteorder[i]; i++) {
1809 unsigned char b;
1810 switch (byteorder[i]) {
1811 case '0': b = attr.raw[0]; break;
1812 case '1': b = attr.raw[1]; break;
1813 case '2': b = attr.raw[2]; break;
1814 case '3': b = attr.raw[3]; break;
1815 case '4': b = attr.raw[4]; break;
1816 case '5': b = attr.raw[5]; break;
1817 case 'r': b = attr.reserv; break;
1818 case 'v': b = attr.current; break;
1819 case 'w': b = attr.worst; break;
1820 default : b = 0; break;
1821 }
1822 rawvalue <<= 8; rawvalue |= b;
1823 }
1824
1825 return rawvalue;
1826 }
1827
1828
1829 // Format attribute raw value.
1830 std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
1831 const ata_vendor_attr_defs & defs)
1832 {
1833 // Get 48 bit or 64 bit raw value
1834 uint64_t rawvalue = ata_get_attr_raw_value(attr, defs);
1835
1836 // Get 16 bit words
1837 const unsigned char * raw = attr.raw;
1838 unsigned word[3];
1839 word[0] = raw[0] | (raw[1] << 8);
1840 word[1] = raw[2] | (raw[3] << 8);
1841 word[2] = raw[4] | (raw[5] << 8);
1842
1843 // Get print format
1844 ata_attr_raw_format format = defs[attr.id].raw_format;
1845 if (format == RAWFMT_DEFAULT)
1846 format = get_default_raw_format(attr.id);
1847
1848 // Print
1849 std::string s;
1850 switch (format) {
1851 case RAWFMT_RAW8:
1852 s = strprintf("%d %d %d %d %d %d",
1853 raw[5], raw[4], raw[3], raw[2], raw[1], raw[0]);
1854 break;
1855
1856 case RAWFMT_RAW16:
1857 s = strprintf("%u %u %u", word[2], word[1], word[0]);
1858 break;
1859
1860 case RAWFMT_RAW48:
1861 case RAWFMT_RAW64:
1862 s = strprintf("%"PRIu64, rawvalue);
1863 break;
1864
1865 case RAWFMT_HEX48:
1866 s = strprintf("0x%012"PRIx64, rawvalue);
1867 break;
1868
1869 case RAWFMT_HEX64:
1870 s = strprintf("0x%016"PRIx64, rawvalue);
1871 break;
1872
1873 case RAWFMT_RAW16_OPT_RAW16:
1874 s = strprintf("%u", word[0]);
1875 if (word[1] || word[2])
1876 s += strprintf(" (%u, %u)", word[2], word[1]);
1877 break;
1878
1879 case RAWFMT_RAW16_OPT_AVG16:
1880 s = strprintf("%u", word[0]);
1881 if (word[1])
1882 s += strprintf(" (Average %u)", word[1]);
1883 break;
1884
1885 case RAWFMT_RAW24_RAW24:
1886 s = strprintf("%d/%d",
1887 raw[0] | (raw[1]<<8) | (raw[2]<<16),
1888 raw[3] | (raw[4]<<8) | (raw[5]<<16));
1889 break;
1890
1891 case RAWFMT_MIN2HOUR:
1892 {
1893 // minutes
1894 int64_t temp = word[0]+(word[1]<<16);
1895 int64_t tmp1 = temp/60;
1896 int64_t tmp2 = temp%60;
1897 s = strprintf("%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
1898 if (word[2])
1899 s += strprintf(" (%u)", word[2]);
1900 }
1901 break;
1902
1903 case RAWFMT_SEC2HOUR:
1904 {
1905 // seconds
1906 int64_t hours = rawvalue/3600;
1907 int64_t minutes = (rawvalue-3600*hours)/60;
1908 int64_t seconds = rawvalue%60;
1909 s = strprintf("%"PRIu64"h+%02"PRIu64"m+%02"PRIu64"s", hours, minutes, seconds);
1910 }
1911 break;
1912
1913 case RAWFMT_HALFMIN2HOUR:
1914 {
1915 // 30-second counter
1916 int64_t hours = rawvalue/120;
1917 int64_t minutes = (rawvalue-120*hours)/2;
1918 s += strprintf("%"PRIu64"h+%02"PRIu64"m", hours, minutes);
1919 }
1920 break;
1921
1922 case RAWFMT_TEMPMINMAX:
1923 // Temperature
1924 s = strprintf("%u", word[0]);
1925 if (word[1] || word[2]) {
1926 unsigned lo = ~0, hi = ~0;
1927 if (!raw[3]) {
1928 // 00 HH 00 LL 00 TT (IBM)
1929 hi = word[2]; lo = word[1];
1930 }
1931 else if (!word[2]) {
1932 // 00 00 HH LL 00 TT (Maxtor)
1933 hi = raw[3]; lo = raw[2];
1934 }
1935 if (lo > hi) {
1936 unsigned t = lo; lo = hi; hi = t;
1937 }
1938 if (lo <= word[0] && word[0] <= hi)
1939 s += strprintf(" (Lifetime Min/Max %u/%u)", lo, hi);
1940 else
1941 s += strprintf(" (%d %d %d %d)", raw[5], raw[4], raw[3], raw[2]);
1942 }
1943 break;
1944
1945 case RAWFMT_TEMP10X:
1946 // ten times temperature in Celsius
1947 s = strprintf("%d.%d", word[0]/10, word[0]%10);
1948 break;
1949
1950 default:
1951 s = "?"; // Should not happen
1952 break;
1953 }
1954
1955 return s;
1956 }
1957
1958 // Attribute names shouldn't be longer than 23 chars, otherwise they break the
1959 // output of smartctl.
1960 static const char * get_default_attr_name(unsigned char id)
1961 {
1962 switch (id) {
1963 case 1:
1964 return "Raw_Read_Error_Rate";
1965 case 2:
1966 return "Throughput_Performance";
1967 case 3:
1968 return "Spin_Up_Time";
1969 case 4:
1970 return "Start_Stop_Count";
1971 case 5:
1972 return "Reallocated_Sector_Ct";
1973 case 6:
1974 return "Read_Channel_Margin";
1975 case 7:
1976 return "Seek_Error_Rate";
1977 case 8:
1978 return "Seek_Time_Performance";
1979 case 9:
1980 return "Power_On_Hours";
1981 case 10:
1982 return "Spin_Retry_Count";
1983 case 11:
1984 return "Calibration_Retry_Count";
1985 case 12:
1986 return "Power_Cycle_Count";
1987 case 13:
1988 return "Read_Soft_Error_Rate";
1989 case 175:
1990 return "Program_Fail_Count_Chip";
1991 case 176:
1992 return "Erase_Fail_Count_Chip";
1993 case 177:
1994 return "Wear_Leveling_Count";
1995 case 178:
1996 return "Used_Rsvd_Blk_Cnt_Chip";
1997 case 179:
1998 return "Used_Rsvd_Blk_Cnt_Tot";
1999 case 180:
2000 return "Unused_Rsvd_Blk_Cnt_Tot";
2001 case 181:
2002 return "Program_Fail_Cnt_Total";
2003 case 182:
2004 return "Erase_Fail_Count_Total";
2005 case 183:
2006 return "Runtime_Bad_Block";
2007 case 184:
2008 return "End-to-End_Error";
2009 case 187:
2010 return "Reported_Uncorrect";
2011 case 188:
2012 return "Command_Timeout";
2013 case 189:
2014 return "High_Fly_Writes";
2015 case 190:
2016 // Western Digital uses this for temperature.
2017 // It's identical to Attribute 194 except that it
2018 // has a failure threshold set to correspond to the
2019 // max allowed operating temperature of the drive, which
2020 // is typically 55C. So if this attribute has failed
2021 // in the past, it indicates that the drive temp exceeded
2022 // 55C sometime in the past.
2023 return "Airflow_Temperature_Cel";
2024 case 191:
2025 return "G-Sense_Error_Rate";
2026 case 192:
2027 return "Power-Off_Retract_Count";
2028 case 193:
2029 return "Load_Cycle_Count";
2030 case 194:
2031 return "Temperature_Celsius";
2032 case 195:
2033 // Fujitsu: "ECC_On_The_Fly_Count";
2034 return "Hardware_ECC_Recovered";
2035 case 196:
2036 return "Reallocated_Event_Count";
2037 case 197:
2038 return "Current_Pending_Sector";
2039 case 198:
2040 return "Offline_Uncorrectable";
2041 case 199:
2042 return "UDMA_CRC_Error_Count";
2043 case 200:
2044 // Western Digital
2045 return "Multi_Zone_Error_Rate";
2046 case 201:
2047 return "Soft_Read_Error_Rate";
2048 case 202:
2049 // Fujitsu: "TA_Increase_Count"
2050 return "Data_Address_Mark_Errs";
2051 case 203:
2052 // Fujitsu
2053 return "Run_Out_Cancel";
2054 // Maxtor: ECC Errors
2055 case 204:
2056 // Fujitsu: "Shock_Count_Write_Opern"
2057 return "Soft_ECC_Correction";
2058 case 205:
2059 // Fujitsu: "Shock_Rate_Write_Opern"
2060 return "Thermal_Asperity_Rate";
2061 case 206:
2062 // Fujitsu
2063 return "Flying_Height";
2064 case 207:
2065 // Maxtor
2066 return "Spin_High_Current";
2067 case 208:
2068 // Maxtor
2069 return "Spin_Buzz";
2070 case 209:
2071 // Maxtor
2072 return "Offline_Seek_Performnce";
2073 case 220:
2074 return "Disk_Shift";
2075 case 221:
2076 return "G-Sense_Error_Rate";
2077 case 222:
2078 return "Loaded_Hours";
2079 case 223:
2080 return "Load_Retry_Count";
2081 case 224:
2082 return "Load_Friction";
2083 case 225:
2084 return "Load_Cycle_Count";
2085 case 226:
2086 return "Load-in_Time";
2087 case 227:
2088 return "Torq-amp_Count";
2089 case 228:
2090 return "Power-off_Retract_Count";
2091 case 230:
2092 // seen in IBM DTPA-353750
2093 return "Head_Amplitude";
2094 case 231:
2095 return "Temperature_Celsius";
2096 case 232:
2097 // seen in Intel X25-E SSD
2098 return "Available_Reservd_Space";
2099 case 233:
2100 // seen in Intel X25-E SSD
2101 return "Media_Wearout_Indicator";
2102 case 240:
2103 return "Head_Flying_Hours";
2104 case 241:
2105 return "Total_LBAs_Written";
2106 case 242:
2107 return "Total_LBAs_Read";
2108 case 250:
2109 return "Read_Error_Retry_Rate";
2110 case 254:
2111 return "Free_Fall_Sensor";
2112 default:
2113 return "Unknown_Attribute";
2114 }
2115 }
2116
2117 // Get attribute name
2118 std::string ata_get_smart_attr_name(unsigned char id, const ata_vendor_attr_defs & defs)
2119 {
2120 if (!defs[id].name.empty())
2121 return defs[id].name;
2122 else
2123 return get_default_attr_name(id);
2124 }
2125
2126 // Find attribute index for attribute id, -1 if not found.
2127 int ata_find_attr_index(unsigned char id, const ata_smart_values & smartval)
2128 {
2129 if (!id)
2130 return -1;
2131 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
2132 if (smartval.vendor_attributes[i].id == id)
2133 return i;
2134 }
2135 return -1;
2136 }
2137
2138 // Return Temperature Attribute raw value selected according to possible
2139 // non-default interpretations. If the Attribute does not exist, return 0
2140 unsigned char ata_return_temperature_value(const ata_smart_values * data, const ata_vendor_attr_defs & defs)
2141 {
2142 for (int i = 0; i < 3; i++) {
2143 static const unsigned char ids[3] = {194, 9, 220};
2144 unsigned char id = ids[i];
2145 const ata_attr_raw_format format = defs[id].raw_format;
2146 if (!( (id == 194 && format == RAWFMT_DEFAULT)
2147 || format == RAWFMT_TEMPMINMAX || format == RAWFMT_TEMP10X))
2148 continue;
2149 int idx = ata_find_attr_index(id, *data);
2150 if (idx < 0)
2151 continue;
2152 uint64_t raw = ata_get_attr_raw_value(data->vendor_attributes[idx], defs);
2153 unsigned temp = (unsigned short)raw; // ignore possible min/max values in high words
2154 if (format == RAWFMT_TEMP10X) // -v N,temp10x
2155 temp = (temp+5) / 10;
2156 if (!(0 < temp && temp <= 255))
2157 continue;
2158 return temp;
2159 }
2160 // No valid attribute found
2161 return 0;
2162 }
2163
2164
2165 // Read SCT Status
2166 int ataReadSCTStatus(ata_device * device, ata_sct_status_response * sts)
2167 {
2168 // read SCT status via SMART log 0xe0
2169 memset(sts, 0, sizeof(*sts));
2170 if (smartcommandhandler(device, READ_LOG, 0xe0, (char *)sts)){
2171 syserror("Error Read SCT Status failed");
2172 return -1;
2173 }
2174
2175 // swap endian order if needed
2176 if (isbigendian()){
2177 swapx(&sts->format_version);
2178 swapx(&sts->sct_version);
2179 swapx(&sts->sct_spec);
2180 swapx(&sts->ext_status_code);
2181 swapx(&sts->action_code);
2182 swapx(&sts->function_code);
2183 swapx(&sts->over_limit_count);
2184 swapx(&sts->under_limit_count);
2185 }
2186
2187 // Check format version
2188 if (!(sts->format_version == 2 || sts->format_version == 3)) {
2189 pout("Error unknown SCT Status format version %u, should be 2 or 3.\n", sts->format_version);
2190 return -1;
2191 }
2192 return 0;
2193 }
2194
2195 // Read SCT Temperature History Table and Status
2196 int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table * tmh,
2197 ata_sct_status_response * sts)
2198 {
2199 // Check initial status
2200 if (ataReadSCTStatus(device, sts))
2201 return -1;
2202
2203 // Do nothing if other SCT command is executing
2204 if (sts->ext_status_code == 0xffff) {
2205 pout("Another SCT command is executing, abort Read Data Table\n"
2206 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2207 sts->ext_status_code, sts->action_code, sts->function_code);
2208 return -1;
2209 }
2210
2211 ata_sct_data_table_command cmd; memset(&cmd, 0, sizeof(cmd));
2212 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2213 cmd.action_code = 5; // Data table command
2214 cmd.function_code = 1; // Read table
2215 cmd.table_id = 2; // Temperature History Table
2216
2217 // write command via SMART log page 0xe0
2218 if (smartcommandhandler(device, WRITE_LOG, 0xe0, (char *)&cmd)){
2219 syserror("Error Write SCT Data Table command failed");
2220 return -1;
2221 }
2222
2223 // read SCT data via SMART log page 0xe1
2224 memset(tmh, 0, sizeof(*tmh));
2225 if (smartcommandhandler(device, READ_LOG, 0xe1, (char *)tmh)){
2226 syserror("Error Read SCT Data Table failed");
2227 return -1;
2228 }
2229
2230 // re-read and check SCT status
2231 if (ataReadSCTStatus(device, sts))
2232 return -1;
2233
2234 if (!(sts->ext_status_code == 0 && sts->action_code == 5 && sts->function_code == 1)) {
2235 pout("Error unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2236 sts->ext_status_code, sts->action_code, sts->function_code);
2237 return -1;
2238 }
2239
2240 // swap endian order if needed
2241 if (isbigendian()){
2242 swapx(&tmh->format_version);
2243 swapx(&tmh->sampling_period);
2244 swapx(&tmh->interval);
2245 }
2246
2247 // Check format version
2248 if (tmh->format_version != 2) {
2249 pout("Error unknown SCT Temperature History Format Version (%u), should be 2.\n", tmh->format_version);
2250 return -1;
2251 }
2252 return 0;
2253 }
2254
2255 // Set SCT Temperature Logging Interval
2256 int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persistent)
2257 {
2258 // Check initial status
2259 ata_sct_status_response sts;
2260 if (ataReadSCTStatus(device, &sts))
2261 return -1;
2262
2263 // Do nothing if other SCT command is executing
2264 if (sts.ext_status_code == 0xffff) {
2265 pout("Another SCT command is executing, abort Feature Control\n"
2266 "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
2267 sts.ext_status_code, sts.action_code, sts.function_code);
2268 return -1;
2269 }
2270
2271 ata_sct_feature_control_command cmd; memset(&cmd, 0, sizeof(cmd));
2272 // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
2273 cmd.action_code = 4; // Feature Control command
2274 cmd.function_code = 1; // Set state
2275 cmd.feature_code = 3; // Temperature logging interval
2276 cmd.state = interval;
2277 cmd.option_flags = (persistent ? 0x01 : 0x00);
2278
2279 // write command via SMART log page 0xe0
2280 if (smartcommandhandler(device, WRITE_LOG, 0xe0, (char *)&cmd)){
2281 syserror("Error Write SCT Feature Control Command failed");
2282 return -1;
2283 }
2284
2285 // re-read and check SCT status
2286 if (ataReadSCTStatus(device, &sts))
2287 return -1;
2288
2289 if (!(sts.ext_status_code == 0 && sts.action_code == 4 && sts.function_code == 1)) {
2290 pout("Error unexcepted SCT status 0x%04x (action_code=%u, function_code=%u)\n",
2291 sts.ext_status_code, sts.action_code, sts.function_code);
2292 return -1;
2293 }
2294 return 0;
2295 }
2296
2297 // Print one self-test log entry.
2298 // Returns true if self-test showed an error.
2299 bool ataPrintSmartSelfTestEntry(unsigned testnum, unsigned char test_type,
2300 unsigned char test_status,
2301 unsigned short timestamp,
2302 uint64_t failing_lba,
2303 bool print_error_only, bool & print_header)
2304 {
2305 const char * msgtest;
2306 switch (test_type) {
2307 case 0x00: msgtest = "Offline"; break;
2308 case 0x01: msgtest = "Short offline"; break;
2309 case 0x02: msgtest = "Extended offline"; break;
2310 case 0x03: msgtest = "Conveyance offline"; break;
2311 case 0x04: msgtest = "Selective offline"; break;
2312 case 0x7f: msgtest = "Abort offline test"; break;
2313 case 0x81: msgtest = "Short captive"; break;
2314 case 0x82: msgtest = "Extended captive"; break;
2315 case 0x83: msgtest = "Conveyance captive"; break;
2316 case 0x84: msgtest = "Selective captive"; break;
2317 default:
2318 if ((0x40 <= test_type && test_type <= 0x7e) || 0x90 <= test_type)
2319 msgtest = "Vendor offline";
2320 else
2321 msgtest = "Reserved offline";
2322 }
2323
2324 bool is_error = false;
2325 const char * msgstat;
2326 switch (test_status >> 4) {
2327 case 0x0: msgstat = "Completed without error"; break;
2328 case 0x1: msgstat = "Aborted by host"; break;
2329 case 0x2: msgstat = "Interrupted (host reset)"; break;
2330 case 0x3: msgstat = "Fatal or unknown error"; is_error = true; break;
2331 case 0x4: msgstat = "Completed: unknown failure"; is_error = true; break;
2332 case 0x5: msgstat = "Completed: electrical failure"; is_error = true; break;
2333 case 0x6: msgstat = "Completed: servo/seek failure"; is_error = true; break;
2334 case 0x7: msgstat = "Completed: read failure"; is_error = true; break;
2335 case 0x8: msgstat = "Completed: handling damage??"; is_error = true; break;
2336 case 0xf: msgstat = "Self-test routine in progress"; break;
2337 default: msgstat = "Unknown/reserved test status";
2338 }
2339
2340 if (!is_error && print_error_only)
2341 return false;
2342
2343 // Print header once
2344 if (print_header) {
2345 print_header = false;
2346 pout("Num Test_Description Status Remaining LifeTime(hours) LBA_of_first_error\n");
2347 }
2348
2349 char msglba[32];
2350 if (is_error && failing_lba < 0xffffffffffffULL)
2351 snprintf(msglba, sizeof(msglba), "%"PRIu64, failing_lba);
2352 else
2353 strcpy(msglba, "-");
2354
2355 pout("#%2u %-19s %-29s %1d0%% %8u %s\n", testnum, msgtest, msgstat,
2356 test_status & 0x0f, timestamp, msglba);
2357
2358 return is_error;
2359 }
2360
2361 // Print Smart self-test log, used by smartctl and smartd.
2362 // return value is:
2363 // bottom 8 bits: number of entries found where self-test showed an error
2364 // remaining bits: if nonzero, power on hours of last self-test where error was found
2365 int ataPrintSmartSelfTestlog(const ata_smart_selftestlog * data, bool allentries,
2366 unsigned char fix_firmwarebug)
2367 {
2368 if (allentries)
2369 pout("SMART Self-test log structure revision number %d\n",(int)data->revnumber);
2370 if ((data->revnumber!=0x0001) && allentries && fix_firmwarebug != FIX_SAMSUNG)
2371 pout("Warning: ATA Specification requires self-test log structure revision number = 1\n");
2372 if (data->mostrecenttest==0){
2373 if (allentries)
2374 pout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n\n");
2375 return 0;
2376 }
2377
2378 bool noheaderprinted = true;
2379 int retval=0, hours=0, testno=0;
2380
2381 // print log
2382 for (int i = 20; i >= 0; i--) {
2383 // log is a circular buffer
2384 int j = (i+data->mostrecenttest)%21;
2385 const ata_smart_selftestlog_struct * log = data->selftest_struct+j;
2386
2387 if (nonempty(log, sizeof(*log))) {
2388 // count entry based on non-empty structures -- needed for
2389 // Seagate only -- other vendors don't have blank entries 'in
2390 // the middle'
2391 testno++;
2392
2393 // T13/1321D revision 1c: (Data structure Rev #1)
2394
2395 //The failing LBA shall be the LBA of the uncorrectable sector
2396 //that caused the test to fail. If the device encountered more
2397 //than one uncorrectable sector during the test, this field
2398 //shall indicate the LBA of the first uncorrectable sector
2399 //encountered. If the test passed or the test failed for some
2400 //reason other than an uncorrectable sector, the value of this
2401 //field is undefined.
2402
2403 // This is true in ALL ATA-5 specs
2404 uint64_t lba48 = (log->lbafirstfailure < 0xffffffff ? log->lbafirstfailure : 0xffffffffffffULL);
2405
2406 // Print entry
2407 if (ataPrintSmartSelfTestEntry(testno,
2408 log->selftestnumber, log->selfteststatus,
2409 log->timestamp, lba48, !allentries, noheaderprinted)) {
2410
2411 // Self-test showed an error
2412 retval++;
2413
2414 // keep track of time of most recent error
2415 if (!hours)
2416 hours = log->timestamp;
2417 }
2418 }
2419 }
2420 if (!allentries && retval)
2421 pout("\n");
2422
2423 hours = hours << 8;
2424 return (retval | hours);
2425 }
2426
2427
2428 /////////////////////////////////////////////////////////////////////////////
2429 // Pseudo-device to parse "smartctl -r ataioctl,2 ..." output and simulate
2430 // an ATA device with same behaviour
2431
2432 namespace {
2433
2434 class parsed_ata_device
2435 : public /*implements*/ ata_device_with_command_set
2436 {
2437 public:
2438 parsed_ata_device(smart_interface * intf, const char * dev_name);
2439
2440 virtual ~parsed_ata_device() throw();
2441
2442 virtual bool is_open() const;
2443
2444 virtual bool open();
2445
2446 virtual bool close();
2447
2448 virtual bool ata_identify_is_cached() const;
2449
2450 protected:
2451 virtual int ata_command_interface(smart_command_set command, int select, char * data);
2452
2453 private:
2454 // Table of parsed commands, return value, data
2455 struct parsed_ata_command
2456 {
2457 smart_command_set command;
2458 int select;
2459 int retval, errval;
2460 char * data;
2461 };
2462
2463 enum { max_num_commands = 32 };
2464 parsed_ata_command m_command_table[max_num_commands];
2465
2466 int m_num_commands;
2467 int m_next_replay_command;
2468 bool m_replay_out_of_sync;
2469 bool m_ata_identify_is_cached;
2470 };
2471
2472 static const char * nextline(const char * s, int & lineno)
2473 {
2474 for (s += strcspn(s, "\r\n"); *s == '\r' || *s == '\n'; s++) {
2475 if (*s == '\r' && s[1] == '\n')
2476 s++;
2477 lineno++;
2478 }
2479 return s;
2480 }
2481
2482 static int name2command(const char * s)
2483 {
2484 for (int i = 0; i < (int)(sizeof(commandstrings)/sizeof(commandstrings[0])); i++) {
2485 if (!strcmp(s, commandstrings[i]))
2486 return i;
2487 }
2488 return -1;
2489 }
2490
2491 static bool matchcpy(char * dest, size_t size, const char * src, const regmatch_t & srcmatch)
2492 {
2493 if (srcmatch.rm_so < 0)
2494 return false;
2495 size_t n = srcmatch.rm_eo - srcmatch.rm_so;
2496 if (n >= size)
2497 n = size-1;
2498 memcpy(dest, src + srcmatch.rm_so, n);
2499 dest[n] = 0;
2500 return true;
2501 }
2502
2503 static inline int matchtoi(const char * src, const regmatch_t & srcmatch, int defval)
2504 {
2505 if (srcmatch.rm_so < 0)
2506 return defval;
2507 return atoi(src + srcmatch.rm_so);
2508 }
2509
2510 parsed_ata_device::parsed_ata_device(smart_interface * intf, const char * dev_name)
2511 : smart_device(intf, dev_name, "ata", ""),
2512 m_num_commands(0),
2513 m_next_replay_command(0),
2514 m_replay_out_of_sync(false),
2515 m_ata_identify_is_cached(false)
2516 {
2517 memset(m_command_table, 0, sizeof(m_command_table));
2518 }
2519
2520 parsed_ata_device::~parsed_ata_device() throw()
2521 {
2522 close();
2523 }
2524
2525 bool parsed_ata_device::is_open() const
2526 {
2527 return (m_num_commands > 0);
2528 }
2529
2530 // Parse stdin and build command table
2531 bool parsed_ata_device::open()
2532 {
2533 const char * pathname = get_dev_name();
2534 if (strcmp(pathname, "-"))
2535 return set_err(EINVAL);
2536 pathname = "<stdin>";
2537 // Fill buffer
2538 char buffer[64*1024];
2539 int size = 0;
2540 while (size < (int)sizeof(buffer)) {
2541 int nr = fread(buffer, 1, sizeof(buffer), stdin);
2542 if (nr <= 0)
2543 break;
2544 size += nr;
2545 }
2546 if (size <= 0)
2547 return set_err(ENOENT, "%s: Unexpected EOF", pathname);
2548 if (size >= (int)sizeof(buffer))
2549 return set_err(EIO, "%s: Buffer overflow", pathname);
2550 buffer[size] = 0;
2551
2552 // Regex to match output from "-r ataioctl,2"
2553 static const char pattern[] = "^"
2554 "(" // (1
2555 "REPORT-IOCTL: DeviceF?D?=[^ ]+ Command=([A-Z ]*[A-Z])" // (2)
2556 "(" // (3
2557 "( InputParameter=([0-9]+))?" // (4 (5))
2558 "|"
2559 "( returned (-?[0-9]+)( errno=([0-9]+)[^\r\n]*)?)" // (6 (7) (8 (9)))
2560 ")" // )
2561 "[\r\n]" // EOL match necessary to match optional parts above
2562 "|"
2563 "===== \\[([A-Z ]*[A-Z])\\] DATA START " // (10)
2564 "|"
2565 " *(En|Dis)abled status cached by OS, " // (11)
2566 ")"; // )
2567
2568 // Compile regex
2569 regular_expression regex;
2570 if (!regex.compile(pattern, REG_EXTENDED))
2571 return set_err(EIO, "invalid regex");
2572
2573 // Parse buffer
2574 const char * errmsg = 0;
2575 int i = -1, state = 0, lineno = 1;
2576 for (const char * line = buffer; *line; line = nextline(line, lineno)) {
2577 // Match line
2578 if (!(line[0] == 'R' || line[0] == '=' || line[0] == ' '))
2579 continue;
2580 const int nmatch = 1+11;
2581 regmatch_t match[nmatch];
2582 if (!regex.execute(line, nmatch, match))
2583 continue;
2584
2585 char cmdname[40];
2586 if (matchcpy(cmdname, sizeof(cmdname), line, match[2])) { // "REPORT-IOCTL:... Command=%s ..."
2587 int nc = name2command(cmdname);
2588 if (nc < 0) {
2589 errmsg = "Unknown ATA command name"; break;
2590 }
2591 if (match[7].rm_so < 0) { // "returned %d"
2592 // Start of command
2593 if (!(state == 0 || state == 2)) {
2594 errmsg = "Missing REPORT-IOCTL result"; break;
2595 }
2596 if (++i >= max_num_commands) {
2597 errmsg = "Too many ATA commands"; break;
2598 }
2599 m_command_table[i].command = (smart_command_set)nc;
2600 m_command_table[i].select = matchtoi(line, match[5], 0); // "InputParameter=%d"
2601 state = 1;
2602 }
2603 else {
2604 // End of command
2605 if (!(state == 1 && (int)m_command_table[i].command == nc)) {
2606 errmsg = "Missing REPORT-IOCTL start"; break;
2607 }
2608 m_command_table[i].retval = matchtoi(line, match[7], -1); // "returned %d"
2609 m_command_table[i].errval = matchtoi(line, match[9], 0); // "errno=%d"
2610 state = 2;
2611 }
2612 }
2613 else if (matchcpy(cmdname, sizeof(cmdname), line, match[10])) { // "===== [%s] DATA START "
2614 // Start of sector hexdump
2615 int nc = name2command(cmdname);
2616 if (!(state == (nc == WRITE_LOG ? 1 : 2) && (int)m_command_table[i].command == nc)) {
2617 errmsg = "Unexpected DATA START"; break;
2618 }
2619 line = nextline(line, lineno);
2620 char * data = (char *)malloc(512);
2621 unsigned j;
2622 for (j = 0; j < 32; j++) {
2623 unsigned b[16];
2624 unsigned u1, u2; int n1 = -1;
2625 if (!(sscanf(line, "%3u-%3u: "
2626 "%2x %2x %2x %2x %2x %2x %2x %2x "
2627 "%2x %2x %2x %2x %2x %2x %2x %2x%n",
2628 &u1, &u2,
2629 b+ 0, b+ 1, b+ 2, b+ 3, b+ 4, b+ 5, b+ 6, b+ 7,
2630 b+ 8, b+ 9, b+10, b+11, b+12, b+13, b+14, b+15, &n1) == 18
2631 && n1 >= 56 && u1 == j*16 && u2 == j*16+15))
2632 break;
2633 for (unsigned k = 0; k < 16; k++)
2634 data[j*16+k] = b[k];
2635 line = nextline(line, lineno);
2636 }
2637 if (j < 32) {
2638 free(data);
2639 errmsg = "Incomplete sector hex dump"; break;
2640 }
2641 m_command_table[i].data = data;
2642 if (nc != WRITE_LOG)
2643 state = 0;
2644 }
2645 else if (match[11].rm_so > 0) { // "(En|Dis)abled status cached by OS"
2646 m_ata_identify_is_cached = true;
2647 }
2648 }
2649
2650 if (!(state == 0 || state == 2))
2651 errmsg = "Missing REPORT-IOCTL result";
2652
2653 if (!errmsg && i < 0)
2654 errmsg = "No information found";
2655
2656 m_num_commands = i+1;
2657 m_next_replay_command = 0;
2658 m_replay_out_of_sync = false;
2659
2660 if (errmsg) {
2661 close();
2662 return set_err(EIO, "%s(%d): Syntax error: %s", pathname, lineno, errmsg);
2663 }
2664 return true;
2665 }
2666
2667 // Report warnings and free command table
2668 bool parsed_ata_device::close()
2669 {
2670 if (m_replay_out_of_sync)
2671 pout("REPLAY-IOCTL: Warning: commands replayed out of sync\n");
2672 else if (m_next_replay_command != 0)
2673 pout("REPLAY-IOCTL: Warning: %d command(s) not replayed\n", m_num_commands-m_next_replay_command);
2674
2675 for (int i = 0; i < m_num_commands; i++) {
2676 if (m_command_table[i].data) {
2677 free(m_command_table[i].data); m_command_table[i].data = 0;
2678 }
2679 }
2680 m_num_commands = 0;
2681 m_next_replay_command = 0;
2682 m_replay_out_of_sync = false;
2683 return true;
2684 }
2685
2686
2687 bool parsed_ata_device::ata_identify_is_cached() const
2688 {
2689 return m_ata_identify_is_cached;
2690 }
2691
2692
2693 // Simulate ATA command from command table
2694 int parsed_ata_device::ata_command_interface(smart_command_set command, int select, char * data)
2695 {
2696 // Find command, try round-robin if out of sync
2697 int i = m_next_replay_command;
2698 for (int j = 0; ; j++) {
2699 if (j >= m_num_commands) {
2700 pout("REPLAY-IOCTL: Warning: Command not found\n");
2701 errno = ENOSYS;
2702 return -1;
2703 }
2704 if (m_command_table[i].command == command && m_command_table[i].select == select)
2705 break;
2706 if (!m_replay_out_of_sync) {
2707 m_replay_out_of_sync = true;
2708 pout("REPLAY-IOCTL: Warning: Command #%d is out of sync\n", i+1);
2709 }
2710 if (++i >= m_num_commands)
2711 i = 0;
2712 }
2713 m_next_replay_command = i;
2714 if (++m_next_replay_command >= m_num_commands)
2715 m_next_replay_command = 0;
2716
2717 // Return command data
2718 switch (command) {
2719 case IDENTIFY:
2720 case PIDENTIFY:
2721 case READ_VALUES:
2722 case READ_THRESHOLDS:
2723 case READ_LOG:
2724 if (m_command_table[i].data)
2725 memcpy(data, m_command_table[i].data, 512);
2726 break;
2727 case WRITE_LOG:
2728 if (!(m_command_table[i].data && !memcmp(data, m_command_table[i].data, 512)))
2729 pout("REPLAY-IOCTL: Warning: WRITE LOG data does not match\n");
2730 break;
2731 case CHECK_POWER_MODE:
2732 data[0] = (char)0xff;
2733 default:
2734 break;
2735 }
2736
2737 if (m_command_table[i].errval)
2738 errno = m_command_table[i].errval;
2739 return m_command_table[i].retval;
2740 }
2741
2742 } // namespace
2743
2744 ata_device * get_parsed_ata_device(smart_interface * intf, const char * dev_name)
2745 {
2746 return new parsed_ata_device(intf, dev_name);
2747 }