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