]> git.proxmox.com Git - mirror_smartmontools-debian.git/blame - atacmds.c
add debian specific patches
[mirror_smartmontools-debian.git] / atacmds.c
CommitLineData
832b75ed
GG
1/*
2 * atacmds.c
3 *
4 * Home page of code is: http://smartmontools.sourceforge.net
5 *
6 * Copyright (C) 2002-6 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
8 * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2, or (at your option)
13 * any later version.
14 *
15 * You should have received a copy of the GNU General Public License
16 * (for example COPYING); if not, write to the Free
17 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 *
19 * This code was originally developed as a Senior Thesis by Michael Cornwell
20 * at the Concurrent Systems Laboratory (now part of the Storage Systems
21 * Research Center), Jack Baskin School of Engineering, University of
22 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
23 *
24 */
25
26#include <stdio.h>
27#include <string.h>
28#include <errno.h>
29#include <stdlib.h>
30#include <ctype.h>
31
32#include "config.h"
33#include "int64.h"
34#include "atacmds.h"
35#include "extern.h"
36#include "utility.h"
37
38const char *atacmds_c_cvsid="$Id: atacmds.c,v 1.168 2006/04/12 17:01:46 ballen4705 Exp $"
39ATACMDS_H_CVSID CONFIG_H_CVSID EXTERN_H_CVSID INT64_H_CVSID UTILITY_H_CVSID;
40
41// to hold onto exit code for atexit routine
42extern int exitstatus;
43
44// for passing global control variables
45extern smartmonctrl *con;
46
47// These Drive Identity tables are taken from hdparm 5.2, and are also
48// given in the ATA/ATAPI specs for the IDENTIFY DEVICE command. Note
49// that SMART was first added into the ATA/ATAPI-3 Standard with
50// Revision 3 of the document, July 25, 1995. Look at the "Document
51// Status" revision commands at the beginning of
52// http://www.t13.org/project/d2008r6.pdf to see this.
53#define NOVAL_0 0x0000
54#define NOVAL_1 0xffff
55/* word 81: minor version number */
56#define MINOR_MAX 0x22
57const char *minor_str[] = { /* word 81 value: */
58 "Device does not report version", /* 0x0000 */
59 "ATA-1 X3T9.2 781D prior to revision 4", /* 0x0001 */
60 "ATA-1 published, ANSI X3.221-1994", /* 0x0002 */
61 "ATA-1 X3T9.2 781D revision 4", /* 0x0003 */
62 "ATA-2 published, ANSI X3.279-1996", /* 0x0004 */
63 "ATA-2 X3T10 948D prior to revision 2k", /* 0x0005 */
64 "ATA-3 X3T10 2008D revision 1", /* 0x0006 */ /* SMART NOT INCLUDED */
65 "ATA-2 X3T10 948D revision 2k", /* 0x0007 */
66 "ATA-3 X3T10 2008D revision 0", /* 0x0008 */
67 "ATA-2 X3T10 948D revision 3", /* 0x0009 */
68 "ATA-3 published, ANSI X3.298-199x", /* 0x000a */
69 "ATA-3 X3T10 2008D revision 6", /* 0x000b */ /* 1st VERSION WITH SMART */
70 "ATA-3 X3T13 2008D revision 7 and 7a", /* 0x000c */
71 "ATA/ATAPI-4 X3T13 1153D revision 6", /* 0x000d */
72 "ATA/ATAPI-4 T13 1153D revision 13", /* 0x000e */
73 "ATA/ATAPI-4 X3T13 1153D revision 7", /* 0x000f */
74 "ATA/ATAPI-4 T13 1153D revision 18", /* 0x0010 */
75 "ATA/ATAPI-4 T13 1153D revision 15", /* 0x0011 */
76 "ATA/ATAPI-4 published, ANSI NCITS 317-1998", /* 0x0012 */
77 "ATA/ATAPI-5 T13 1321D revision 3", /* 0x0013 */
78 "ATA/ATAPI-4 T13 1153D revision 14", /* 0x0014 */
79 "ATA/ATAPI-5 T13 1321D revision 1", /* 0x0015 */
80 "ATA/ATAPI-5 published, ANSI NCITS 340-2000", /* 0x0016 */
81 "ATA/ATAPI-4 T13 1153D revision 17", /* 0x0017 */
82 "ATA/ATAPI-6 T13 1410D revision 0", /* 0x0018 */
83 "ATA/ATAPI-6 T13 1410D revision 3a", /* 0x0019 */
84 "ATA/ATAPI-7 T13 1532D revision 1", /* 0x001a */
85 "ATA/ATAPI-6 T13 1410D revision 2", /* 0x001b */
86 "ATA/ATAPI-6 T13 1410D revision 1", /* 0x001c */
87 "reserved", /* 0x001d */
88 "ATA/ATAPI-7 T13 1532D revision 0", /* 0x001e */
89 "reserved", /* 0x001f */
90 "reserved", /* 0x0020 */
91 "ATA/ATAPI-7 T13 1532D revision 4a", /* 0x0021 */
92 "ATA/ATAPI-6 published, ANSI INCITS 361-2002" /* 0x0022 */
93};
94
95// NOTE ATA/ATAPI-4 REV 4 was the LAST revision where the device
96// attribute structures were NOT completely vendor specific. So any
97// disk that is ATA/ATAPI-4 or above can not be trusted to show the
98// vendor values in sensible format.
99
100// Negative values below are because it doesn't support SMART
101const int actual_ver[] = {
102 /* word 81 value: */
103 0, /* 0x0000 WARNING: */
104 1, /* 0x0001 WARNING: */
105 1, /* 0x0002 WARNING: */
106 1, /* 0x0003 WARNING: */
107 2, /* 0x0004 WARNING: This array */
108 2, /* 0x0005 WARNING: corresponds */
109 -3, /*<== */ /* 0x0006 WARNING: *exactly* */
110 2, /* 0x0007 WARNING: to the ATA/ */
111 -3, /*<== */ /* 0x0008 WARNING: ATAPI version */
112 2, /* 0x0009 WARNING: listed in */
113 3, /* 0x000a WARNING: the */
114 3, /* 0x000b WARNING: minor_str */
115 3, /* 0x000c WARNING: array */
116 4, /* 0x000d WARNING: above. */
117 4, /* 0x000e WARNING: */
118 4, /* 0x000f WARNING: If you change */
119 4, /* 0x0010 WARNING: that one, */
120 4, /* 0x0011 WARNING: change this one */
121 4, /* 0x0012 WARNING: too!!! */
122 5, /* 0x0013 WARNING: */
123 4, /* 0x0014 WARNING: */
124 5, /* 0x0015 WARNING: */
125 5, /* 0x0016 WARNING: */
126 4, /* 0x0017 WARNING: */
127 6, /* 0x0018 WARNING: */
128 6, /* 0x0019 WARNING: */
129 7, /* 0x001a WARNING: */
130 6, /* 0x001b WARNING: */
131 6, /* 0x001c WARNING: */
132 0, /* 0x001d WARNING: */
133 7, /* 0x001e WARNING: */
134 0, /* 0x001f WARNING: */
135 0, /* 0x0020 WARNING: */
136 7, /* 0x0021 WARNING: */
137 6 /* 0x0022 WARNING: */
138};
139
140// When you add additional items to this list, you should then:
141// 0 -- update this list
142// 1 -- modify the following function parse_attribute_def()
143// 2 -- if needed, modify ataPrintSmartAttribRawValue()
144// 3 - if needed, modify ataPrintSmartAttribName()
145// 4 -- add #define PRESET_N_DESCRIPTION at top of knowndrives.c
146// 5 -- add drive in question into knowndrives[] table in knowndrives.c
147// 6 -- update smartctl.8
148// 7 -- update smartd.8
149// 8 -- do "make smartd.conf.5" to update smartd.conf.5
150// 9 -- update CHANGELOG file
151const char *vendorattributeargs[] = {
152 // 0 defs[9]=1
153 "9,minutes",
154 // 1 defs[9]=3
155 "9,seconds",
156 // 2 defs[9]=2
157 "9,temp",
158 // 3 defs[220]=1
159 "220,temp",
160 // 4 defs[*]=253
161 "N,raw8",
162 // 5 defs[*]=254
163 "N,raw16",
164 // 6 defs[*]=255
165 "N,raw48",
166 // 7 defs[200]=1
167 "200,writeerrorcount",
168 // 8 defs[9]=4
169 "9,halfminutes",
170 // 9 defs[194]=1
171 "194,10xCelsius",
172 // 10 defs[194]=2
173 "194,unknown",
174 // 11 defs[193]=1
175 "193,loadunload",
176 // 12 defs[201]=1
177 "201,detectedtacount",
178 // 13 defs[192]=1
179 "192,emergencyretractcyclect",
180 // 14 defs[198]=1
181 "198,offlinescanuncsectorct",
182 // NULL should always terminate the array
183 NULL
184};
185
186// This are the meanings of the Self-test failure checkpoint byte.
187// This is in the self-test log at offset 4 bytes into the self-test
188// descriptor and in the SMART READ DATA structure at byte offset
189// 371. These codes are not well documented. The meanings returned by
190// this routine are used (at least) by Maxtor and IBM. Returns NULL if
191// not recognized. Currently the maximum length is 15 bytes.
192const char *SelfTestFailureCodeName(unsigned char which){
193
194 switch (which) {
195 case 0:
196 return "Write_Test";
197 case 1:
198 return "Servo_Basic";
199 case 2:
200 return "Servo_Random";
201 case 3:
202 return "G-list_Scan";
203 case 4:
204 return "Handling_Damage";
205 case 5:
206 return "Read_Scan";
207 default:
208 return NULL;
209 }
210}
211
212// This is a utility function for parsing pairs like "9,minutes" or
213// "220,temp", and putting the correct flag into the attributedefs
214// array. Returns 1 if problem, 0 if pair has been recongized.
215int parse_attribute_def(char *pair, unsigned char **defsptr){
216 int i,j;
217 char temp[32];
218 unsigned char *defs;
219
220 // If array does not exist, allocate it
221 if (!*defsptr && !(*defsptr=(unsigned char *)calloc(MAX_ATTRIBUTE_NUM, 1))){
222 pout("Out of memory in parse_attribute_def\n");
223 EXIT(1);
224 }
225
226 defs=*defsptr;
227
228 // look along list and see if we find the pair
229 for (i=0; vendorattributeargs[i] && strcmp(pair, vendorattributeargs[i]); i++);
230
231 switch (i) {
232 case 0:
233 // attribute 9 is power on time in minutes
234 defs[9]=1;
235 return 0;
236 case 1:
237 // attribute 9 is power-on-time in seconds
238 defs[9]=3;
239 return 0;
240 case 2:
241 // attribute 9 is temperature in celsius
242 defs[9]=2;
243 return 0;
244 case 3:
245 // attribute 220 is temperature in celsius
246 defs[220]=1;
247 return 0;
248 case 4:
249 // print all attributes in raw 8-bit form
250 for (j=0; j<MAX_ATTRIBUTE_NUM; j++)
251 defs[j]=253;
252 return 0;
253 case 5:
254 // print all attributes in raw 16-bit form
255 for (j=0; j<MAX_ATTRIBUTE_NUM; j++)
256 defs[j]=254;
257 return 0;
258 case 6:
259 // print all attributes in raw 48-bit form
260 for (j=0; j<MAX_ATTRIBUTE_NUM; j++)
261 defs[j]=255;
262 return 0;
263 case 7:
264 // attribute 200 is write error count
265 defs[200]=1;
266 return 0;
267 case 8:
268 // attribute 9 increments once every 30 seconds (power on time
269 // measure)
270 defs[9]=4;
271 return 0;
272 case 9:
273 // attribute 194 is ten times disk temp in Celsius
274 defs[194]=1;
275 return 0;
276 case 10:
277 // attribute 194 is unknown
278 defs[194]=2;
279 return 0;
280 case 11:
281 // Hitachi : Attributes 193 has 2 values : 1 load, 1 normal unload
282 defs[193]=1;
283 return 0;
284 case 12:
285 // Fujitsu
286 defs[201]=1;
287 return 0;
288 case 13:
289 // Fujitsu
290 defs[192]=1;
291 return 0;
292 case 14:
293 // Fujitsu
294 defs[198]=1;
295 return 0;
296 default:
297 // pair not found
298 break;
299 }
300 // At this point, either the pair was not found, or it is of the
301 // form N,uninterpreted, in which case we need to parse N
302 j=sscanf(pair,"%d,%14s", &i, temp);
303
304 // if no match to pattern, unrecognized
305 if (j!=2 || i<0 || i >255)
306 return 1;
307
308 // check for recognized strings
309 if (!strcmp(temp, "raw8")) {
310 defs[i]=253;
311 return 0;
312 }
313
314 // check for recognized strings
315 if (!strcmp(temp, "raw16")) {
316 defs[i]=254;
317 return 0;
318 }
319
320 // check for recognized strings
321 if (!strcmp(temp, "raw48")) {
322 defs[i]=255;
323 return 0;
324 }
325
326 // didn't recognize the string
327 return 1;
328}
329
330// Structure used in sorting the array vendorattributeargs[].
331typedef struct vaa_pair_s {
332 const char *vaa;
333 const char *padded_vaa;
334} vaa_pair;
335
336// Returns a copy of s with all numbers of less than three digits padded with
337// leading zeros. Returns NULL if there isn't enough memory available. The
338// memory for the string is dynamically allocated and should be freed by the
339// caller.
340char *pad_numbers(const char *s)
341{
342 char c, *t, *u;
343 const char *r;
344 int i, len, ndigits = 0;
345
346 // Allocate the maximum possible amount of memory needed.
347 if (!(t = (char *)malloc(strlen(s)*2+2)))
348 return NULL;
349
350 // Copy the string s to t, padding any numbers of less than three digits
351 // with leading zeros. The string is copied backwards to simplify the code.
352 r = s + strlen(s);
353 u = t;
354 while (( r-- >= s)) {
355 if (isdigit((int)*r))
356 ndigits++;
357 else if (ndigits > 0) {
358 while (ndigits++ < 3)
359 *u++ = '0';
360 ndigits = 0;
361 }
362 *u++ = *r;
363 }
364 *u = '\0';
365
366 // Reverse the string in t.
367 len = strlen(t);
368 for (i = 0; i < len/2; i++) {
369 c = t[i];
370 t[i] = t[len-1-i];
371 t[len-1-i] = c;
372 }
373
374 return t;
375}
376
377// Comparison function for qsort(). Used by sort_vendorattributeargs().
378int compare_vaa_pairs(const void *a, const void *b)
379{
380 vaa_pair *p = (vaa_pair *)a;
381 vaa_pair *q = (vaa_pair *)b;
382
383 return strcmp(p->padded_vaa, q->padded_vaa);
384}
385
386// Returns a sorted list of vendorattributeargs or NULL if there is not enough
387// memory available. The memory for the list is allocated dynamically and
388// should be freed by the caller.
389// To perform the sort, any numbers in the strings are padded out to three
390// digits by adding leading zeros. For example,
391//
392// "9,minutes" becomes "009,minutes"
393// "N,raw16" becomes "N,raw016"
394//
395// and the original strings are paired with the padded strings. The list of
396// pairs is then sorted by comparing the padded strings (using strcmp) and the
397// result is then the list of unpadded strings.
398//
399const char **sort_vendorattributeargs(void) {
400 const char **ps, **sorted_list = NULL;
401 vaa_pair *pairs, *pp;
402 int count, i;
403
404 // Figure out how many strings are in vendorattributeargs[] (not including
405 // the terminating NULL).
406 count = (sizeof vendorattributeargs) / sizeof(char *) - 1;
407
408 // Construct a list of pairs of strings from vendorattributeargs[] and their
409 // padded equivalents.
410 if (!(pairs = (vaa_pair *)malloc(sizeof(vaa_pair) * count)))
411 goto END;
412 for (ps = vendorattributeargs, pp = pairs; *ps; ps++, pp++) {
413 pp->vaa = *ps;
414 if (!(pp->padded_vaa = pad_numbers(*ps)))
415 goto END;
416 }
417
418 // Sort the array of vaa_pair structures by comparing the padded strings
419 // using strcmp().
420 qsort(pairs, count, sizeof(vaa_pair), compare_vaa_pairs);
421
422 // Construct the sorted list of strings.
423 if (!(sorted_list = (const char **)malloc(sizeof vendorattributeargs)))
424 goto END;
425 for (ps = sorted_list, pp = pairs, i = 0; i < count; ps++, pp++, i++)
426 *ps = pp->vaa;
427 *ps = NULL;
428
429END:
430 if (pairs) {
431 for (i = 0; i < count; i++)
432 if (pairs[i].padded_vaa)
433 free((void *)pairs[i].padded_vaa);
434 free((void *)pairs);
435 }
436
437 // If there was a problem creating the list then sorted_list should now
438 // contain NULL.
439 return sorted_list;
440}
441
442// Function to return a multiline string containing a list of the arguments in
443// vendorattributeargs[]. The strings are preceeded by tabs and followed
444// (except for the last) by newlines.
445// This function allocates the required memory for the string and the caller
446// must use free() to free it. It returns NULL if the required memory can't
447// be allocated.
448char *create_vendor_attribute_arg_list(void){
449 const char **ps, **sorted;
450 char *s;
451 int len;
452
453 // Get a sorted list of vendor attribute arguments. If the sort fails
454 // (which should only happen if the system is really low on memory) then just
455 // use the unordered list.
456 if (!(sorted = (const char **) sort_vendorattributeargs()))
457 sorted = vendorattributeargs;
458
459 // Calculate the required number of characters
460 len = 1; // At least one char ('\0')
461 for (ps = sorted; *ps != NULL; ps++) {
462 len += 1; // For the tab
463 len += strlen(*ps); // For the actual argument string
464 if (*(ps+1))
465 len++; // For the newline if required
466 }
467
468 // Attempt to allocate memory for the string
469 if (!(s = (char *)malloc(len)))
470 return NULL;
471
472 // Construct the string
473 *s = '\0';
474 for (ps = sorted; *ps != NULL; ps++) {
475 strcat(s, "\t");
476 strcat(s, *ps);
477 if (*(ps+1))
478 strcat(s, "\n");
479 }
480
481 free((char **)sorted);
482
483 // Return a pointer to the string
484 return s;
485}
486
487// swap two bytes. Point to low address
488void swap2(char *location){
489 char tmp=*location;
490 *location=*(location+1);
491 *(location+1)=tmp;
492 return;
493}
494
495// swap four bytes. Point to low address
496void swap4(char *location){
497 char tmp=*location;
498 *location=*(location+3);
499 *(location+3)=tmp;
500 swap2(location+1);
501 return;
502}
503
504// swap eight bytes. Points to low address
505void swap8(char *location){
506 char tmp=*location;
507 *location=*(location+7);
508 *(location+7)=tmp;
509 tmp=*(location+1);
510 *(location+1)=*(location+6);
511 *(location+6)=tmp;
512 swap4(location+2);
513 return;
514}
515
516static char *commandstrings[]={
517 "SMART ENABLE",
518 "SMART DISABLE",
519 "SMART AUTOMATIC ATTRIBUTE SAVE",
520 "SMART IMMEDIATE OFFLINE",
521 "SMART AUTO OFFLINE",
522 "SMART STATUS",
523 "SMART STATUS CHECK",
524 "SMART READ ATTRIBUTE VALUES",
525 "SMART READ ATTRIBUTE THRESHOLDS",
526 "SMART READ LOG",
527 "IDENTIFY DEVICE",
528 "IDENTIFY PACKET DEVICE",
529 "CHECK POWER MODE",
530 "SMART WRITE LOG",
531 "WARNING (UNDEFINED COMMAND -- CONTACT DEVELOPERS AT " PACKAGE_BUGREPORT ")\n"
532};
533
534void prettyprint(unsigned char *stuff, char *name){
535 int i,j;
536 pout("\n===== [%s] DATA START (BASE-16) =====\n", name);
537 for (i=0; i<32; i++){
538 pout("%03d-%03d: ", 16*i, 16*(i+1)-1);
539 for (j=0; j<15; j++)
540 pout("%02x ",*stuff++);
541 pout("%02x\n",*stuff++);
542 }
543 pout("===== [%s] DATA END (512 Bytes) =====\n\n", name);
544}
545
546// This function provides the pretty-print reporting for SMART
547// commands: it implements the various -r "reporting" options for ATA
548// ioctls.
549int smartcommandhandler(int device, smart_command_set command, int select, char *data){
550 int retval;
551
552 // This conditional is true for commands that return data
553 int getsdata=(command==PIDENTIFY ||
554 command==IDENTIFY ||
555 command==READ_LOG ||
556 command==READ_THRESHOLDS ||
557 command==READ_VALUES ||
558 command==CHECK_POWER_MODE);
559
560 int sendsdata=(command==WRITE_LOG);
561
562 // If reporting is enabled, say what the command will be before it's executed
563 if (con->reportataioctl){
564 // conditional is true for commands that use parameters
565 int usesparam=(command==READ_LOG ||
566 command==AUTO_OFFLINE ||
567 command==AUTOSAVE ||
568 command==IMMEDIATE_OFFLINE ||
569 command==WRITE_LOG);
570
571 pout("\nREPORT-IOCTL: DeviceFD=%d Command=%s", device, commandstrings[command]);
572 if (usesparam)
573 pout(" InputParameter=%d\n", select);
574 else
575 pout("\n");
576 }
577
578 if ((getsdata || sendsdata) && !data){
579 pout("REPORT-IOCTL: Unable to execute command %s : data destination address is NULL\n", commandstrings[command]);
580 return -1;
581 }
582
583 // The reporting is cleaner, and we will find coding bugs faster, if
584 // the commands that failed clearly return empty (zeroed) data
585 // structures
586 if (getsdata) {
587 if (command==CHECK_POWER_MODE)
588 data[0]=0;
589 else
590 memset(data, '\0', 512);
591 }
592
593
594 // If reporting is enabled, say what input was sent to the command
595 if (con->reportataioctl && sendsdata){
596 pout("REPORT-IOCTL: DeviceFD=%d Command=%s", device, commandstrings[command]);
597 // if requested, pretty-print the output data structure
598 if (con->reportataioctl>1)
599 prettyprint((unsigned char *)data, commandstrings[command]);
600 }
601
602 // In case the command produces an error, we'll want to know what it is:
603 errno=0;
604
605 // now execute the command
606 switch (con->controller_type) {
607 case CONTROLLER_3WARE_678K:
608 case CONTROLLER_3WARE_678K_CHAR:
609 case CONTROLLER_3WARE_9000_CHAR:
610 retval=escalade_command_interface(device, con->controller_port-1, con->controller_type, command, select, data);
611 if (retval && con->controller_port<=0)
612 pout("WARNING: apparently missing '-d 3ware,N' disk specification\n");
613 break;
614 case CONTROLLER_MARVELL_SATA:
615 retval=marvell_command_interface(device, command, select, data);
616 break;
617 default:
618 retval=ata_command_interface(device, command, select, data);
619 }
620
621 // If reporting is enabled, say what output was produced by the command
622 if (con->reportataioctl){
623 if (errno)
624 pout("REPORT-IOCTL: DeviceFD=%d Command=%s returned %d errno=%d [%s]\n",
625 device, commandstrings[command], retval, errno, strerror(errno));
626 else
627 pout("REPORT-IOCTL: DeviceFD=%d Command=%s returned %d\n",
628 device, commandstrings[command], retval);
629
630 // if requested, pretty-print the output data structure
631 if (con->reportataioctl>1 && getsdata) {
632 if (command==CHECK_POWER_MODE)
633 pout("Sector Count Register (BASE-16): %02x\n", (unsigned char)(*data));
634 else
635 prettyprint((unsigned char *)data, commandstrings[command]);
636 }
637 }
638 return retval;
639}
640
641
642// This function computes the checksum of a single disk sector (512
643// bytes). Returns zero if checksum is OK, nonzero if the checksum is
644// incorrect. The size (512) is correct for all SMART structures.
645unsigned char checksum(unsigned char *buffer){
646 unsigned char sum=0;
647 int i;
648
649 for (i=0; i<512; i++)
650 sum+=buffer[i];
651
652 return sum;
653}
654
655// returns -1 if command fails or the device is in Sleep mode, else
656// value of Sector Count register. Sector Count result values:
657// 00h device is in Standby mode.
658// 80h device is in Idle mode.
659// FFh device is in Active mode or Idle mode.
660
661int ataCheckPowerMode(int device) {
662 unsigned char result;
663
664 if ((smartcommandhandler(device, CHECK_POWER_MODE, 0, (char *)&result)))
665 return -1;
666
667 if (result!=0 && result!=0x80 && result!=0xff)
668 pout("ataCheckPowerMode(): ATA CHECK POWER MODE returned unknown Sector Count Register value %02x\n", result);
669
670 return (int)result;
671}
672
673
674
675
676// Reads current Device Identity info (512 bytes) into buf. Returns 0
677// if all OK. Returns -1 if no ATA Device identity can be
678// established. Returns >0 if Device is ATA Packet Device (not SMART
679// capable). The value of the integer helps identify the type of
680// Packet device, which is useful so that the user can connect the
681// formal device number with whatever object is inside their computer.
682int ataReadHDIdentity (int device, struct ata_identify_device *buf){
683 unsigned short *rawshort=(unsigned short *)buf;
684 unsigned char *rawbyte =(unsigned char *)buf;
685
686 // See if device responds either to IDENTIFY DEVICE or IDENTIFY
687 // PACKET DEVICE
688 if ((smartcommandhandler(device, IDENTIFY, 0, (char *)buf))){
689 if (smartcommandhandler(device, PIDENTIFY, 0, (char *)buf)){
690 return -1;
691 }
692 }
693
694#ifndef __NetBSD__
695 // if machine is big-endian, swap byte order as needed
696 // (the NetBSD kernel does deliver the results in host byte order)
697 if (isbigendian()){
698 int i;
699
700 // swap various capability words that are needed
701 for (i=0; i<33; i++)
702 swap2((char *)(buf->words047_079+i));
703
704 for (i=80; i<=87; i++)
705 swap2((char *)(rawshort+i));
706
707 for (i=0; i<168; i++)
708 swap2((char *)(buf->words088_255+i));
709 }
710#endif
711
712 // If there is a checksum there, validate it
713 if ((rawshort[255] & 0x00ff) == 0x00a5 && checksum(rawbyte))
714 checksumwarning("Drive Identity Structure");
715
716 // If this is a PACKET DEVICE, return device type
717 if (rawbyte[1] & 0x80)
718 return 1+(rawbyte[1] & 0x1f);
719
720 // Not a PACKET DEVICE
721 return 0;
722}
723
724// Returns ATA version as an integer, and a pointer to a string
725// describing which revision. Note that Revision 0 of ATA-3 does NOT
726// support SMART. For this one case we return -3 rather than +3 as
727// the version number. See notes above.
728int ataVersionInfo (const char** description, struct ata_identify_device *drive, unsigned short *minor){
729 unsigned short major;
730 int i;
731
732 // check that arrays at the top of this file are defined
733 // consistently
734 if (sizeof(minor_str) != sizeof(char *)*(1+MINOR_MAX)){
735 pout("Internal error in ataVersionInfo(). minor_str[] size %d\n"
736 "is not consistent with value of MINOR_MAX+1 = %d\n",
737 (int)(sizeof(minor_str)/sizeof(char *)), MINOR_MAX+1);
738 fflush(NULL);
739 abort();
740 }
741 if (sizeof(actual_ver) != sizeof(int)*(1+MINOR_MAX)){
742 pout("Internal error in ataVersionInfo(). actual_ver[] size %d\n"
743 "is not consistent with value of MINOR_MAX = %d\n",
744 (int)(sizeof(actual_ver)/sizeof(int)), MINOR_MAX+1);
745 fflush(NULL);
746 abort();
747 }
748
749 // get major and minor ATA revision numbers
750 major=drive->major_rev_num;
751 *minor=drive->minor_rev_num;
752
753 // First check if device has ANY ATA version information in it
754 if (major==NOVAL_0 || major==NOVAL_1) {
755 *description=NULL;
756 return -1;
757 }
758
759 // The minor revision number has more information - try there first
760 if (*minor && (*minor<=MINOR_MAX)){
761 int std = actual_ver[*minor];
762 if (std) {
763 *description=minor_str[*minor];
764 return std;
765 }
766 }
767
768 // HDPARM has a very complicated algorithm from here on. Since SMART only
769 // exists on ATA-3 and later standards, let's punt on this. If you don't
770 // like it, please fix it. The code's in CVS.
771 for (i=15; i>0; i--)
772 if (major & (0x1<<i))
773 break;
774
775 *description=NULL;
776 if (i==0)
777 return 1;
778 else
779 return i;
780}
781
782// returns 1 if SMART supported, 0 if SMART unsupported, -1 if can't tell
783int ataSmartSupport(struct ata_identify_device *drive){
784 unsigned short word82=drive->command_set_1;
785 unsigned short word83=drive->command_set_2;
786
787 // check if words 82/83 contain valid info
788 if ((word83>>14) == 0x01)
789 // return value of SMART support bit
790 return word82 & 0x0001;
791
792 // since we can're rely on word 82, we don't know if SMART supported
793 return -1;
794}
795
796// returns 1 if SMART enabled, 0 if SMART disabled, -1 if can't tell
797int ataIsSmartEnabled(struct ata_identify_device *drive){
798 unsigned short word85=drive->cfs_enable_1;
799 unsigned short word87=drive->csf_default;
800
801 // check if words 85/86/87 contain valid info
802 if ((word87>>14) == 0x01)
803 // return value of SMART enabled bit
804 return word85 & 0x0001;
805
806 // Since we can't rely word85, we don't know if SMART is enabled.
807 return -1;
808}
809
810
811// Reads SMART attributes into *data
812int ataReadSmartValues(int device, struct ata_smart_values *data){
813
814 if (smartcommandhandler(device, READ_VALUES, 0, (char *)data)){
815 syserror("Error SMART Values Read failed");
816 return -1;
817 }
818
819 // compute checksum
820 if (checksum((unsigned char *)data))
821 checksumwarning("SMART Attribute Data Structure");
822
823 // byte swap if needed
824 if (isbigendian()){
825 int i;
826 swap2((char *)&(data->revnumber));
827 swap2((char *)&(data->total_time_to_complete_off_line));
828 swap2((char *)&(data->smart_capability));
829 for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++){
830 struct ata_smart_attribute *x=data->vendor_attributes+i;
831 swap2((char *)&(x->flags));
832 }
833 }
834
835 return 0;
836}
837
838
839// This corrects some quantities that are byte reversed in the SMART
840// SELF TEST LOG
841void fixsamsungselftestlog(struct ata_smart_selftestlog *data){
842 int i;
843
844 // bytes 508/509 (numbered from 0) swapped (swap of self-test index
845 // with one byte of reserved.
846 swap2((char *)&(data->mostrecenttest));
847
848 // LBA low register (here called 'selftestnumber", containing
849 // information about the TYPE of the self-test) is byte swapped with
850 // Self-test execution status byte. These are bytes N, N+1 in the
851 // entries.
852 for (i=0; i<21; i++)
853 swap2((char *)&(data->selftest_struct[i].selftestnumber));
854
855 return;
856}
857
858// Reads the Self Test Log (log #6)
859int ataReadSelfTestLog (int device, struct ata_smart_selftestlog *data){
860
861 // get data from device
862 if (smartcommandhandler(device, READ_LOG, 0x06, (char *)data)){
863 syserror("Error SMART Error Self-Test Log Read failed");
864 return -1;
865 }
866
867 // compute its checksum, and issue a warning if needed
868 if (checksum((unsigned char *)data))
869 checksumwarning("SMART Self-Test Log Structure");
870
871 // fix firmware bugs in self-test log
872 if (con->fixfirmwarebug == FIX_SAMSUNG)
873 fixsamsungselftestlog(data);
874
875 // fix endian order, if needed
876 if (isbigendian()){
877 int i;
878 swap2((char*)&(data->revnumber));
879 for (i=0; i<21; i++){
880 struct ata_smart_selftestlog_struct *x=data->selftest_struct+i;
881 swap2((char *)&(x->timestamp));
882 swap4((char *)&(x->lbafirstfailure));
883 }
884 }
885
886 return 0;
887}
888
889
890// Reads the Log Directory (log #0). Note: NO CHECKSUM!!
891int ataReadLogDirectory (int device, struct ata_smart_log_directory *data){
892
893 // get data from device
894 if (smartcommandhandler(device, READ_LOG, 0x00, (char *)data)){
895 return -1;
896 }
897
898 // swap endian order if needed
899 if (isbigendian()){
900 swap2((char *)&(data->logversion));
901 }
902
903 return 0;
904}
905
906
907// Reads the selective self-test log (log #9)
908int ataReadSelectiveSelfTestLog(int device, struct ata_selective_self_test_log *data){
909
910 // get data from device
911 if (smartcommandhandler(device, READ_LOG, 0x09, (char *)data)){
912 syserror("Error SMART Read Selective Self-Test Log failed");
913 return -1;
914 }
915
916 // compute its checksum, and issue a warning if needed
917 if (checksum((unsigned char *)data))
918 checksumwarning("SMART Selective Self-Test Log Structure");
919
920 // swap endian order if needed
921 if (isbigendian()){
922 int i;
923 swap2((char *)&(data->logversion));
924 for (i=0;i<5;i++){
925 swap8((char *)&(data->span[i].start));
926 swap8((char *)&(data->span[i].end));
927 }
928 swap8((char *)&(data->currentlba));
929 swap2((char *)&(data->currentspan));
930 swap2((char *)&(data->flags));
931 swap2((char *)&(data->pendingtime));
932 }
933
934 if (data->logversion != 1)
935 pout("SMART Selective Self-Test Log Data Structure Revision Number (%d) should be 1\n", data->logversion);
936
937 return 0;
938}
939
940// Writes the selective self-test log (log #9)
941int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv){
942 int i;
943 struct ata_selective_self_test_log sstlog, *data=&sstlog;
944 unsigned char cksum=0;
945 unsigned char *ptr=(unsigned char *)data;
946
947 // Read log
948 if (ataReadSelectiveSelfTestLog(device, data)) {
949 pout("Since Read failed, will not attempt to WRITE Selective Self-test Log\n");
950 return -1;
951 }
952
953 // Fix logversion if needed
954 if (data->logversion !=1) {
955 pout("Error SMART Selective Self-Test Log Data Structure Revision not recognized\n"
956 "Revision number should be 1 but is %d. To be safe, aborting WRITE LOG\n", data->logversion);
957 return -2;
958 }
959
960 // Host is NOT allowed to write selective self-test log if a selective
961 // self-test is in progress.
962 if (0<data->currentspan && data->currentspan<6 && ((sv->self_test_exec_status)>>4)==15) {
963 pout("Error SMART Selective or other Self-Test in progress.\n");
964 return -4;
965 }
966
967 // Clear spans
968 for (i=0; i<5; i++)
969 memset(data->span+i, 0, sizeof(struct test_span));
970
971 // Set spans for testing
972 for (i=0; i<con->smartselectivenumspans; i++){
973 data->span[i].start = con->smartselectivespan[i][0];
974 data->span[i].end = con->smartselectivespan[i][1];
975 }
976
977 // host must initialize to zero before initiating selective self-test
978 data->currentlba=0;
979 data->currentspan=0;
980
981 // Perform off-line scan after selective test?
982 if (1 == con->scanafterselect)
983 // NO
984 data->flags &= ~SELECTIVE_FLAG_DOSCAN;
985 else if (2 == con->scanafterselect)
986 // YES
987 data->flags |= SELECTIVE_FLAG_DOSCAN;
988
989 // Must clear active and pending flags before writing
990 data->flags &= ~(SELECTIVE_FLAG_ACTIVE);
991 data->flags &= ~(SELECTIVE_FLAG_PENDING);
992
993 // modify pending time?
994 if (con->pendingtime)
995 data->pendingtime=(unsigned short)(con->pendingtime-1);
996
997 // Set checksum to zero, then compute checksum
998 data->checksum=0;
999 for (i=0; i<512; i++)
1000 cksum+=ptr[i];
1001 cksum=~cksum;
1002 cksum+=1;
1003 data->checksum=cksum;
1004
1005 // swap endian order if needed
1006 if (isbigendian()){
1007 int i;
1008 swap2((char *)&(data->logversion));
1009 for (i=0;i<5;i++){
1010 swap8((char *)&(data->span[i].start));
1011 swap8((char *)&(data->span[i].end));
1012 }
1013 swap8((char *)&(data->currentlba));
1014 swap2((char *)&(data->currentspan));
1015 swap2((char *)&(data->flags));
1016 swap2((char *)&(data->pendingtime));
1017 }
1018
1019 // write new selective self-test log
1020 if (smartcommandhandler(device, WRITE_LOG, 0x09, (char *)data)){
1021 syserror("Error Write Selective Self-Test Log failed");
1022 return -3;
1023 }
1024
1025 return 0;
1026}
1027
1028// This corrects some quantities that are byte reversed in the SMART
1029// ATA ERROR LOG.
1030void fixsamsungerrorlog(struct ata_smart_errorlog *data){
1031 int i,j;
1032
1033 // FIXED IN SAMSUNG -25 FIRMWARE???
1034 // Device error count in bytes 452-3
1035 swap2((char *)&(data->ata_error_count));
1036
1037 // FIXED IN SAMSUNG -22a FIRMWARE
1038 // step through 5 error log data structures
1039 for (i=0; i<5; i++){
1040 // step through 5 command data structures
1041 for (j=0; j<5; j++)
1042 // Command data structure 4-byte millisec timestamp. These are
1043 // bytes (N+8, N+9, N+10, N+11).
1044 swap4((char *)&(data->errorlog_struct[i].commands[j].timestamp));
1045 // Error data structure two-byte hour life timestamp. These are
1046 // bytes (N+28, N+29).
1047 swap2((char *)&(data->errorlog_struct[i].error_struct.timestamp));
1048 }
1049 return;
1050}
1051
1052// NEEDED ONLY FOR SAMSUNG -22 (some) -23 AND -24?? FIRMWARE
1053void fixsamsungerrorlog2(struct ata_smart_errorlog *data){
1054 // Device error count in bytes 452-3
1055 swap2((char *)&(data->ata_error_count));
1056 return;
1057}
1058
1059// Reads the Summary SMART Error Log (log #1). The Comprehensive SMART
1060// Error Log is #2, and the Extended Comprehensive SMART Error log is
1061// #3
1062int ataReadErrorLog (int device, struct ata_smart_errorlog *data){
1063
1064 // get data from device
1065 if (smartcommandhandler(device, READ_LOG, 0x01, (char *)data)){
1066 syserror("Error SMART Error Log Read failed");
1067 return -1;
1068 }
1069
1070 // compute its checksum, and issue a warning if needed
1071 if (checksum((unsigned char *)data))
1072 checksumwarning("SMART ATA Error Log Structure");
1073
1074 // Some disks have the byte order reversed in some SMART Summary
1075 // Error log entries
1076 if (con->fixfirmwarebug == FIX_SAMSUNG)
1077 fixsamsungerrorlog(data);
1078 else if (con->fixfirmwarebug == FIX_SAMSUNG2)
1079 fixsamsungerrorlog2(data);
1080
1081 // Correct endian order if necessary
1082 if (isbigendian()){
1083 int i,j;
1084
1085 // Device error count in bytes 452-3
1086 swap2((char *)&(data->ata_error_count));
1087
1088 // step through 5 error log data structures
1089 for (i=0; i<5; i++){
1090 // step through 5 command data structures
1091 for (j=0; j<5; j++)
1092 // Command data structure 4-byte millisec timestamp
1093 swap4((char *)&(data->errorlog_struct[i].commands[j].timestamp));
1094 // Error data structure life timestamp
1095 swap2((char *)&(data->errorlog_struct[i].error_struct.timestamp));
1096 }
1097 }
1098
1099 return 0;
1100}
1101
1102int ataReadSmartThresholds (int device, struct ata_smart_thresholds_pvt *data){
1103
1104 // get data from device
1105 if (smartcommandhandler(device, READ_THRESHOLDS, 0, (char *)data)){
1106 syserror("Error SMART Thresholds Read failed");
1107 return -1;
1108 }
1109
1110 // compute its checksum, and issue a warning if needed
1111 if (checksum((unsigned char *)data))
1112 checksumwarning("SMART Attribute Thresholds Structure");
1113
1114 // byte swap if needed
1115 if (isbigendian())
1116 swap2((char *)&(data->revnumber));
1117
1118 return 0;
1119}
1120
1121int ataEnableSmart (int device ){
1122 if (smartcommandhandler(device, ENABLE, 0, NULL)){
1123 syserror("Error SMART Enable failed");
1124 return -1;
1125 }
1126 return 0;
1127}
1128
1129int ataDisableSmart (int device ){
1130
1131 if (smartcommandhandler(device, DISABLE, 0, NULL)){
1132 syserror("Error SMART Disable failed");
1133 return -1;
1134 }
1135 return 0;
1136}
1137
1138int ataEnableAutoSave(int device){
1139 if (smartcommandhandler(device, AUTOSAVE, 241, NULL)){
1140 syserror("Error SMART Enable Auto-save failed");
1141 return -1;
1142 }
1143 return 0;
1144}
1145
1146int ataDisableAutoSave(int device){
1147
1148 if (smartcommandhandler(device, AUTOSAVE, 0, NULL)){
1149 syserror("Error SMART Disable Auto-save failed");
1150 return -1;
1151 }
1152 return 0;
1153}
1154
1155// In *ALL* ATA standards the Enable/Disable AutoOffline command is
1156// marked "OBSOLETE". It is defined in SFF-8035i Revision 2, and most
1157// vendors still support it for backwards compatibility. IBM documents
1158// it for some drives.
1159int ataEnableAutoOffline (int device ){
1160
1161 /* timer hard coded to 4 hours */
1162 if (smartcommandhandler(device, AUTO_OFFLINE, 248, NULL)){
1163 syserror("Error SMART Enable Automatic Offline failed");
1164 return -1;
1165 }
1166 return 0;
1167}
1168
1169// Another Obsolete Command. See comments directly above, associated
1170// with the corresponding Enable command.
1171int ataDisableAutoOffline (int device ){
1172
1173 if (smartcommandhandler(device, AUTO_OFFLINE, 0, NULL)){
1174 syserror("Error SMART Disable Automatic Offline failed");
1175 return -1;
1176 }
1177 return 0;
1178}
1179
1180// If SMART is enabled, supported, and working, then this call is
1181// guaranteed to return 1, else zero. Note that it should return 1
1182// regardless of whether the disk's SMART status is 'healthy' or
1183// 'failing'.
1184int ataDoesSmartWork(int device){
1185 int retval=smartcommandhandler(device, STATUS, 0, NULL);
1186
1187 if (-1 == retval)
1188 return 0;
1189
1190 return 1;
1191}
1192
1193// This function uses a different interface (DRIVE_TASK) than the
1194// other commands in this file.
1195int ataSmartStatus2(int device){
1196 return smartcommandhandler(device, STATUS_CHECK, 0, NULL);
1197}
1198
1199// This is the way to execute ALL tests: offline, short self-test,
1200// extended self test, with and without captive mode, etc.
1201int ataSmartTest(int device, int testtype, struct ata_smart_values *sv) {
1202 char cmdmsg[128],*type,*captive;
1203 int errornum, cap, retval, select=0;
1204
1205 // Boolean, if set, says test is captive
1206 cap=testtype & CAPTIVE_MASK;
1207
1208 // Set up strings that describe the type of test
1209 if (cap)
1210 captive="captive";
1211 else
1212 captive="off-line";
1213
1214 if (testtype==OFFLINE_FULL_SCAN)
1215 type="off-line";
1216 else if (testtype==SHORT_SELF_TEST || testtype==SHORT_CAPTIVE_SELF_TEST)
1217 type="Short self-test";
1218 else if (testtype==EXTEND_SELF_TEST || testtype==EXTEND_CAPTIVE_SELF_TEST)
1219 type="Extended self-test";
1220 else if (testtype==CONVEYANCE_SELF_TEST || testtype==CONVEYANCE_CAPTIVE_SELF_TEST)
1221 type="Conveyance self-test";
1222 else if ((select=(testtype==SELECTIVE_SELF_TEST || testtype==SELECTIVE_CAPTIVE_SELF_TEST)))
1223 type="Selective self-test";
1224 else
1225 type="[Unrecognized] self-test";
1226
1227 // If doing a selective self-test, first use WRITE_LOG to write the
1228 // selective self-test log.
1229 if (select && (retval=ataWriteSelectiveSelfTestLog(device, sv))) {
1230 if (retval==-4)
1231 pout("Can't start selective self-test without aborting current test: use '-X' option to smartctl.\n");
1232 return retval;
1233 }
1234
1235 // Print ouf message that we are sending the command to test
1236 if (testtype==ABORT_SELF_TEST)
1237 sprintf(cmdmsg,"Abort SMART off-line mode self-test routine");
1238 else
1239 sprintf(cmdmsg,"Execute SMART %s routine immediately in %s mode",type,captive);
1240 pout("Sending command: \"%s\".\n",cmdmsg);
1241
1242 if (select) {
1243 int i;
1244 pout("SPAN STARTING_LBA ENDING_LBA\n");
1245 for (i = 0; i < con->smartselectivenumspans; i++)
1246 pout(" %d %20"PRId64" %20"PRId64"\n", i,
1247 con->smartselectivespan[i][0],
1248 con->smartselectivespan[i][1]);
1249 }
1250
1251 // Now send the command to test
1252 errornum=smartcommandhandler(device, IMMEDIATE_OFFLINE, testtype, NULL);
1253
1254 if (errornum && !(cap && errno==EIO)){
1255 char errormsg[128];
1256 sprintf(errormsg,"Command \"%s\" failed",cmdmsg);
1257 syserror(errormsg);
1258 pout("\n");
1259 return -1;
1260 }
1261
1262 // Since the command succeeded, tell user
1263 if (testtype==ABORT_SELF_TEST)
1264 pout("Self-testing aborted!\n");
1265 else
1266 pout("Drive command \"%s\" successful.\nTesting has begun.\n",cmdmsg);
1267 return 0;
1268}
1269
1270/* Test Time Functions */
1271int TestTime(struct ata_smart_values *data,int testtype){
1272 switch (testtype){
1273 case OFFLINE_FULL_SCAN:
1274 return (int) data->total_time_to_complete_off_line;
1275 case SHORT_SELF_TEST:
1276 case SHORT_CAPTIVE_SELF_TEST:
1277 return (int) data->short_test_completion_time;
1278 case EXTEND_SELF_TEST:
1279 case EXTEND_CAPTIVE_SELF_TEST:
1280 return (int) data->extend_test_completion_time;
1281 case CONVEYANCE_SELF_TEST:
1282 case CONVEYANCE_CAPTIVE_SELF_TEST:
1283 return (int) data->conveyance_test_completion_time;
1284 default:
1285 return 0;
1286 }
1287}
1288
1289// This function tells you both about the ATA error log and the
1290// self-test error log capability (introduced in ATA-5). The bit is
1291// poorly documented in the ATA/ATAPI standard. Starting with ATA-6,
1292// SMART error logging is also indicated in bit 0 of DEVICE IDENTIFY
1293// word 84 and 87. Top two bits must match the pattern 01. BEFORE
1294// ATA-6 these top two bits still had to match the pattern 01, but the
1295// remaining bits were reserved (==0).
1296int isSmartErrorLogCapable (struct ata_smart_values *data, struct ata_identify_device *identity){
1297
1298 unsigned short word84=identity->command_set_extension;
1299 unsigned short word87=identity->csf_default;
1300 int isata6=identity->major_rev_num & (0x01<<6);
1301 int isata7=identity->major_rev_num & (0x01<<7);
1302
1303 if ((isata6 || isata7) && (word84>>14) == 0x01 && (word84 & 0x01))
1304 return 1;
1305
1306 if ((isata6 || isata7) && (word87>>14) == 0x01 && (word87 & 0x01))
1307 return 1;
1308
1309 // otherwise we'll use the poorly documented capability bit
1310 return data->errorlog_capability & 0x01;
1311}
1312
1313// See previous function. If the error log exists then the self-test
1314// log should (must?) also exist.
1315int isSmartTestLogCapable (struct ata_smart_values *data, struct ata_identify_device *identity){
1316
1317 unsigned short word84=identity->command_set_extension;
1318 unsigned short word87=identity->csf_default;
1319 int isata6=identity->major_rev_num & (0x01<<6);
1320 int isata7=identity->major_rev_num & (0x01<<7);
1321
1322 if ((isata6 || isata7) && (word84>>14) == 0x01 && (word84 & 0x02))
1323 return 1;
1324
1325 if ((isata6 || isata7) && (word87>>14) == 0x01 && (word87 & 0x02))
1326 return 1;
1327
1328
1329 // otherwise we'll use the poorly documented capability bit
1330 return data->errorlog_capability & 0x01;
1331}
1332
1333
1334int isGeneralPurposeLoggingCapable(struct ata_identify_device *identity){
1335 unsigned short word84=identity->command_set_extension;
1336 unsigned short word87=identity->csf_default;
1337
1338 // If bit 14 of word 84 is set to one and bit 15 of word 84 is
1339 // cleared to zero, the contents of word 84 contains valid support
1340 // information. If not, support information is not valid in this
1341 // word.
1342 if ((word84>>14) == 0x01)
1343 // If bit 5 of word 84 is set to one, the device supports the
1344 // General Purpose Logging feature set.
1345 return (word84 & (0x01 << 5));
1346
1347 // If bit 14 of word 87 is set to one and bit 15 of word 87 is
1348 // cleared to zero, the contents of words (87:85) contain valid
1349 // information. If not, information is not valid in these words.
1350 if ((word87>>14) == 0x01)
1351 // If bit 5 of word 87 is set to one, the device supports
1352 // the General Purpose Logging feature set.
1353 return (word87 & (0x01 << 5));
1354
1355 // not capable
1356 return 0;
1357}
1358
1359
1360// SMART self-test capability is also indicated in bit 1 of DEVICE
1361// IDENTIFY word 87 (if top two bits of word 87 match pattern 01).
1362// However this was only introduced in ATA-6 (but self-test log was in
1363// ATA-5).
1364int isSupportExecuteOfflineImmediate(struct ata_smart_values *data){
1365 return data->offline_data_collection_capability & 0x01;
1366}
1367// Note in the ATA-5 standard, the following bit is listed as "Vendor
1368// Specific". So it may not be reliable. The only use of this that I
1369// have found is in IBM drives, where it is well-documented. See for
1370// example page 170, section 13.32.1.18 of the IBM Travelstar 40GNX
1371// hard disk drive specifications page 164 Revision 1.1 22 Apr 2002.
1372int isSupportAutomaticTimer(struct ata_smart_values *data){
1373 return data->offline_data_collection_capability & 0x02;
1374}
1375int isSupportOfflineAbort(struct ata_smart_values *data){
1376 return data->offline_data_collection_capability & 0x04;
1377}
1378int isSupportOfflineSurfaceScan(struct ata_smart_values *data){
1379 return data->offline_data_collection_capability & 0x08;
1380}
1381int isSupportSelfTest (struct ata_smart_values *data){
1382 return data->offline_data_collection_capability & 0x10;
1383}
1384int isSupportConveyanceSelfTest(struct ata_smart_values *data){
1385 return data->offline_data_collection_capability & 0x20;
1386}
1387int isSupportSelectiveSelfTest(struct ata_smart_values *data){
1388 return data->offline_data_collection_capability & 0x40;
1389}
1390
1391
1392
1393// Loop over all valid attributes. If they are prefailure attributes
1394// and are at or below the threshold value, then return the ID of the
1395// first failing attribute found. Return 0 if all prefailure
1396// attributes are in bounds. The spec says "Bit 0
1397// -Pre-failure/advisory - If the value of this bit equals zero, an
1398// attribute value less than or equal to its corresponding attribute
1399// threshold indicates an advisory condition where the usage or age of
1400// the device has exceeded its intended design life period. If the
1401// value of this bit equals one, an atribute value less than or equal
1402// to its corresponding attribute threshold indicates a pre-failure
1403// condition where imminent loss of data is being predicted."
1404
1405
1406// onlyfailed=0 : are or were any age or prefailure attributes <= threshold
1407// onlyfailed=1: are any prefailure attributes <= threshold now
1408int ataCheckSmart(struct ata_smart_values *data,
1409 struct ata_smart_thresholds_pvt *thresholds,
1410 int onlyfailed){
1411 int i;
1412
1413 // loop over all attributes
1414 for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++){
1415
1416 // pointers to disk's values and vendor's thresholds
1417 struct ata_smart_attribute *disk=data->vendor_attributes+i;
1418 struct ata_smart_threshold_entry *thre=thresholds->thres_entries+i;
1419
1420 // consider only valid attributes
1421 if (disk->id && thre->id){
1422 int failednow,failedever;
1423
1424 failednow =disk->current <= thre->threshold;
1425 failedever=disk->worst <= thre->threshold;
1426
1427 if (!onlyfailed && failedever)
1428 return disk->id;
1429
1430 if (onlyfailed && failednow && ATTRIBUTE_FLAGS_PREFAILURE(disk->flags))
1431 return disk->id;
1432 }
1433 }
1434 return 0;
1435}
1436
1437
1438
1439// This checks the n'th attribute in the attribute list, NOT the
1440// attribute with id==n. If the attribute does not exist, or the
1441// attribute is > threshold, then returns zero. If the attribute is
1442// <= threshold (failing) then we the attribute number if it is a
1443// prefail attribute. Else we return minus the attribute number if it
1444// is a usage attribute.
1445int ataCheckAttribute(struct ata_smart_values *data,
1446 struct ata_smart_thresholds_pvt *thresholds,
1447 int n){
1448 struct ata_smart_attribute *disk;
1449 struct ata_smart_threshold_entry *thre;
1450
1451 if (n<0 || n>=NUMBER_ATA_SMART_ATTRIBUTES || !data || !thresholds)
1452 return 0;
1453
1454 // pointers to disk's values and vendor's thresholds
1455 disk=data->vendor_attributes+n;
1456 thre=thresholds->thres_entries+n;
1457
1458 if (!disk || !thre)
1459 return 0;
1460
1461 // consider only valid attributes, check for failure
1462 if (!disk->id || !thre->id || (disk->id != thre->id) || disk->current> thre->threshold)
1463 return 0;
1464
1465 // We have found a failed attribute. Return positive or negative?
1466 if (ATTRIBUTE_FLAGS_PREFAILURE(disk->flags))
1467 return disk->id;
1468 else
1469 return -1*(disk->id);
1470}
1471
1472
1473// This routine prints the raw value of an attribute as a text string
1474// into out. It also returns this 48-bit number as a long long. The
1475// array defs[] contains non-zero values if particular attributes have
1476// non-default interpretations.
1477
1478int64_t ataPrintSmartAttribRawValue(char *out,
1479 struct ata_smart_attribute *attribute,
1480 unsigned char *defs){
1481 int64_t rawvalue;
1482 unsigned word[3];
1483 int j;
1484 unsigned char select;
1485
1486 // convert the six individual bytes to a long long (8 byte) integer.
1487 // This is the value that we'll eventually return.
1488 rawvalue = 0;
1489 for (j=0; j<6; j++) {
1490 // This looks a bit roundabout, but is necessary. Don't
1491 // succumb to the temptation to use raw[j]<<(8*j) since under
1492 // the normal rules this will be promoted to the native type.
1493 // On a 32 bit machine this might then overflow.
1494 int64_t temp;
1495 temp = attribute->raw[j];
1496 temp <<= 8*j;
1497 rawvalue |= temp;
1498 }
1499
1500 // convert quantities to three two-byte words
1501 for (j=0; j<3; j++){
1502 word[j] = attribute->raw[2*j+1];
1503 word[j] <<= 8;
1504 word[j] |= attribute->raw[2*j];
1505 }
1506
1507 // if no data array, Attributes have default interpretations
1508 if (defs)
1509 select=defs[attribute->id];
1510 else
1511 select=0;
1512
1513 // Print six one-byte quantities.
1514 if (select==253){
1515 for (j=0; j<5; j++)
1516 out+=sprintf(out, "%d ", attribute->raw[5-j]);
1517 out+=sprintf(out, "%d ", attribute->raw[0]);
1518 return rawvalue;
1519 }
1520
1521 // Print three two-byte quantities
1522 if (select==254){
1523 out+=sprintf(out, "%d %d %d", word[2], word[1], word[0]);
1524 return rawvalue;
1525 }
1526
1527 // Print one six-byte quantity
1528 if (select==255){
1529 out+=sprintf(out, "%"PRIu64, rawvalue);
1530 return rawvalue;
1531 }
1532
1533 // This switch statement is where we handle Raw attributes
1534 // that are stored in an unusual vendor-specific format,
1535 switch (attribute->id){
1536 // Spin-up time
1537 case 3:
1538 out+=sprintf(out, "%d", word[0]);
1539 // if second nonzero then it stores the average spin-up time
1540 if (word[1])
1541 out+=sprintf(out, " (Average %d)", word[1]);
1542 break;
1543 // Power on time
1544 case 9:
1545 if (select==1){
1546 // minutes
1547 int64_t tmp1=rawvalue/60;
1548 int64_t tmp2=rawvalue%60;
1549 out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
1550 }
1551 else if (select==3){
1552 // seconds
1553 int64_t hours=rawvalue/3600;
1554 int64_t minutes=(rawvalue-3600*hours)/60;
1555 int64_t seconds=rawvalue%60;
1556 out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m+%02"PRIu64"s", hours, minutes, seconds);
1557 }
1558 else if (select==4){
1559 // 30-second counter
1560 int64_t tmp1=rawvalue/120;
1561 int64_t tmp2=(rawvalue-120*tmp1)/2;
1562 out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
1563 }
1564 else
1565 // hours
1566 out+=sprintf(out, "%"PRIu64, rawvalue); //stored in hours
1567 break;
1568 // Load unload cycles
1569 case 193:
1570 if (select==1){
1571 // loadunload
1572 long load =attribute->raw[0] + (attribute->raw[1]<<8) + (attribute->raw[2]<<16);
1573 long unload=attribute->raw[3] + (attribute->raw[4]<<8) + (attribute->raw[5]<<16);
1574 out+=sprintf(out, "%lu/%lu", load, unload);
1575 }
1576 else
1577 // associated
1578 out+=sprintf(out, "%"PRIu64, rawvalue);
1579 break;
1580 // Temperature
1581 case 194:
1582 if (select==1){
1583 // ten times temperature in Celsius
1584 int deg=word[0]/10;
1585 int tenths=word[0]%10;
1586 out+=sprintf(out, "%d.%d", deg, tenths);
1587 }
1588 else if (select==2)
1589 // unknown attribute
1590 out+=sprintf(out, "%"PRIu64, rawvalue);
1591 else {
1592 out+=sprintf(out, "%d", word[0]);
1593 if (!(rawvalue==word[0])) {
1594 int min=word[1]<word[2]?word[1]:word[2];
1595 int max=word[1]>word[2]?word[1]:word[2];
1596 // The other bytes are in use. Try IBM's model
1597 out+=sprintf(out, " (Lifetime Min/Max %d/%d)", min, max);
1598 }
1599 }
1600 break;
1601 default:
1602 out+=sprintf(out, "%"PRIu64, rawvalue);
1603 }
1604
1605 // Return the full value
1606 return rawvalue;
1607}
1608
1609
1610// Note some attribute names appear redundant because different
1611// manufacturers use different attribute IDs for an attribute with the
1612// same name. The variable val should contain a non-zero value if a particular
1613// attributes has a non-default interpretation.
1614void ataPrintSmartAttribName(char *out, unsigned char id, unsigned char *definitions){
1615 char *name;
1616 unsigned char val;
1617
1618 // If no data array, use default interpretations
1619 if (definitions)
1620 val=definitions[id];
1621 else
1622 val=0;
1623
1624 switch (id){
1625
1626 case 1:
1627 name="Raw_Read_Error_Rate";
1628 break;
1629 case 2:
1630 name="Throughput_Performance";
1631 break;
1632 case 3:
1633 name="Spin_Up_Time";
1634 break;
1635 case 4:
1636 name="Start_Stop_Count";
1637 break;
1638 case 5:
1639 name="Reallocated_Sector_Ct";
1640 break;
1641 case 6:
1642 name="Read_Channel_Margin";
1643 break;
1644 case 7:
1645 name="Seek_Error_Rate";
1646 break;
1647 case 8:
1648 name="Seek_Time_Performance";
1649 break;
1650 case 9:
1651 switch (val) {
1652 case 1:
1653 name="Power_On_Minutes";
1654 break;
1655 case 2:
1656 name="Temperature_Celsius";
1657 break;
1658 case 3:
1659 name="Power_On_Seconds";
1660 break;
1661 case 4:
1662 name="Power_On_Half_Minutes";
1663 break;
1664 default:
1665 name="Power_On_Hours";
1666 break;
1667 }
1668 break;
1669 case 10:
1670 name="Spin_Retry_Count";
1671 break;
1672 case 11:
1673 name="Calibration_Retry_Count";
1674 break;
1675 case 12:
1676 name="Power_Cycle_Count";
1677 break;
1678 case 13:
1679 name="Read_Soft_Error_Rate";
1680 break;
1681 case 191:
1682 name="G-Sense_Error_Rate";
1683 break;
1684 case 192:
1685 switch (val) {
1686 case 1:
1687 // Fujitsu
1688 name="Emergency_Retract_Cycle_Ct";
1689 break;
1690 default:
1691 name="Power-Off_Retract_Count";
1692 break;
1693 }
1694 break;
1695 case 193:
1696 name="Load_Cycle_Count";
1697 break;
1698 case 194:
1699 switch (val){
1700 case 1:
1701 // Samsung SV1204H with RK100-13 firmware
1702 name="Temperature_Celsius_x10";
1703 break;
1704 case 2:
1705 // for disks with no temperature Attribute
1706 name="Unknown_Attribute";
1707 break;
1708 default:
1709 name="Temperature_Celsius";
1710 break;
1711 }
1712 break;
1713 case 195:
1714 // Fujitsu name="ECC_On_The_Fly_Count";
1715 name="Hardware_ECC_Recovered";
1716 break;
1717 case 196:
1718 name="Reallocated_Event_Count";
1719 break;
1720 case 197:
1721 name="Current_Pending_Sector";
1722 break;
1723 case 198:
1724 switch (val){
1725 case 1:
1726 // Fujitsu
1727 name="Off-line_Scan_UNC_Sector_Ct";
1728 break;
1729 default:
1730 name="Offline_Uncorrectable";
1731 break;
1732 }
1733 break;
1734 case 199:
1735 name="UDMA_CRC_Error_Count";
1736 break;
1737 case 200:
1738 switch (val) {
1739 case 1:
1740 // Fujitsu MHS2020AT
1741 name="Write_Error_Count";
1742 break;
1743 default:
1744 // Western Digital
1745 name="Multi_Zone_Error_Rate";
1746 break;
1747 }
1748 break;
1749 case 201:
1750 switch (val) {
1751 case 1:
1752 // Fujitsu
1753 name="Detected_TA_Count";
1754 break;
1755 default:
1756 name="Soft_Read_Error_Rate";
1757 break;
1758 }
1759 break;
1760 case 202:
1761 // Fujitsu
1762 name="TA_Increase_Count";
1763 // Maxtor: Data Address Mark Errors
1764 break;
1765 case 203:
1766 // Fujitsu
1767 name="Run_Out_Cancel";
1768 // Maxtor: ECC Errors
1769 break;
1770 case 204:
1771 // Fujitsu
1772 name="Shock_Count_Write_Opern";
1773 // Maxtor: Soft ECC Correction
1774 break;
1775 case 205:
1776 // Fujitsu
1777 name="Shock_Rate_Write_Opern";
1778 // Maxtor: Thermal Aspirates
1779 break;
1780 case 206:
1781 // Fujitsu
1782 name="Flying_Height";
1783 break;
1784 case 207:
1785 // Maxtor
1786 name="Spin_High_Current";
1787 break;
1788 case 208:
1789 // Maxtor
1790 name="Spin_Buzz";
1791 break;
1792 case 209:
1793 // Maxtor
1794 name="Offline_Seek_Performnce";
1795 break;
1796 case 220:
1797 switch (val) {
1798 case 1:
1799 name="Temperature_Celsius";
1800 break;
1801 default:
1802 name="Disk_Shift";
1803 break;
1804 }
1805 break;
1806 case 221:
1807 name="G-Sense_Error_Rate";
1808 break;
1809 case 222:
1810 name="Loaded_Hours";
1811 break;
1812 case 223:
1813 name="Load_Retry_Count";
1814 break;
1815 case 224:
1816 name="Load_Friction";
1817 break;
1818 case 225:
1819 name="Load_Cycle_Count";
1820 break;
1821 case 226:
1822 name="Load-in_Time";
1823 break;
1824 case 227:
1825 name="Torq-amp_Count";
1826 break;
1827 case 228:
1828 name="Power-off_Retract_Count";
1829 break;
1830 case 230:
1831 // seen in IBM DTPA-353750
1832 name="Head_Amplitude";
1833 break;
1834 case 231:
1835 name="Temperature_Celsius";
1836 break;
1837 case 240:
1838 name="Head_Flying_Hours";
1839 break;
1840 case 250:
1841 name="Read_Error_Retry_Rate";
1842 break;
1843 default:
1844 name="Unknown_Attribute";
1845 break;
1846 }
1847 sprintf(out,"%3hu %s",(short int)id,name);
1848 return;
1849}
1850
1851// Returns raw value of Attribute with ID==id. This will be in the
1852// range 0 to 2^48-1 inclusive. If the Attribute does not exist,
1853// return -1.
1854int64_t ATAReturnAttributeRawValue(unsigned char id, struct ata_smart_values *data) {
1855 int i;
1856
1857 // valid Attribute IDs are in the range 1 to 255 inclusive.
1858 if (!id || !data)
1859 return -1;
1860
1861 // loop over Attributes to see if there is one with the desired ID
1862 for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++) {
1863 struct ata_smart_attribute *this = data->vendor_attributes + i;
1864 if (this->id == id) {
1865 // we've found the desired Attribute. Return its value
1866 int64_t rawvalue=0;
1867 int j;
1868
1869 for (j=0; j<6; j++) {
1870 // This looks a bit roundabout, but is necessary. Don't
1871 // succumb to the temptation to use raw[j]<<(8*j) since under
1872 // the normal rules this will be promoted to the native type.
1873 // On a 32 bit machine this might then overflow.
1874 int64_t temp;
1875 temp = this->raw[j];
1876 temp <<= 8*j;
1877 rawvalue |= temp;
1878 } // loop over j
1879 return rawvalue;
1880 } // found desired Attribute
1881 } // loop over Attributes
1882
1883 // fall-through: no such Attribute found
1884 return -1;
1885}
1886
1887