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