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