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