]> git.proxmox.com Git - mirror_smartmontools-debian.git/blob - ataprint.cpp
Merge branch 'upstream'
[mirror_smartmontools-debian.git] / ataprint.cpp
1 /*
2 * ataprint.cpp
3 *
4 * Home page of code is: http://smartmontools.sourceforge.net
5 *
6 * Copyright (C) 2002-7 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2, or (at your option)
12 * any later version.
13 *
14 * You should have received a copy of the GNU General Public License
15 * (for example COPYING); if not, write to the Free
16 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 *
18 * This code was originally developed as a Senior Thesis by Michael Cornwell
19 * at the Concurrent Systems Laboratory (now part of the Storage Systems
20 * Research Center), Jack Baskin School of Engineering, University of
21 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
22 *
23 */
24
25 #include "config.h"
26
27 #include <ctype.h>
28 #include <errno.h>
29 #include <stdio.h>
30 #include <string.h>
31 #ifdef HAVE_LOCALE_H
32 #include <locale.h>
33 #endif // #ifdef HAVE_LOCALE_H
34
35 #include "int64.h"
36 #include "atacmdnames.h"
37 #include "atacmds.h"
38 #include "ataprint.h"
39 #include "smartctl.h"
40 #include "extern.h"
41 #include "utility.h"
42 #include "knowndrives.h"
43
44 const char *ataprint_c_cvsid="$Id: ataprint.cpp,v 1.184 2007/12/08 13:04:05 chrfranke Exp $"
45 ATACMDNAMES_H_CVSID ATACMDS_H_CVSID ATAPRINT_H_CVSID CONFIG_H_CVSID EXTERN_H_CVSID INT64_H_CVSID KNOWNDRIVES_H_CVSID SMARTCTL_H_CVSID UTILITY_H_CVSID;
46
47 // for passing global control variables
48 extern smartmonctrl *con;
49
50 // to hold onto exit code for atexit routine
51 extern int exitstatus;
52
53 // Copies n bytes (or n-1 if n is odd) from in to out, but swaps adjacents
54 // bytes.
55 void swapbytes(char *out, const char *in, size_t n)
56 {
57 size_t i;
58
59 for (i = 0; i < n; i += 2) {
60 out[i] = in[i+1];
61 out[i+1] = in[i];
62 }
63 }
64
65 // Copies in to out, but removes leading and trailing whitespace.
66 void trim(char *out, const char *in)
67 {
68 int i, first, last;
69
70 // Find the first non-space character (maybe none).
71 first = -1;
72 for (i = 0; in[i]; i++)
73 if (!isspace((int)in[i])) {
74 first = i;
75 break;
76 }
77
78 if (first == -1) {
79 // There are no non-space characters.
80 out[0] = '\0';
81 return;
82 }
83
84 // Find the last non-space character.
85 for (i = strlen(in)-1; i >= first && isspace((int)in[i]); i--)
86 ;
87 last = i;
88
89 strncpy(out, in+first, last-first+1);
90 out[last-first+1] = '\0';
91 }
92
93 // Convenience function for formatting strings from ata_identify_device
94 void format_ata_string(char *out, const char *in, int n)
95 {
96 bool must_swap = !con->fixswappedid;
97 #ifdef __NetBSD__
98 /* NetBSD kernel delivers IDENTIFY data in host byte order (but all else is LE) */
99 if (isbigendian())
100 must_swap = !must_swap;
101 #endif
102
103 char tmp[65];
104 n = n > 64 ? 64 : n;
105 if (!must_swap)
106 strncpy(tmp, in, n);
107 else
108 swapbytes(tmp, in, n);
109 tmp[n] = '\0';
110 trim(out, tmp);
111 }
112
113 static const char * infofound(const char *output) {
114 return (*output ? output : "[No Information Found]");
115 }
116
117
118 /* For the given Command Register (CR) and Features Register (FR), attempts
119 * to construct a string that describes the contents of the Status
120 * Register (ST) and Error Register (ER). The string is dynamically allocated
121 * memory and the return value is a pointer to this string. It is up to the
122 * caller to free this memory. If there is insufficient memory or if the
123 * meanings of the flags of the error register are not known for the given
124 * command then it returns NULL.
125 *
126 * The meanings of the flags of the error register for all commands are
127 * described in the ATA spec and could all be supported here in theory.
128 * Currently, only a few commands are supported (those that have been seen
129 * to produce errors). If many more are to be added then this function
130 * should probably be redesigned.
131 */
132 char *construct_st_er_desc(struct ata_smart_errorlog_struct *data) {
133 unsigned char CR=data->commands[4].commandreg;
134 unsigned char FR=data->commands[4].featuresreg;
135 unsigned char ST=data->error_struct.status;
136 unsigned char ER=data->error_struct.error_register;
137 char *s;
138 const char *error_flag[8];
139 int i, print_lba=0, print_sector=0;
140
141 // Set of character strings corresponding to different error codes.
142 // Please keep in alphabetic order if you add more.
143 const char *abrt = "ABRT"; // ABORTED
144 const char *amnf = "AMNF"; // ADDRESS MARK NOT FOUND
145 const char *ccto = "CCTO"; // COMMAND COMPLETION TIMED OUT
146 const char *eom = "EOM"; // END OF MEDIA
147 const char *icrc = "ICRC"; // INTERFACE CRC ERROR
148 const char *idnf = "IDNF"; // ID NOT FOUND
149 const char *ili = "ILI"; // MEANING OF THIS BIT IS COMMAND-SET SPECIFIC
150 const char *mc = "MC"; // MEDIA CHANGED
151 const char *mcr = "MCR"; // MEDIA CHANGE REQUEST
152 const char *nm = "NM"; // NO MEDIA
153 const char *obs = "obs"; // OBSOLETE
154 const char *tk0nf = "TK0NF"; // TRACK 0 NOT FOUND
155 const char *unc = "UNC"; // UNCORRECTABLE
156 const char *wp = "WP"; // WRITE PROTECTED
157
158 /* If for any command the Device Fault flag of the status register is
159 * not used then used_device_fault should be set to 0 (in the CR switch
160 * below)
161 */
162 int uses_device_fault = 1;
163
164 /* A value of NULL means that the error flag isn't used */
165 for (i = 0; i < 8; i++)
166 error_flag[i] = NULL;
167
168 switch (CR) {
169 case 0x10: // RECALIBRATE
170 error_flag[2] = abrt;
171 error_flag[1] = tk0nf;
172 break;
173 case 0x20: /* READ SECTOR(S) */
174 case 0x21: // READ SECTOR(S)
175 case 0x24: // READ SECTOR(S) EXT
176 case 0xC4: /* READ MULTIPLE */
177 case 0x29: // READ MULTIPLE EXT
178 error_flag[6] = unc;
179 error_flag[5] = mc;
180 error_flag[4] = idnf;
181 error_flag[3] = mcr;
182 error_flag[2] = abrt;
183 error_flag[1] = nm;
184 error_flag[0] = amnf;
185 print_lba=1;
186 break;
187 case 0x22: // READ LONG (with retries)
188 case 0x23: // READ LONG (without retries)
189 error_flag[4] = idnf;
190 error_flag[2] = abrt;
191 error_flag[0] = amnf;
192 print_lba=1;
193 break;
194 case 0x2a: // READ STREAM DMA
195 case 0x2b: // READ STREAM PIO
196 if (CR==0x2a)
197 error_flag[7] = icrc;
198 error_flag[6] = unc;
199 error_flag[5] = mc;
200 error_flag[4] = idnf;
201 error_flag[3] = mcr;
202 error_flag[2] = abrt;
203 error_flag[1] = nm;
204 error_flag[0] = ccto;
205 print_lba=1;
206 print_sector=(int)data->error_struct.sector_count;
207 break;
208 case 0x3A: // WRITE STREAM DMA
209 case 0x3B: // WRITE STREAM PIO
210 if (CR==0x3A)
211 error_flag[7] = icrc;
212 error_flag[6] = wp;
213 error_flag[5] = mc;
214 error_flag[4] = idnf;
215 error_flag[3] = mcr;
216 error_flag[2] = abrt;
217 error_flag[1] = nm;
218 error_flag[0] = ccto;
219 print_lba=1;
220 print_sector=(int)data->error_struct.sector_count;
221 break;
222 case 0x25: /* READ DMA EXT */
223 case 0x26: // READ DMA QUEUED EXT
224 case 0xC7: // READ DMA QUEUED
225 case 0xC8: /* READ DMA */
226 case 0xC9:
227 error_flag[7] = icrc;
228 error_flag[6] = unc;
229 error_flag[5] = mc;
230 error_flag[4] = idnf;
231 error_flag[3] = mcr;
232 error_flag[2] = abrt;
233 error_flag[1] = nm;
234 error_flag[0] = amnf;
235 print_lba=1;
236 if (CR==0x25 || CR==0xC8)
237 print_sector=(int)data->error_struct.sector_count;
238 break;
239 case 0x30: /* WRITE SECTOR(S) */
240 case 0x31: // WRITE SECTOR(S)
241 case 0x34: // WRITE SECTOR(S) EXT
242 case 0xC5: /* WRITE MULTIPLE */
243 case 0x39: // WRITE MULTIPLE EXT
244 case 0xCE: // WRITE MULTIPLE FUA EXT
245 error_flag[6] = wp;
246 error_flag[5] = mc;
247 error_flag[4] = idnf;
248 error_flag[3] = mcr;
249 error_flag[2] = abrt;
250 error_flag[1] = nm;
251 print_lba=1;
252 break;
253 case 0x32: // WRITE LONG (with retries)
254 case 0x33: // WRITE LONG (without retries)
255 error_flag[4] = idnf;
256 error_flag[2] = abrt;
257 print_lba=1;
258 break;
259 case 0x3C: // WRITE VERIFY
260 error_flag[6] = unc;
261 error_flag[4] = idnf;
262 error_flag[2] = abrt;
263 error_flag[0] = amnf;
264 print_lba=1;
265 break;
266 case 0x40: // READ VERIFY SECTOR(S) with retries
267 case 0x41: // READ VERIFY SECTOR(S) without retries
268 case 0x42: // READ VERIFY SECTOR(S) EXT
269 error_flag[6] = unc;
270 error_flag[5] = mc;
271 error_flag[4] = idnf;
272 error_flag[3] = mcr;
273 error_flag[2] = abrt;
274 error_flag[1] = nm;
275 error_flag[0] = amnf;
276 print_lba=1;
277 break;
278 case 0xA0: /* PACKET */
279 /* Bits 4-7 are all used for sense key (a 'command packet set specific error
280 * indication' according to the ATA/ATAPI-7 standard), so "Sense key" will
281 * be repeated in the error description string if more than one of those
282 * bits is set.
283 */
284 error_flag[7] = "Sense key (bit 3)",
285 error_flag[6] = "Sense key (bit 2)",
286 error_flag[5] = "Sense key (bit 1)",
287 error_flag[4] = "Sense key (bit 0)",
288 error_flag[2] = abrt;
289 error_flag[1] = eom;
290 error_flag[0] = ili;
291 break;
292 case 0xA1: /* IDENTIFY PACKET DEVICE */
293 case 0xEF: /* SET FEATURES */
294 case 0x00: /* NOP */
295 case 0xC6: /* SET MULTIPLE MODE */
296 error_flag[2] = abrt;
297 break;
298 case 0x2F: // READ LOG EXT
299 error_flag[6] = unc;
300 error_flag[4] = idnf;
301 error_flag[2] = abrt;
302 error_flag[0] = obs;
303 break;
304 case 0x3F: // WRITE LOG EXT
305 error_flag[4] = idnf;
306 error_flag[2] = abrt;
307 error_flag[0] = obs;
308 break;
309 case 0xB0: /* SMART */
310 switch(FR) {
311 case 0xD0: // SMART READ DATA
312 case 0xD1: // SMART READ ATTRIBUTE THRESHOLDS
313 case 0xD5: /* SMART READ LOG */
314 error_flag[6] = unc;
315 error_flag[4] = idnf;
316 error_flag[2] = abrt;
317 error_flag[0] = obs;
318 break;
319 case 0xD6: /* SMART WRITE LOG */
320 error_flag[4] = idnf;
321 error_flag[2] = abrt;
322 error_flag[0] = obs;
323 break;
324 case 0xD2: // Enable/Disable Attribute Autosave
325 case 0xD3: // SMART SAVE ATTRIBUTE VALUES (ATA-3)
326 case 0xD8: // SMART ENABLE OPERATIONS
327 case 0xD9: /* SMART DISABLE OPERATIONS */
328 case 0xDA: /* SMART RETURN STATUS */
329 case 0xDB: // Enable/Disable Auto Offline (SFF)
330 error_flag[2] = abrt;
331 break;
332 case 0xD4: // SMART EXECUTE IMMEDIATE OFFLINE
333 error_flag[4] = idnf;
334 error_flag[2] = abrt;
335 break;
336 default:
337 return NULL;
338 break;
339 }
340 break;
341 case 0xB1: /* DEVICE CONFIGURATION */
342 switch (FR) {
343 case 0xC0: /* DEVICE CONFIGURATION RESTORE */
344 error_flag[2] = abrt;
345 break;
346 default:
347 return NULL;
348 break;
349 }
350 break;
351 case 0xCA: /* WRITE DMA */
352 case 0xCB:
353 case 0x35: // WRITE DMA EXT
354 case 0x3D: // WRITE DMA FUA EXT
355 case 0xCC: // WRITE DMA QUEUED
356 case 0x36: // WRITE DMA QUEUED EXT
357 case 0x3E: // WRITE DMA QUEUED FUA EXT
358 error_flag[7] = icrc;
359 error_flag[6] = wp;
360 error_flag[5] = mc;
361 error_flag[4] = idnf;
362 error_flag[3] = mcr;
363 error_flag[2] = abrt;
364 error_flag[1] = nm;
365 error_flag[0] = amnf;
366 print_lba=1;
367 if (CR==0x35)
368 print_sector=(int)data->error_struct.sector_count;
369 break;
370 case 0xE4: // READ BUFFER
371 case 0xE8: // WRITE BUFFER
372 error_flag[2] = abrt;
373 break;
374 default:
375 return NULL;
376 }
377
378 /* 256 bytes -- that'll be plenty (OK, this is lazy!) */
379 if (!(s = (char *)malloc(256)))
380 return s;
381
382 s[0] = '\0';
383
384 /* We ignore any status flags other than Device Fault and Error */
385
386 if (uses_device_fault && (ST & (1 << 5))) {
387 strcat(s, "Device Fault");
388 if (ST & 1) // Error flag
389 strcat(s, "; ");
390 }
391 if (ST & 1) { // Error flag
392 int count = 0;
393
394 strcat(s, "Error: ");
395 for (i = 7; i >= 0; i--)
396 if ((ER & (1 << i)) && (error_flag[i])) {
397 if (count++ > 0)
398 strcat(s, ", ");
399 strcat(s, error_flag[i]);
400 }
401 }
402
403 // If the error was a READ or WRITE error, print the Logical Block
404 // Address (LBA) at which the read or write failed.
405 if (print_lba) {
406 char tmp[128];
407 int lba;
408
409 // bits 24-27: bits 0-3 of DH
410 lba = 0xf & data->error_struct.drive_head;
411 lba <<= 8;
412 // bits 16-23: CH
413 lba |= data->error_struct.cylinder_high;
414 lba <<= 8;
415 // bits 8-15: CL
416 lba |= data->error_struct.cylinder_low;
417 lba <<= 8;
418 // bits 0-7: SN
419 lba |= data->error_struct.sector_number;
420
421 // print number of sectors, if known, and append to print string
422 if (print_sector) {
423 snprintf(tmp, 128, " %d sectors", print_sector);
424 strcat(s, tmp);
425 }
426
427 // print LBA, and append to print string
428 snprintf(tmp, 128, " at LBA = 0x%08x = %d", lba, lba);
429 strcat(s, tmp);
430 }
431
432 return s;
433 }
434
435
436 // Get number of sectors from IDENTIFY sector. If the drive doesn't
437 // support LBA addressing or has no user writable sectors
438 // (eg, CDROM or DVD) then routine returns zero.
439 static uint64_t get_num_sectors(const ata_identify_device *drive)
440 {
441 unsigned short command_set_2 = drive->command_set_2;
442 unsigned short capabilities_0 = drive->words047_079[49-47];
443 unsigned short sects_16 = drive->words047_079[60-47];
444 unsigned short sects_32 = drive->words047_079[61-47];
445 unsigned short lba_16 = drive->words088_255[100-88];
446 unsigned short lba_32 = drive->words088_255[101-88];
447 unsigned short lba_48 = drive->words088_255[102-88];
448 unsigned short lba_64 = drive->words088_255[103-88];
449
450 // LBA support?
451 if (!(capabilities_0 & 0x0200))
452 return 0; // No
453
454 // if drive supports LBA addressing, determine 32-bit LBA capacity
455 uint64_t lba32 = (unsigned int)sects_32 << 16 |
456 (unsigned int)sects_16 << 0 ;
457
458 uint64_t lba64 = 0;
459 // if drive supports 48-bit addressing, determine THAT capacity
460 if ((command_set_2 & 0xc000) == 0x4000 && (command_set_2 & 0x0400))
461 lba64 = (uint64_t)lba_64 << 48 |
462 (uint64_t)lba_48 << 32 |
463 (uint64_t)lba_32 << 16 |
464 (uint64_t)lba_16 << 0 ;
465
466 // return the larger of the two possible capacities
467 return (lba32 > lba64 ? lba32 : lba64);
468 }
469
470
471 // This returns the capacity of a disk drive and also prints this into
472 // a string, using comma separators to make it easier to read. If the
473 // drive doesn't support LBA addressing or has no user writable
474 // sectors (eg, CDROM or DVD) then routine returns zero.
475 uint64_t determine_capacity(struct ata_identify_device *drive, char *pstring){
476
477 // get correct character to use as thousands separator
478 char *separator=",";
479 #ifdef HAVE_LOCALE_H
480 struct lconv *currentlocale=NULL;
481 setlocale (LC_ALL, "");
482 currentlocale=localeconv();
483 if (*(currentlocale->thousands_sep))
484 separator=(char *)currentlocale->thousands_sep;
485 #endif // #ifdef HAVE_LOCALE_H
486
487 // get #sectors and turn into bytes
488 uint64_t capacity = get_num_sectors(drive) * 512;
489 uint64_t retval = capacity;
490
491 // print with locale-specific separators (default is comma)
492 int started=0, k=1000000000;
493 uint64_t power_of_ten = k;
494 power_of_ten *= k;
495
496 for (k=0; k<7; k++) {
497 uint64_t threedigits = capacity/power_of_ten;
498 capacity -= threedigits*power_of_ten;
499 if (started)
500 // we have already printed some digits
501 pstring += sprintf(pstring, "%s%03"PRIu64, separator, threedigits);
502 else if (threedigits || k==6) {
503 // these are the first digits that we are printing
504 pstring += sprintf(pstring, "%"PRIu64, threedigits);
505 started = 1;
506 }
507 if (k!=6)
508 power_of_ten /= 1000;
509 }
510
511 return retval;
512 }
513
514 int ataPrintDriveInfo (struct ata_identify_device *drive){
515 int version, drivetype;
516 const char *description;
517 char unknown[64], timedatetz[DATEANDEPOCHLEN];
518 unsigned short minorrev;
519 char model[64], serial[64], firm[64], capacity[64];
520
521 // format drive information (with byte swapping as needed)
522 format_ata_string(model, (char *)drive->model,40);
523 format_ata_string(serial, (char *)drive->serial_no,20);
524 format_ata_string(firm, (char *)drive->fw_rev,8);
525
526 // print out model, serial # and firmware versions (byte-swap ASCI strings)
527 drivetype=lookupdrive(model, firm);
528
529 // Print model family if known
530 if (drivetype>=0 && knowndrives[drivetype].modelfamily)
531 pout("Model Family: %s\n", knowndrives[drivetype].modelfamily);
532
533 pout("Device Model: %s\n", infofound(model));
534 if (!con->dont_print_serial)
535 pout("Serial Number: %s\n", infofound(serial));
536 pout("Firmware Version: %s\n", infofound(firm));
537
538 if (determine_capacity(drive, capacity))
539 pout("User Capacity: %s bytes\n", capacity);
540
541 // See if drive is recognized
542 pout("Device is: %s\n", drivetype<0?
543 "Not in smartctl database [for details use: -P showall]":
544 "In smartctl database [for details use: -P show]");
545
546 // now get ATA version info
547 version=ataVersionInfo(&description,drive, &minorrev);
548
549 // unrecognized minor revision code
550 if (!description){
551 if (!minorrev)
552 sprintf(unknown, "Exact ATA specification draft version not indicated");
553 else
554 sprintf(unknown,"Not recognized. Minor revision code: 0x%02hx", minorrev);
555 description=unknown;
556 }
557
558
559 // SMART Support was first added into the ATA/ATAPI-3 Standard with
560 // Revision 3 of the document, July 25, 1995. Look at the "Document
561 // Status" revision commands at the beginning of
562 // http://www.t13.org/project/d2008r6.pdf to see this. So it's not
563 // enough to check if we are ATA-3. Version=-3 indicates ATA-3
564 // BEFORE Revision 3.
565 pout("ATA Version is: %d\n",(int)abs(version));
566 pout("ATA Standard is: %s\n",description);
567
568 // print current time and date and timezone
569 dateandtimezone(timedatetz);
570 pout("Local Time is: %s\n", timedatetz);
571
572 // Print warning message, if there is one
573 if (drivetype>=0 && knowndrives[drivetype].warningmsg)
574 pout("\n==> WARNING: %s\n\n", knowndrives[drivetype].warningmsg);
575
576 if (version>=3)
577 return drivetype;
578
579 pout("SMART is only available in ATA Version 3 Revision 3 or greater.\n");
580 pout("We will try to proceed in spite of this.\n");
581 return drivetype;
582 }
583
584
585 const char *OfflineDataCollectionStatus(unsigned char status_byte){
586 unsigned char stat=status_byte & 0x7f;
587
588 switch(stat){
589 case 0x00:
590 return "was never started";
591 case 0x02:
592 return "was completed without error";
593 case 0x03:
594 if (status_byte == 0x03)
595 return "is in progress";
596 else
597 return "is in a Reserved state";
598 case 0x04:
599 return "was suspended by an interrupting command from host";
600 case 0x05:
601 return "was aborted by an interrupting command from host";
602 case 0x06:
603 return "was aborted by the device with a fatal error";
604 default:
605 if (stat >= 0x40)
606 return "is in a Vendor Specific state\n";
607 else
608 return "is in a Reserved state\n";
609 }
610 }
611
612
613 /* prints verbose value Off-line data collection status byte */
614 void PrintSmartOfflineStatus(struct ata_smart_values *data){
615
616 pout("Offline data collection status: (0x%02x)\t",
617 (int)data->offline_data_collection_status);
618
619 // Off-line data collection status byte is not a reserved
620 // or vendor specific value
621 pout("Offline data collection activity\n"
622 "\t\t\t\t\t%s.\n", OfflineDataCollectionStatus(data->offline_data_collection_status));
623
624 // Report on Automatic Data Collection Status. Only IBM documents
625 // this bit. See SFF 8035i Revision 2 for details.
626 if (data->offline_data_collection_status & 0x80)
627 pout("\t\t\t\t\tAuto Offline Data Collection: Enabled.\n");
628 else
629 pout("\t\t\t\t\tAuto Offline Data Collection: Disabled.\n");
630
631 return;
632 }
633
634 void PrintSmartSelfExecStatus(struct ata_smart_values *data)
635 {
636 pout("Self-test execution status: ");
637
638 switch (data->self_test_exec_status >> 4)
639 {
640 case 0:
641 pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
642 (int)data->self_test_exec_status);
643 pout("without error or no self-test has ever \n\t\t\t\t\tbeen run.\n");
644 break;
645 case 1:
646 pout("(%4d)\tThe self-test routine was aborted by\n\t\t\t\t\t",
647 (int)data->self_test_exec_status);
648 pout("the host.\n");
649 break;
650 case 2:
651 pout("(%4d)\tThe self-test routine was interrupted\n\t\t\t\t\t",
652 (int)data->self_test_exec_status);
653 pout("by the host with a hard or soft reset.\n");
654 break;
655 case 3:
656 pout("(%4d)\tA fatal error or unknown test error\n\t\t\t\t\t",
657 (int)data->self_test_exec_status);
658 pout("occurred while the device was executing\n\t\t\t\t\t");
659 pout("its self-test routine and the device \n\t\t\t\t\t");
660 pout("was unable to complete the self-test \n\t\t\t\t\t");
661 pout("routine.\n");
662 break;
663 case 4:
664 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
665 (int)data->self_test_exec_status);
666 pout("a test element that failed and the test\n\t\t\t\t\t");
667 pout("element that failed is not known.\n");
668 break;
669 case 5:
670 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
671 (int)data->self_test_exec_status);
672 pout("the electrical element of the test\n\t\t\t\t\t");
673 pout("failed.\n");
674 break;
675 case 6:
676 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
677 (int)data->self_test_exec_status);
678 pout("the servo (and/or seek) element of the \n\t\t\t\t\t");
679 pout("test failed.\n");
680 break;
681 case 7:
682 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
683 (int)data->self_test_exec_status);
684 pout("the read element of the test failed.\n");
685 break;
686 case 8:
687 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
688 (int)data->self_test_exec_status);
689 pout("a test element that failed and the\n\t\t\t\t\t");
690 pout("device is suspected of having handling\n\t\t\t\t\t");
691 pout("damage.\n");
692 break;
693 case 15:
694 if (con->fixfirmwarebug == FIX_SAMSUNG3 && data->self_test_exec_status == 0xf0) {
695 pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
696 (int)data->self_test_exec_status);
697 pout("with unknown result or self-test in\n\t\t\t\t\t");
698 pout("progress with less than 10%% remaining.\n");
699 }
700 else {
701 pout("(%4d)\tSelf-test routine in progress...\n\t\t\t\t\t",
702 (int)data->self_test_exec_status);
703 pout("%1d0%% of test remaining.\n",
704 (int)(data->self_test_exec_status & 0x0f));
705 }
706 break;
707 default:
708 pout("(%4d)\tReserved.\n",
709 (int)data->self_test_exec_status);
710 break;
711 }
712
713 }
714
715
716
717 void PrintSmartTotalTimeCompleteOffline ( struct ata_smart_values *data){
718 pout("Total time to complete Offline \n");
719 pout("data collection: \t\t (%4d) seconds.\n",
720 (int)data->total_time_to_complete_off_line);
721 }
722
723
724
725 void PrintSmartOfflineCollectCap(struct ata_smart_values *data){
726 pout("Offline data collection\n");
727 pout("capabilities: \t\t\t (0x%02x) ",
728 (int)data->offline_data_collection_capability);
729
730 if (data->offline_data_collection_capability == 0x00){
731 pout("\tOffline data collection not supported.\n");
732 }
733 else {
734 pout( "%s\n", isSupportExecuteOfflineImmediate(data)?
735 "SMART execute Offline immediate." :
736 "No SMART execute Offline immediate.");
737
738 pout( "\t\t\t\t\t%s\n", isSupportAutomaticTimer(data)?
739 "Auto Offline data collection on/off support.":
740 "No Auto Offline data collection support.");
741
742 pout( "\t\t\t\t\t%s\n", isSupportOfflineAbort(data)?
743 "Abort Offline collection upon new\n\t\t\t\t\tcommand.":
744 "Suspend Offline collection upon new\n\t\t\t\t\tcommand.");
745
746 pout( "\t\t\t\t\t%s\n", isSupportOfflineSurfaceScan(data)?
747 "Offline surface scan supported.":
748 "No Offline surface scan supported.");
749
750 pout( "\t\t\t\t\t%s\n", isSupportSelfTest(data)?
751 "Self-test supported.":
752 "No Self-test supported.");
753
754 pout( "\t\t\t\t\t%s\n", isSupportConveyanceSelfTest(data)?
755 "Conveyance Self-test supported.":
756 "No Conveyance Self-test supported.");
757
758 pout( "\t\t\t\t\t%s\n", isSupportSelectiveSelfTest(data)?
759 "Selective Self-test supported.":
760 "No Selective Self-test supported.");
761 }
762 }
763
764
765
766 void PrintSmartCapability ( struct ata_smart_values *data)
767 {
768 pout("SMART capabilities: ");
769 pout("(0x%04x)\t", (int)data->smart_capability);
770
771 if (data->smart_capability == 0x00)
772 {
773 pout("Automatic saving of SMART data\t\t\t\t\tis not implemented.\n");
774 }
775 else
776 {
777
778 pout( "%s\n", (data->smart_capability & 0x01)?
779 "Saves SMART data before entering\n\t\t\t\t\tpower-saving mode.":
780 "Does not save SMART data before\n\t\t\t\t\tentering power-saving mode.");
781
782 if ( data->smart_capability & 0x02 )
783 {
784 pout("\t\t\t\t\tSupports SMART auto save timer.\n");
785 }
786 }
787 }
788
789 void PrintSmartErrorLogCapability (struct ata_smart_values *data, struct ata_identify_device *identity)
790 {
791
792 pout("Error logging capability: ");
793
794 if ( isSmartErrorLogCapable(data, identity) )
795 {
796 pout(" (0x%02x)\tError logging supported.\n",
797 (int)data->errorlog_capability);
798 }
799 else {
800 pout(" (0x%02x)\tError logging NOT supported.\n",
801 (int)data->errorlog_capability);
802 }
803 }
804
805 void PrintSmartShortSelfTestPollingTime(struct ata_smart_values *data){
806 pout("Short self-test routine \n");
807 if (isSupportSelfTest(data))
808 pout("recommended polling time: \t (%4d) minutes.\n",
809 (int)data->short_test_completion_time);
810 else
811 pout("recommended polling time: \t Not Supported.\n");
812 }
813
814 void PrintSmartExtendedSelfTestPollingTime(struct ata_smart_values *data){
815 pout("Extended self-test routine\n");
816 if (isSupportSelfTest(data))
817 pout("recommended polling time: \t (%4d) minutes.\n",
818 (int)data->extend_test_completion_time);
819 else
820 pout("recommended polling time: \t Not Supported.\n");
821 }
822
823 void PrintSmartConveyanceSelfTestPollingTime(struct ata_smart_values *data){
824 pout("Conveyance self-test routine\n");
825 if (isSupportConveyanceSelfTest(data))
826 pout("recommended polling time: \t (%4d) minutes.\n",
827 (int)data->conveyance_test_completion_time);
828 else
829 pout("recommended polling time: \t Not Supported.\n");
830 }
831
832 // onlyfailed=0 : print all attribute values
833 // onlyfailed=1: just ones that are currently failed and have prefailure bit set
834 // onlyfailed=2: ones that are failed, or have failed with or without prefailure bit set
835 void PrintSmartAttribWithThres (struct ata_smart_values *data,
836 struct ata_smart_thresholds_pvt *thresholds,
837 int onlyfailed){
838 int i;
839 int needheader=1;
840 char rawstring[64];
841
842 // step through all vendor attributes
843 for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++){
844 char *status;
845 struct ata_smart_attribute *disk=data->vendor_attributes+i;
846 struct ata_smart_threshold_entry *thre=thresholds->thres_entries+i;
847
848 // consider only valid attributes (allowing some screw-ups in the
849 // thresholds page data to slip by)
850 if (disk->id){
851 const char *type, *update;
852 int failednow,failedever;
853 char attributename[64];
854
855 failednow = (disk->current <= thre->threshold);
856 failedever= (disk->worst <= thre->threshold);
857
858 // These break out of the loop if we are only printing certain entries...
859 if (onlyfailed==1 && (!ATTRIBUTE_FLAGS_PREFAILURE(disk->flags) || !failednow))
860 continue;
861
862 if (onlyfailed==2 && !failedever)
863 continue;
864
865 // print header only if needed
866 if (needheader){
867 if (!onlyfailed){
868 pout("SMART Attributes Data Structure revision number: %d\n",(int)data->revnumber);
869 pout("Vendor Specific SMART Attributes with Thresholds:\n");
870 }
871 pout("ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE\n");
872 needheader=0;
873 }
874
875 // is this Attribute currently failed, or has it ever failed?
876 if (failednow)
877 status="FAILING_NOW";
878 else if (failedever)
879 status="In_the_past";
880 else
881 status=" -";
882
883 // Print name of attribute
884 ataPrintSmartAttribName(attributename,disk->id, con->attributedefs);
885 pout("%-28s",attributename);
886
887 // printing line for each valid attribute
888 type=ATTRIBUTE_FLAGS_PREFAILURE(disk->flags)?"Pre-fail":"Old_age";
889 update=ATTRIBUTE_FLAGS_ONLINE(disk->flags)?"Always":"Offline";
890
891 pout("0x%04x %.3d %.3d %.3d %-10s%-9s%-12s",
892 (int)disk->flags, (int)disk->current, (int)disk->worst,
893 (int)thre->threshold, type, update, status);
894
895 // print raw value of attribute
896 ataPrintSmartAttribRawValue(rawstring, disk, con->attributedefs);
897 pout("%s\n", rawstring);
898
899 // print a warning if there is inconsistency here!
900 if (disk->id != thre->id){
901 char atdat[64],atthr[64];
902 ataPrintSmartAttribName(atdat, disk->id, con->attributedefs);
903 ataPrintSmartAttribName(atthr, thre->id, con->attributedefs);
904 pout("%-28s<== Data Page | WARNING: PREVIOUS ATTRIBUTE HAS TWO\n",atdat);
905 pout("%-28s<== Threshold Page | INCONSISTENT IDENTITIES IN THE DATA\n",atthr);
906 }
907 }
908 }
909 if (!needheader) pout("\n");
910 }
911
912 // Print SMART related SCT capabilities
913 static void ataPrintSCTCapability(const ata_identify_device *drive)
914 {
915 unsigned short sctcaps = drive->words088_255[206-88];
916 if (!(sctcaps & 0x01))
917 return;
918 pout("SCT capabilities: \t (0x%04x)\tSCT Status supported.\n", sctcaps);
919 if (sctcaps & 0x10)
920 pout("\t\t\t\t\tSCT Feature Control supported.\n");
921 if (sctcaps & 0x20)
922 pout("\t\t\t\t\tSCT Data Table supported.\n");
923 }
924
925
926 void ataPrintGeneralSmartValues(struct ata_smart_values *data, struct ata_identify_device *drive){
927 pout("General SMART Values:\n");
928
929 PrintSmartOfflineStatus(data);
930
931 if (isSupportSelfTest(data)){
932 PrintSmartSelfExecStatus (data);
933 }
934
935 PrintSmartTotalTimeCompleteOffline(data);
936 PrintSmartOfflineCollectCap(data);
937 PrintSmartCapability(data);
938
939 PrintSmartErrorLogCapability(data, drive);
940
941 pout( "\t\t\t\t\t%s\n", isGeneralPurposeLoggingCapable(drive)?
942 "General Purpose Logging supported.":
943 "No General Purpose Logging support.");
944
945 if (isSupportSelfTest(data)){
946 PrintSmartShortSelfTestPollingTime (data);
947 PrintSmartExtendedSelfTestPollingTime (data);
948 }
949 if (isSupportConveyanceSelfTest(data))
950 PrintSmartConveyanceSelfTestPollingTime (data);
951
952 ataPrintSCTCapability(drive);
953
954 pout("\n");
955 }
956
957 int ataPrintLogDirectory(struct ata_smart_log_directory *data){
958 int i;
959 char *name;
960
961 pout("SMART Log Directory Logging Version %d%s\n",
962 data->logversion, data->logversion==1?" [multi-sector log support]":"");
963 for (i=0; i<=255; i++){
964 int numsect;
965
966 // Directory log length
967 numsect = i? data->entry[i-1].numsectors : 1;
968
969 // If the log is not empty, what is it's name
970 if (numsect){
971 switch (i) {
972 case 0:
973 name="Log Directory"; break;
974 case 1:
975 name="Summary SMART error log"; break;
976 case 2:
977 name="Comprehensive SMART error log"; break;
978 case 3:
979 name="Extended Comprehensive SMART error log"; break;
980 case 6:
981 name="SMART self-test log"; break;
982 case 7:
983 name="Extended self-test log"; break;
984 case 9:
985 name="Selective self-test log"; break;
986 case 0x20:
987 name="Streaming performance log"; break;
988 case 0x21:
989 name="Write stream error log"; break;
990 case 0x22:
991 name="Read stream error log"; break;
992 case 0x23:
993 name="Delayed sector log"; break;
994 default:
995 if (0xa0<=i && i<=0xbf)
996 name="Device vendor specific log";
997 else if (0x80<=i && i<=0x9f)
998 name="Host vendor specific log";
999 else
1000 name="Reserved log";
1001 break;
1002 }
1003
1004 // print name and length of log
1005 pout("Log at address 0x%02x has %03d sectors [%s]\n",
1006 i, numsect, name);
1007 }
1008 }
1009 return 0;
1010 }
1011
1012 // returns number of errors
1013 int ataPrintSmartErrorlog(struct ata_smart_errorlog *data){
1014 int k;
1015
1016 pout("SMART Error Log Version: %d\n", (int)data->revnumber);
1017
1018 // if no errors logged, return
1019 if (!data->error_log_pointer){
1020 pout("No Errors Logged\n\n");
1021 return 0;
1022 }
1023 PRINT_ON(con);
1024 // If log pointer out of range, return
1025 if (data->error_log_pointer>5){
1026 pout("Invalid Error Log index = 0x%02x (T13/1321D rev 1c "
1027 "Section 8.41.6.8.2.2 gives valid range from 1 to 5)\n\n",
1028 (int)data->error_log_pointer);
1029 return 0;
1030 }
1031
1032 // Some internal consistency checking of the data structures
1033 if ((data->ata_error_count-data->error_log_pointer)%5 && con->fixfirmwarebug != FIX_SAMSUNG2) {
1034 pout("Warning: ATA error count %d inconsistent with error log pointer %d\n\n",
1035 data->ata_error_count,data->error_log_pointer);
1036 }
1037
1038 // starting printing error log info
1039 if (data->ata_error_count<=5)
1040 pout( "ATA Error Count: %d\n", (int)data->ata_error_count);
1041 else
1042 pout( "ATA Error Count: %d (device log contains only the most recent five errors)\n",
1043 (int)data->ata_error_count);
1044 PRINT_OFF(con);
1045 pout("\tCR = Command Register [HEX]\n"
1046 "\tFR = Features Register [HEX]\n"
1047 "\tSC = Sector Count Register [HEX]\n"
1048 "\tSN = Sector Number Register [HEX]\n"
1049 "\tCL = Cylinder Low Register [HEX]\n"
1050 "\tCH = Cylinder High Register [HEX]\n"
1051 "\tDH = Device/Head Register [HEX]\n"
1052 "\tDC = Device Command Register [HEX]\n"
1053 "\tER = Error register [HEX]\n"
1054 "\tST = Status register [HEX]\n"
1055 "Powered_Up_Time is measured from power on, and printed as\n"
1056 "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
1057 "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
1058
1059 // now step through the five error log data structures (table 39 of spec)
1060 for (k = 4; k >= 0; k-- ) {
1061 char *st_er_desc;
1062
1063 // The error log data structure entries are a circular buffer
1064 int j, i=(data->error_log_pointer+k)%5;
1065 struct ata_smart_errorlog_struct *elog=data->errorlog_struct+i;
1066 struct ata_smart_errorlog_error_struct *summary=&(elog->error_struct);
1067
1068 // Spec says: unused error log structures shall be zero filled
1069 if (nonempty((unsigned char*)elog,sizeof(*elog))){
1070 // Table 57 of T13/1532D Volume 1 Revision 3
1071 char *msgstate;
1072 int bits=summary->state & 0x0f;
1073 int days = (int)summary->timestamp/24;
1074
1075 switch (bits){
1076 case 0x00: msgstate="in an unknown state";break;
1077 case 0x01: msgstate="sleeping"; break;
1078 case 0x02: msgstate="in standby mode"; break;
1079 case 0x03: msgstate="active or idle"; break;
1080 case 0x04: msgstate="doing SMART Offline or Self-test"; break;
1081 default:
1082 if (bits<0x0b)
1083 msgstate="in a reserved state";
1084 else
1085 msgstate="in a vendor specific state";
1086 }
1087
1088 // See table 42 of ATA5 spec
1089 PRINT_ON(con);
1090 pout("Error %d occurred at disk power-on lifetime: %d hours (%d days + %d hours)\n",
1091 (int)(data->ata_error_count+k-4), (int)summary->timestamp, days, (int)(summary->timestamp-24*days));
1092 PRINT_OFF(con);
1093 pout(" When the command that caused the error occurred, the device was %s.\n\n",msgstate);
1094 pout(" After command completion occurred, registers were:\n"
1095 " ER ST SC SN CL CH DH\n"
1096 " -- -- -- -- -- -- --\n"
1097 " %02x %02x %02x %02x %02x %02x %02x",
1098 (int)summary->error_register,
1099 (int)summary->status,
1100 (int)summary->sector_count,
1101 (int)summary->sector_number,
1102 (int)summary->cylinder_low,
1103 (int)summary->cylinder_high,
1104 (int)summary->drive_head);
1105 // Add a description of the contents of the status and error registers
1106 // if possible
1107 st_er_desc = construct_st_er_desc(elog);
1108 if (st_er_desc) {
1109 pout(" %s", st_er_desc);
1110 free(st_er_desc);
1111 }
1112 pout("\n\n");
1113 pout(" Commands leading to the command that caused the error were:\n"
1114 " CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name\n"
1115 " -- -- -- -- -- -- -- -- ---------------- --------------------\n");
1116 for ( j = 4; j >= 0; j--){
1117 struct ata_smart_errorlog_command_struct *thiscommand=elog->commands+j;
1118
1119 // Spec says: unused data command structures shall be zero filled
1120 if (nonempty((unsigned char*)thiscommand,sizeof(*thiscommand))) {
1121 char timestring[32];
1122
1123 // Convert integer milliseconds to a text-format string
1124 MsecToText(thiscommand->timestamp, timestring);
1125
1126 pout(" %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
1127 (int)thiscommand->commandreg,
1128 (int)thiscommand->featuresreg,
1129 (int)thiscommand->sector_count,
1130 (int)thiscommand->sector_number,
1131 (int)thiscommand->cylinder_low,
1132 (int)thiscommand->cylinder_high,
1133 (int)thiscommand->drive_head,
1134 (int)thiscommand->devicecontrolreg,
1135 timestring,
1136 look_up_ata_command(thiscommand->commandreg, thiscommand->featuresreg));
1137 }
1138 }
1139 pout("\n");
1140 }
1141 }
1142 PRINT_ON(con);
1143 if (con->printing_switchable)
1144 pout("\n");
1145 PRINT_OFF(con);
1146 return data->ata_error_count;
1147 }
1148
1149 void ataPrintSelectiveSelfTestLog(struct ata_selective_self_test_log *log, struct ata_smart_values *sv) {
1150 int i,field1,field2;
1151 char *msg;
1152 char tmp[64];
1153 uint64_t maxl=0,maxr=0;
1154 uint64_t current=log->currentlba;
1155 uint64_t currentend=current+65535;
1156
1157 // print data structure revision number
1158 pout("SMART Selective self-test log data structure revision number %d\n",(int)log->logversion);
1159 if (1 != log->logversion)
1160 pout("Warning: ATA Specification requires selective self-test log data structure revision number = 1\n");
1161
1162 switch((sv->self_test_exec_status)>>4){
1163 case 0:msg="Completed";
1164 break;
1165 case 1:msg="Aborted_by_host";
1166 break;
1167 case 2:msg="Interrupted";
1168 break;
1169 case 3:msg="Fatal_error";
1170 break;
1171 case 4:msg="Completed_unknown_failure";
1172 break;
1173 case 5:msg="Completed_electrical_failure";
1174 break;
1175 case 6:msg="Completed_servo/seek_failure";
1176 break;
1177 case 7:msg="Completed_read_failure";
1178 break;
1179 case 8:msg="Completed_handling_damage??";
1180 break;
1181 case 15:msg="Self_test_in_progress";
1182 break;
1183 default:msg="Unknown_status ";
1184 break;
1185 }
1186
1187 // find the number of columns needed for printing. If in use, the
1188 // start/end of span being read-scanned...
1189 if (log->currentspan>5) {
1190 maxl=current;
1191 maxr=currentend;
1192 }
1193 for (i=0; i<5; i++) {
1194 uint64_t start=log->span[i].start;
1195 uint64_t end =log->span[i].end;
1196 // ... plus max start/end of each of the five test spans.
1197 if (start>maxl)
1198 maxl=start;
1199 if (end > maxr)
1200 maxr=end;
1201 }
1202
1203 // we need at least 7 characters wide fields to accomodate the
1204 // labels
1205 if ((field1=snprintf(tmp,64, "%"PRIu64, maxl))<7)
1206 field1=7;
1207 if ((field2=snprintf(tmp,64, "%"PRIu64, maxr))<7)
1208 field2=7;
1209
1210 // now print the five test spans
1211 pout(" SPAN %*s %*s CURRENT_TEST_STATUS\n", field1, "MIN_LBA", field2, "MAX_LBA");
1212
1213 for (i=0; i<5; i++) {
1214 uint64_t start=log->span[i].start;
1215 uint64_t end=log->span[i].end;
1216
1217 if ((i+1)==(int)log->currentspan)
1218 // this span is currently under test
1219 pout(" %d %*"PRIu64" %*"PRIu64" %s [%01d0%% left] (%"PRIu64"-%"PRIu64")\n",
1220 i+1, field1, start, field2, end, msg,
1221 (int)(sv->self_test_exec_status & 0xf), current, currentend);
1222 else
1223 // this span is not currently under test
1224 pout(" %d %*"PRIu64" %*"PRIu64" Not_testing\n",
1225 i+1, field1, start, field2, end);
1226 }
1227
1228 // if we are currently read-scanning, print LBAs and the status of
1229 // the read scan
1230 if (log->currentspan>5)
1231 pout("%5d %*"PRIu64" %*"PRIu64" Read_scanning %s\n",
1232 (int)log->currentspan, field1, current, field2, currentend,
1233 OfflineDataCollectionStatus(sv->offline_data_collection_status));
1234
1235 /* Print selective self-test flags. Possible flag combinations are
1236 (numbering bits from 0-15):
1237 Bit-1 Bit-3 Bit-4
1238 Scan Pending Active
1239 0 * * Don't scan
1240 1 0 0 Will carry out scan after selective test
1241 1 1 0 Waiting to carry out scan after powerup
1242 1 0 1 Currently scanning
1243 1 1 1 Currently scanning
1244 */
1245
1246 pout("Selective self-test flags (0x%x):\n", (unsigned int)log->flags);
1247 if (log->flags & SELECTIVE_FLAG_DOSCAN) {
1248 if (log->flags & SELECTIVE_FLAG_ACTIVE)
1249 pout(" Currently read-scanning the remainder of the disk.\n");
1250 else if (log->flags & SELECTIVE_FLAG_PENDING)
1251 pout(" Read-scan of remainder of disk interrupted; will resume %d min after power-up.\n",
1252 (int)log->pendingtime);
1253 else
1254 pout(" After scanning selected spans, read-scan remainder of disk.\n");
1255 }
1256 else
1257 pout(" After scanning selected spans, do NOT read-scan remainder of disk.\n");
1258
1259 // print pending time
1260 pout("If Selective self-test is pending on power-up, resume after %d minute delay.\n",
1261 (int)log->pendingtime);
1262
1263 return;
1264 }
1265
1266 // return value is:
1267 // bottom 8 bits: number of entries found where self-test showed an error
1268 // remaining bits: if nonzero, power on hours of last self-test where error was found
1269 int ataPrintSmartSelfTestlog(struct ata_smart_selftestlog *data,int allentries){
1270 int i,j,noheaderprinted=1;
1271 int retval=0, hours=0, testno=0;
1272
1273 if (allentries)
1274 pout("SMART Self-test log structure revision number %d\n",(int)data->revnumber);
1275 if ((data->revnumber!=0x0001) && allentries && con->fixfirmwarebug != FIX_SAMSUNG)
1276 pout("Warning: ATA Specification requires self-test log structure revision number = 1\n");
1277 if (data->mostrecenttest==0){
1278 if (allentries)
1279 pout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n\n");
1280 return 0;
1281 }
1282
1283 // print log
1284 for (i=20;i>=0;i--){
1285 struct ata_smart_selftestlog_struct *log;
1286
1287 // log is a circular buffer
1288 j=(i+data->mostrecenttest)%21;
1289 log=data->selftest_struct+j;
1290
1291 if (nonempty((unsigned char*)log,sizeof(*log))){
1292 char *msgtest,*msgstat,percent[64],firstlba[64];
1293 int errorfound=0;
1294
1295 // count entry based on non-empty structures -- needed for
1296 // Seagate only -- other vendors don't have blank entries 'in
1297 // the middle'
1298 testno++;
1299
1300 // test name
1301 switch(log->selftestnumber){
1302 case 0: msgtest="Offline "; break;
1303 case 1: msgtest="Short offline "; break;
1304 case 2: msgtest="Extended offline "; break;
1305 case 3: msgtest="Conveyance offline "; break;
1306 case 4: msgtest="Selective offline "; break;
1307 case 127: msgtest="Abort offline test "; break;
1308 case 129: msgtest="Short captive "; break;
1309 case 130: msgtest="Extended captive "; break;
1310 case 131: msgtest="Conveyance captive "; break;
1311 case 132: msgtest="Selective captive "; break;
1312 default:
1313 if ( log->selftestnumber>=192 ||
1314 (log->selftestnumber>= 64 && log->selftestnumber<=126))
1315 msgtest="Vendor offline ";
1316 else
1317 msgtest="Reserved offline ";
1318 }
1319
1320 // test status
1321 switch((log->selfteststatus)>>4){
1322 case 0:msgstat="Completed without error "; break;
1323 case 1:msgstat="Aborted by host "; break;
1324 case 2:msgstat="Interrupted (host reset) "; break;
1325 case 3:msgstat="Fatal or unknown error "; errorfound=1; break;
1326 case 4:msgstat="Completed: unknown failure "; errorfound=1; break;
1327 case 5:msgstat="Completed: electrical failure"; errorfound=1; break;
1328 case 6:msgstat="Completed: servo/seek failure"; errorfound=1; break;
1329 case 7:msgstat="Completed: read failure "; errorfound=1; break;
1330 case 8:msgstat="Completed: handling damage?? "; errorfound=1; break;
1331 case 15:msgstat="Self-test routine in progress"; break;
1332 default:msgstat="Unknown/reserved test status ";
1333 }
1334
1335 retval+=errorfound;
1336 sprintf(percent,"%1d0%%",(log->selfteststatus)&0xf);
1337
1338 // T13/1321D revision 1c: (Data structure Rev #1)
1339
1340 //The failing LBA shall be the LBA of the uncorrectable sector
1341 //that caused the test to fail. If the device encountered more
1342 //than one uncorrectable sector during the test, this field
1343 //shall indicate the LBA of the first uncorrectable sector
1344 //encountered. If the test passed or the test failed for some
1345 //reason other than an uncorrectable sector, the value of this
1346 //field is undefined.
1347
1348 // This is true in ALL ATA-5 specs
1349
1350 if (!errorfound || log->lbafirstfailure==0xffffffff || log->lbafirstfailure==0x00000000)
1351 sprintf(firstlba,"%s","-");
1352 else
1353 sprintf(firstlba,"%u",log->lbafirstfailure);
1354
1355 // print out a header if needed
1356 if (noheaderprinted && (allentries || errorfound)){
1357 pout("Num Test_Description Status Remaining LifeTime(hours) LBA_of_first_error\n");
1358 noheaderprinted=0;
1359 }
1360
1361 // print out an entry, either if we are printing all entries OR
1362 // if an error was found
1363 if (allentries || errorfound)
1364 pout("#%2d %s %s %s %8d %s\n", testno, msgtest, msgstat, percent, (int)log->timestamp, firstlba);
1365
1366 // keep track of time of most recent error
1367 if (errorfound && !hours)
1368 hours=log->timestamp;
1369 }
1370 }
1371 if (!allentries && retval)
1372 pout("\n");
1373
1374 hours = hours << 8;
1375 return (retval | hours);
1376 }
1377
1378 void ataPseudoCheckSmart ( struct ata_smart_values *data,
1379 struct ata_smart_thresholds_pvt *thresholds) {
1380 int i;
1381 int failed = 0;
1382 for (i = 0 ; i < NUMBER_ATA_SMART_ATTRIBUTES ; i++) {
1383 if (data->vendor_attributes[i].id &&
1384 thresholds->thres_entries[i].id &&
1385 ATTRIBUTE_FLAGS_PREFAILURE(data->vendor_attributes[i].flags) &&
1386 (data->vendor_attributes[i].current <= thresholds->thres_entries[i].threshold) &&
1387 (thresholds->thres_entries[i].threshold != 0xFE)){
1388 pout("Attribute ID %d Failed\n",(int)data->vendor_attributes[i].id);
1389 failed = 1;
1390 }
1391 }
1392 pout("%s\n", ( failed )?
1393 "SMART overall-health self-assessment test result: FAILED!\n"
1394 "Drive failure expected in less than 24 hours. SAVE ALL DATA":
1395 "SMART overall-health self-assessment test result: PASSED");
1396 }
1397
1398
1399 // Format SCT Temperature value
1400 static const char * sct_ptemp(signed char x, char * buf)
1401 {
1402 if (x == -128 /*0x80 = unknown*/)
1403 strcpy(buf, " ?");
1404 else
1405 sprintf(buf, "%2d", x);
1406 return buf;
1407 }
1408
1409 static const char * sct_pbar(int x, char * buf)
1410 {
1411 if (x <= 19)
1412 x = 0;
1413 else
1414 x -= 19;
1415 bool ov = false;
1416 if (x > 40) {
1417 x = 40; ov = true;
1418 }
1419 if (x > 0) {
1420 memset(buf, '*', x);
1421 if (ov)
1422 buf[x-1] = '+';
1423 buf[x] = 0;
1424 }
1425 else {
1426 buf[0] = '-'; buf[1] = 0;
1427 }
1428 return buf;
1429 }
1430
1431 static const char * sct_device_state_msg(unsigned char state)
1432 {
1433 switch (state) {
1434 case 0: return "Active";
1435 case 1: return "Stand-by";
1436 case 2: return "Sleep";
1437 case 3: return "DST executing in background";
1438 case 4: return "SMART Off-line Data Collection executing in background";
1439 case 5: return "SCT command executing in background";
1440 default:return "Unknown";
1441 }
1442 }
1443
1444 // Print SCT Status
1445 static int ataPrintSCTStatus(const ata_sct_status_response * sts)
1446 {
1447 pout("SCT Status Version: %u\n", sts->format_version);
1448 pout("SCT Version (vendor specific): %u (0x%04x)\n", sts->sct_version, sts->sct_version);
1449 pout("SCT Support Level: %u\n", sts->sct_spec);
1450 pout("Device State: %s (%u)\n",
1451 sct_device_state_msg(sts->device_state), sts->device_state);
1452 char buf1[20], buf2[20];
1453 if ( !sts->min_temp && !sts->life_min_temp && !sts->byte205
1454 && !sts->under_limit_count && !sts->over_limit_count ) {
1455 // "Reserved" fields not set, assume "old" format version 2
1456 // Table 11 of T13/1701DT Revision 5
1457 // Table 54 of T13/1699-D Revision 3e
1458 pout("Current Temperature: %s Celsius\n",
1459 sct_ptemp(sts->hda_temp, buf1));
1460 pout("Power Cycle Max Temperature: %s Celsius\n",
1461 sct_ptemp(sts->max_temp, buf2));
1462 pout("Lifetime Max Temperature: %s Celsius\n",
1463 sct_ptemp(sts->life_max_temp, buf2));
1464 }
1465 else {
1466 // Assume "new" format version 2 or version 3
1467 // T13/e06152r0-3 (Additional SCT Temperature Statistics)
1468 // Table 60 of T13/1699-D Revision 3f
1469 pout("Current Temperature: %s Celsius\n",
1470 sct_ptemp(sts->hda_temp, buf1));
1471 pout("Power Cycle Min/Max Temperature: %s/%s Celsius\n",
1472 sct_ptemp(sts->min_temp, buf1), sct_ptemp(sts->max_temp, buf2));
1473 pout("Lifetime Min/Max Temperature: %s/%s Celsius\n",
1474 sct_ptemp(sts->life_min_temp, buf1), sct_ptemp(sts->life_max_temp, buf2));
1475 if (sts->byte205) // e06152r0-2, removed in e06152r3
1476 pout("Lifetime Average Temperature: %s Celsius\n",
1477 sct_ptemp((signed char)sts->byte205, buf1));
1478 pout("Under/Over Temperature Limit Count: %2u/%u\n",
1479 sts->under_limit_count, sts->over_limit_count);
1480 }
1481 return 0;
1482 }
1483
1484 // Print SCT Temperature History Table
1485 static int ataPrintSCTTempHist(const ata_sct_temperature_history_table * tmh)
1486 {
1487 char buf1[20], buf2[80];
1488 pout("SCT Temperature History Version: %u\n", tmh->format_version);
1489 pout("Temperature Sampling Period: %u minute%s\n",
1490 tmh->sampling_period, (tmh->sampling_period==1?"":"s"));
1491 pout("Temperature Logging Interval: %u minute%s\n",
1492 tmh->interval, (tmh->interval==1?"":"s"));
1493 pout("Min/Max recommended Temperature: %s/%s Celsius\n",
1494 sct_ptemp(tmh->min_op_limit, buf1), sct_ptemp(tmh->max_op_limit, buf2));
1495 pout("Min/Max Temperature Limit: %s/%s Celsius\n",
1496 sct_ptemp(tmh->under_limit, buf1), sct_ptemp(tmh->over_limit, buf2));
1497 pout("Temperature History Size (Index): %u (%u)\n", tmh->cb_size, tmh->cb_index);
1498 if (!(0 < tmh->cb_size && tmh->cb_size <= sizeof(tmh->cb) && tmh->cb_index < tmh->cb_size)) {
1499 pout("Error invalid Temperature History Size or Index\n");
1500 return 0;
1501 }
1502
1503 // Print table
1504 pout("\nIndex Estimated Time Temperature Celsius\n");
1505 unsigned n = 0, i = (tmh->cb_index+1) % tmh->cb_size;
1506 unsigned interval = (tmh->interval > 0 ? tmh->interval : 1);
1507 time_t t = time(0) - (tmh->cb_size-1) * interval * 60;
1508 t -= t % (interval * 60);
1509 while (n < tmh->cb_size) {
1510 // Find range of identical temperatures
1511 unsigned n1 = n, n2 = n+1, i2 = (i+1) % tmh->cb_size;
1512 while (n2 < tmh->cb_size && tmh->cb[i2] == tmh->cb[i]) {
1513 n2++; i2 = (i2+1) % tmh->cb_size;
1514 }
1515 // Print range
1516 while (n < n2) {
1517 if (n == n1 || n == n2-1 || n2 <= n1+3) {
1518 char date[30];
1519 // TODO: Don't print times < boot time
1520 strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&t));
1521 pout(" %3u %s %s %s\n", i, date,
1522 sct_ptemp(tmh->cb[i], buf1), sct_pbar(tmh->cb[i], buf2));
1523 }
1524 else if (n == n1+1) {
1525 pout(" ... ..(%3u skipped). .. %s\n",
1526 n2-n1-2, sct_pbar(tmh->cb[i], buf2));
1527 }
1528 t += interval * 60; i = (i+1) % tmh->cb_size; n++;
1529 }
1530 }
1531 //assert(n == tmh->cb_size && i == (tmh->cb_index+1) % tmh->cb_size);
1532
1533 return 0;
1534 }
1535
1536
1537 // Compares failure type to policy in effect, and either exits or
1538 // simply returns to the calling routine.
1539 void failuretest(int type, int returnvalue){
1540
1541 // If this is an error in an "optional" SMART command
1542 if (type==OPTIONAL_CMD){
1543 if (con->conservative){
1544 pout("An optional SMART command failed: exiting. Remove '-T conservative' option to continue.\n");
1545 EXIT(returnvalue);
1546 }
1547 return;
1548 }
1549
1550 // If this is an error in a "mandatory" SMART command
1551 if (type==MANDATORY_CMD){
1552 if (con->permissive--)
1553 return;
1554 pout("A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.\n");
1555 EXIT(returnvalue);
1556 }
1557
1558 pout("Smartctl internal error in failuretest(type=%d). Please contact developers at " PACKAGE_HOMEPAGE "\n",type);
1559 EXIT(returnvalue|FAILCMD);
1560 }
1561
1562 // Used to warn users about invalid checksums. Action to be taken may be
1563 // altered by the user.
1564 void checksumwarning(const char *string){
1565 // user has asked us to ignore checksum errors
1566 if (con->checksumignore)
1567 return;
1568
1569 pout("Warning! %s error: invalid SMART checksum.\n",string);
1570
1571 // user has asked us to fail on checksum errors
1572 if (con->checksumfail)
1573 EXIT(FAILSMART);
1574
1575 return;
1576 }
1577
1578 // Initialize to zero just in case some SMART routines don't work
1579 struct ata_identify_device drive;
1580 struct ata_smart_values smartval;
1581 struct ata_smart_thresholds_pvt smartthres;
1582 struct ata_smart_errorlog smarterror;
1583 struct ata_smart_selftestlog smartselftest;
1584
1585 int ataPrintMain (int fd){
1586 int timewait,code;
1587 int returnval=0, retid=0, supported=0, needupdate=0, known=0;
1588 const char * powername = 0; char powerchg = 0;
1589
1590 // If requested, check power mode first
1591 if (con->powermode) {
1592 unsigned char powerlimit = 0xff;
1593 int powermode = ataCheckPowerMode(fd);
1594 switch (powermode) {
1595 case -1:
1596 if (errno == ENOSYS) {
1597 pout("CHECK POWER STATUS not implemented, ignoring -n Option\n"); break;
1598 }
1599 powername = "SLEEP"; powerlimit = 2;
1600 break;
1601 case 0:
1602 powername = "STANDBY"; powerlimit = 3; break;
1603 case 0x80:
1604 powername = "IDLE"; powerlimit = 4; break;
1605 case 0xff:
1606 powername = "ACTIVE or IDLE"; break;
1607 default:
1608 pout("CHECK POWER STATUS returned %d, not ATA compliant, ignoring -n Option\n", powermode);
1609 break;
1610 }
1611 if (powername) {
1612 if (con->powermode >= powerlimit) {
1613 pout("Device is in %s mode, exit(%d)\n", powername, FAILPOWER);
1614 return FAILPOWER;
1615 }
1616 powerchg = (powermode != 0xff); // SMART tests will spin up drives
1617 }
1618 }
1619
1620 // Start by getting Drive ID information. We need this, to know if SMART is supported.
1621 if ((retid=ataReadHDIdentity(fd,&drive))<0){
1622 pout("Smartctl: Device Read Identity Failed (not an ATA/ATAPI device)\n\n");
1623 failuretest(MANDATORY_CMD, returnval|=FAILID);
1624 }
1625
1626 // If requested, show which presets would be used for this drive and exit.
1627 if (con->showpresets) {
1628 showpresets(&drive);
1629 EXIT(0);
1630 }
1631
1632 // Use preset vendor attribute options unless user has requested otherwise.
1633 if (!con->ignorepresets){
1634 unsigned char *charptr;
1635 if ((charptr=con->attributedefs))
1636 applypresets(&drive, &charptr, con);
1637 else {
1638 pout("Fatal internal error in ataPrintMain()\n");
1639 EXIT(returnval|=FAILCMD);
1640 }
1641 }
1642
1643 // Print most drive identity information if requested
1644 if (con->driveinfo){
1645 pout("=== START OF INFORMATION SECTION ===\n");
1646 known = ataPrintDriveInfo(&drive);
1647 }
1648
1649 // Was this a packet device?
1650 if (retid>0){
1651 pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n", packetdevicetype(retid-1));
1652 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1653 }
1654
1655 // if drive does not supports SMART it's time to exit
1656 supported=ataSmartSupport(&drive);
1657 if (supported != 1){
1658 if (supported==0) {
1659 pout("SMART support is: Unavailable - device lacks SMART capability.\n");
1660 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1661 pout(" Checking to be sure by trying SMART ENABLE command.\n");
1662 }
1663 else {
1664 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
1665 if (!known) failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1666 pout(" Checking for SMART support by trying SMART ENABLE command.\n");
1667 }
1668
1669 if (ataEnableSmart(fd)){
1670 pout(" SMART ENABLE failed - this establishes that this device lacks SMART functionality.\n");
1671 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1672 supported=0;
1673 }
1674 else {
1675 pout(" SMART ENABLE appeared to work! Continuing.\n");
1676 supported=1;
1677 }
1678 if (!con->driveinfo) pout("\n");
1679 }
1680
1681 // Now print remaining drive info: is SMART enabled?
1682 if (con->driveinfo){
1683 int ison=ataIsSmartEnabled(&drive),isenabled=ison;
1684
1685 if (ison==-1) {
1686 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
1687 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1688 // check SMART support by trying a command
1689 pout(" Checking to be sure by trying SMART RETURN STATUS command.\n");
1690 isenabled=ataDoesSmartWork(fd);
1691 }
1692 else {
1693 pout("SMART support is: Available - device has SMART capability.\n");
1694 #ifdef HAVE_ATA_IDENTIFY_IS_CACHED
1695 if (ata_identify_is_cached(fd)) {
1696 pout(" %sabled status cached by OS, trying SMART RETURN STATUS cmd.\n",
1697 (isenabled?"En":"Dis"));
1698 isenabled=ataDoesSmartWork(fd);
1699 }
1700 #endif
1701 }
1702
1703 if (isenabled)
1704 pout("SMART support is: Enabled\n");
1705 else {
1706 if (ison==-1)
1707 pout("SMART support is: Unavailable\n");
1708 else
1709 pout("SMART support is: Disabled\n");
1710 }
1711 // Print the (now possibly changed) power mode if available
1712 if (powername)
1713 pout("Power mode %s %s\n", (powerchg?"was:":"is: "), powername);
1714 pout("\n");
1715 }
1716
1717 // START OF THE ENABLE/DISABLE SECTION OF THE CODE
1718 if (con->smartenable || con->smartdisable ||
1719 con->smartautosaveenable || con->smartautosavedisable ||
1720 con->smartautoofflineenable || con->smartautoofflinedisable)
1721 pout("=== START OF ENABLE/DISABLE COMMANDS SECTION ===\n");
1722
1723 // Enable/Disable SMART commands
1724 if (con->smartenable){
1725 if (ataEnableSmart(fd)) {
1726 pout("Smartctl: SMART Enable Failed.\n\n");
1727 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1728 }
1729 else
1730 pout("SMART Enabled.\n");
1731 }
1732
1733 // From here on, every command requires that SMART be enabled...
1734 if (!ataDoesSmartWork(fd)) {
1735 pout("SMART Disabled. Use option -s with argument 'on' to enable it.\n");
1736 return returnval;
1737 }
1738
1739 // Turn off SMART on device
1740 if (con->smartdisable){
1741 if (ataDisableSmart(fd)) {
1742 pout( "Smartctl: SMART Disable Failed.\n\n");
1743 failuretest(MANDATORY_CMD,returnval|=FAILSMART);
1744 }
1745 pout("SMART Disabled. Use option -s with argument 'on' to enable it.\n");
1746 return returnval;
1747 }
1748
1749 // Let's ALWAYS issue this command to get the SMART status
1750 code=ataSmartStatus2(fd);
1751 if (code==-1)
1752 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1753
1754 // Enable/Disable Auto-save attributes
1755 if (con->smartautosaveenable){
1756 if (ataEnableAutoSave(fd)){
1757 pout( "Smartctl: SMART Enable Attribute Autosave Failed.\n\n");
1758 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1759 }
1760 else
1761 pout("SMART Attribute Autosave Enabled.\n");
1762 }
1763 if (con->smartautosavedisable){
1764 if (ataDisableAutoSave(fd)){
1765 pout( "Smartctl: SMART Disable Attribute Autosave Failed.\n\n");
1766 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
1767 }
1768 else
1769 pout("SMART Attribute Autosave Disabled.\n");
1770 }
1771
1772 // for everything else read values and thresholds are needed
1773 if (ataReadSmartValues(fd, &smartval)){
1774 pout("Smartctl: SMART Read Values failed.\n\n");
1775 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1776 }
1777 if (ataReadSmartThresholds(fd, &smartthres)){
1778 pout("Smartctl: SMART Read Thresholds failed.\n\n");
1779 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1780 }
1781
1782 // Enable/Disable Off-line testing
1783 if (con->smartautoofflineenable){
1784 if (!isSupportAutomaticTimer(&smartval)){
1785 pout("Warning: device does not support SMART Automatic Timers.\n\n");
1786 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1787 }
1788 needupdate=1;
1789 if (ataEnableAutoOffline(fd)){
1790 pout( "Smartctl: SMART Enable Automatic Offline Failed.\n\n");
1791 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1792 }
1793 else
1794 pout("SMART Automatic Offline Testing Enabled every four hours.\n");
1795 }
1796 if (con->smartautoofflinedisable){
1797 if (!isSupportAutomaticTimer(&smartval)){
1798 pout("Warning: device does not support SMART Automatic Timers.\n\n");
1799 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1800 }
1801 needupdate=1;
1802 if (ataDisableAutoOffline(fd)){
1803 pout("Smartctl: SMART Disable Automatic Offline Failed.\n\n");
1804 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1805 }
1806 else
1807 pout("SMART Automatic Offline Testing Disabled.\n");
1808 }
1809
1810 if (needupdate && ataReadSmartValues(fd, &smartval)){
1811 pout("Smartctl: SMART Read Values failed.\n\n");
1812 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1813 }
1814
1815 // all this for a newline!
1816 if (con->smartenable || con->smartdisable ||
1817 con->smartautosaveenable || con->smartautosavedisable ||
1818 con->smartautoofflineenable || con->smartautoofflinedisable)
1819 pout("\n");
1820
1821 // START OF READ-ONLY OPTIONS APART FROM -V and -i
1822 if ( con->checksmart || con->generalsmartvalues || con->smartvendorattrib || con->smarterrorlog
1823 || con->smartselftestlog || con->selectivetestlog || con->scttempsts || con->scttemphist )
1824 pout("=== START OF READ SMART DATA SECTION ===\n");
1825
1826 // Check SMART status (use previously returned value)
1827 if (con->checksmart){
1828 switch (code) {
1829
1830 case 0:
1831 // The case where the disk health is OK
1832 pout("SMART overall-health self-assessment test result: PASSED\n");
1833 if (ataCheckSmart(&smartval, &smartthres,0)){
1834 if (con->smartvendorattrib)
1835 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
1836 else {
1837 PRINT_ON(con);
1838 pout("Please note the following marginal Attributes:\n");
1839 PrintSmartAttribWithThres(&smartval, &smartthres,2);
1840 }
1841 returnval|=FAILAGE;
1842 }
1843 else
1844 pout("\n");
1845 break;
1846
1847 case 1:
1848 // The case where the disk health is NOT OK
1849 PRINT_ON(con);
1850 pout("SMART overall-health self-assessment test result: FAILED!\n"
1851 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
1852 PRINT_OFF(con);
1853 if (ataCheckSmart(&smartval, &smartthres,1)){
1854 returnval|=FAILATTR;
1855 if (con->smartvendorattrib)
1856 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
1857 else {
1858 PRINT_ON(con);
1859 pout("Failed Attributes:\n");
1860 PrintSmartAttribWithThres(&smartval, &smartthres,1);
1861 }
1862 }
1863 else
1864 pout("No failed Attributes found.\n\n");
1865 returnval|=FAILSTATUS;
1866 PRINT_OFF(con);
1867 break;
1868
1869 case -1:
1870 default:
1871 // The case where something went wrong with HDIO_DRIVE_TASK ioctl()
1872 if (ataCheckSmart(&smartval, &smartthres,1)){
1873 PRINT_ON(con);
1874 pout("SMART overall-health self-assessment test result: FAILED!\n"
1875 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
1876 PRINT_OFF(con);
1877 returnval|=FAILATTR;
1878 returnval|=FAILSTATUS;
1879 if (con->smartvendorattrib)
1880 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
1881 else {
1882 PRINT_ON(con);
1883 pout("Failed Attributes:\n");
1884 PrintSmartAttribWithThres(&smartval, &smartthres,1);
1885 }
1886 }
1887 else {
1888 pout("SMART overall-health self-assessment test result: PASSED\n");
1889 if (ataCheckSmart(&smartval, &smartthres,0)){
1890 if (con->smartvendorattrib)
1891 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
1892 else {
1893 PRINT_ON(con);
1894 pout("Please note the following marginal Attributes:\n");
1895 PrintSmartAttribWithThres(&smartval, &smartthres,2);
1896 }
1897 returnval|=FAILAGE;
1898 }
1899 else
1900 pout("\n");
1901 }
1902 PRINT_OFF(con);
1903 break;
1904 } // end of switch statement
1905
1906 PRINT_OFF(con);
1907 } // end of checking SMART Status
1908
1909 // Print general SMART values
1910 if (con->generalsmartvalues)
1911 ataPrintGeneralSmartValues(&smartval, &drive);
1912
1913 // Print vendor-specific attributes
1914 if (con->smartvendorattrib){
1915 PRINT_ON(con);
1916 PrintSmartAttribWithThres(&smartval, &smartthres,con->printing_switchable?2:0);
1917 PRINT_OFF(con);
1918 }
1919
1920 // Print SMART log Directory
1921 if (con->smartlogdirectory){
1922 struct ata_smart_log_directory smartlogdirectory;
1923 if (!isGeneralPurposeLoggingCapable(&drive)){
1924 pout("Warning: device does not support General Purpose Logging\n");
1925 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1926 }
1927 else {
1928 PRINT_ON(con);
1929 pout("Log Directory Supported\n");
1930 if (ataReadLogDirectory(fd, &smartlogdirectory)){
1931 PRINT_OFF(con);
1932 pout("Read Log Directory failed.\n\n");
1933 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1934 }
1935 else
1936 ataPrintLogDirectory( &smartlogdirectory);
1937 }
1938 PRINT_OFF(con);
1939 }
1940
1941 // Print SMART error log
1942 if (con->smarterrorlog){
1943 if (!isSmartErrorLogCapable(&smartval, &drive)){
1944 pout("Warning: device does not support Error Logging\n");
1945 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1946 }
1947 if (ataReadErrorLog(fd, &smarterror)){
1948 pout("Smartctl: SMART Error Log Read Failed\n");
1949 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1950 }
1951 else {
1952 // quiet mode is turned on inside ataPrintSmartErrorLog()
1953 if (ataPrintSmartErrorlog(&smarterror))
1954 returnval|=FAILERR;
1955 PRINT_OFF(con);
1956 }
1957 }
1958
1959 // Print SMART self-test log
1960 if (con->smartselftestlog){
1961 if (!isSmartTestLogCapable(&smartval, &drive)){
1962 pout("Warning: device does not support Self Test Logging\n");
1963 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1964 }
1965 if(ataReadSelfTestLog(fd, &smartselftest)){
1966 pout("Smartctl: SMART Self Test Log Read Failed\n");
1967 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1968 }
1969 else {
1970 PRINT_ON(con);
1971 if (ataPrintSmartSelfTestlog(&smartselftest,!con->printing_switchable))
1972 returnval|=FAILLOG;
1973 PRINT_OFF(con);
1974 pout("\n");
1975 }
1976 }
1977
1978 // Print SMART selective self-test log
1979 if (con->selectivetestlog){
1980 struct ata_selective_self_test_log log;
1981
1982 if (!isSupportSelectiveSelfTest(&smartval))
1983 pout("Device does not support Selective Self Tests/Logging\n");
1984 else if(ataReadSelectiveSelfTestLog(fd, &log)) {
1985 pout("Smartctl: SMART Selective Self Test Log Read Failed\n");
1986 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
1987 }
1988 else {
1989 PRINT_ON(con);
1990 ataPrintSelectiveSelfTestLog(&log, &smartval);
1991 PRINT_OFF(con);
1992 pout("\n");
1993 }
1994 }
1995
1996 // Print SMART SCT status and temperature history table
1997 if (con->scttempsts || con->scttemphist || con->scttempint) {
1998 for (;;) {
1999 if (!isSCTCapable(&drive)) {
2000 pout("Warning: device does not support SCT Commands\n");
2001 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2002 break;
2003 }
2004 if (con->scttempsts || con->scttemphist) {
2005 ata_sct_status_response sts;
2006 ata_sct_temperature_history_table tmh;
2007 if (!con->scttemphist) {
2008 // Read SCT status only
2009 if (ataReadSCTStatus(fd, &sts)) {
2010 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2011 break;
2012 }
2013 }
2014 else {
2015 if (!isSCTDataTableCapable(&drive)) {
2016 pout("Warning: device does not support SCT Data Table command\n");
2017 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2018 break;
2019 }
2020 // Read SCT status and temperature history
2021 if (ataReadSCTTempHist(fd, &tmh, &sts)) {
2022 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2023 break;
2024 }
2025 }
2026 if (con->scttempsts)
2027 ataPrintSCTStatus(&sts);
2028 if (con->scttemphist)
2029 ataPrintSCTTempHist(&tmh);
2030 pout("\n");
2031 }
2032 if (con->scttempint) {
2033 // Set new temperature logging interval
2034 if (!isSCTFeatureControlCapable(&drive)) {
2035 pout("Warning: device does not support SCT Feature Control command\n");
2036 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2037 break;
2038 }
2039 if (ataSetSCTTempInterval(fd, con->scttempint, !!con->scttempintp)) {
2040 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2041 break;
2042 }
2043 pout("Temperature Logging Interval set to %u minute%s (%s)\n",
2044 con->scttempint, (con->scttempint==1?"":"s"), (con->scttempintp?"persistent":"volatile"));
2045 }
2046 break;
2047 }
2048 }
2049
2050 // START OF THE TESTING SECTION OF THE CODE. IF NO TESTING, RETURN
2051 if (con->testcase==-1)
2052 return returnval;
2053
2054 pout("=== START OF OFFLINE IMMEDIATE AND SELF-TEST SECTION ===\n");
2055 // if doing a self-test, be sure it's supported by the hardware
2056 switch (con->testcase){
2057 case OFFLINE_FULL_SCAN:
2058 if (!isSupportExecuteOfflineImmediate(&smartval)){
2059 pout("Warning: device does not support Execute Offline Immediate function.\n\n");
2060 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2061 }
2062 break;
2063 case ABORT_SELF_TEST:
2064 case SHORT_SELF_TEST:
2065 case EXTEND_SELF_TEST:
2066 case SHORT_CAPTIVE_SELF_TEST:
2067 case EXTEND_CAPTIVE_SELF_TEST:
2068 if (!isSupportSelfTest(&smartval)){
2069 pout("Warning: device does not support Self-Test functions.\n\n");
2070 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2071 }
2072 break;
2073 case CONVEYANCE_SELF_TEST:
2074 case CONVEYANCE_CAPTIVE_SELF_TEST:
2075 if (!isSupportConveyanceSelfTest(&smartval)){
2076 pout("Warning: device does not support Conveyance Self-Test functions.\n\n");
2077 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2078 }
2079 break;
2080 case SELECTIVE_SELF_TEST:
2081 case SELECTIVE_CAPTIVE_SELF_TEST:
2082 if (!isSupportSelectiveSelfTest(&smartval)){
2083 pout("Warning: device does not support Selective Self-Test functions.\n\n");
2084 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2085 }
2086 break;
2087 default:
2088 pout("Internal error in smartctl: con->testcase==%d not recognized\n", (int)con->testcase);
2089 pout("Please contact smartmontools developers at %s.\n", PACKAGE_BUGREPORT);
2090 EXIT(returnval|=FAILCMD);
2091 }
2092
2093 // Now do the test. Note ataSmartTest prints its own error/success
2094 // messages
2095 if (ataSmartTest(fd, con->testcase, &smartval, get_num_sectors(&drive)))
2096 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2097 else {
2098 // Tell user how long test will take to complete. This is tricky
2099 // because in the case of an Offline Full Scan, the completion
2100 // timer is volatile, and needs to be read AFTER the command is
2101 // given. If this will interrupt the Offline Full Scan, we don't
2102 // do it, just warn user.
2103 if (con->testcase==OFFLINE_FULL_SCAN){
2104 if (isSupportOfflineAbort(&smartval))
2105 pout("Note: giving further SMART commands will abort Offline testing\n");
2106 else if (ataReadSmartValues(fd, &smartval)){
2107 pout("Smartctl: SMART Read Values failed.\n");
2108 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2109 }
2110 }
2111
2112 // Now say how long the test will take to complete
2113 if ((timewait=TestTime(&smartval,con->testcase))){
2114 time_t t=time(NULL);
2115 if (con->testcase==OFFLINE_FULL_SCAN) {
2116 t+=timewait;
2117 pout("Please wait %d seconds for test to complete.\n", (int)timewait);
2118 } else {
2119 t+=timewait*60;
2120 pout("Please wait %d minutes for test to complete.\n", (int)timewait);
2121 }
2122 pout("Test will complete after %s\n", ctime(&t));
2123
2124 if (con->testcase!=SHORT_CAPTIVE_SELF_TEST &&
2125 con->testcase!=EXTEND_CAPTIVE_SELF_TEST &&
2126 con->testcase!=CONVEYANCE_CAPTIVE_SELF_TEST &&
2127 con->testcase!=SELECTIVE_CAPTIVE_SELF_TEST)
2128 pout("Use smartctl -X to abort test.\n");
2129 }
2130 }
2131
2132 return returnval;
2133 }