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