]> git.proxmox.com Git - mirror_smartmontools-debian.git/blame - ataprint.cpp
Update to Standards-Version 3.9.5, no changes need
[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 *
cfbba5b9 6 * Copyright (C) 2002-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
d2e702cf 7 * Copyright (C) 2008-14 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
ee38a438 16 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
832b75ed
GG
17 *
18 * This code was originally developed as a Senior Thesis by Michael Cornwell
19 * at the Concurrent Systems Laboratory (now part of the Storage Systems
20 * Research Center), Jack Baskin School of Engineering, University of
21 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
22 *
23 */
24
25#include "config.h"
26
27#include <ctype.h>
4d59bff9 28#include <errno.h>
832b75ed 29#include <stdio.h>
2127e193 30#include <stdlib.h>
832b75ed 31#include <string.h>
832b75ed
GG
32
33#include "int64.h"
34#include "atacmdnames.h"
35#include "atacmds.h"
ee38a438 36#include "ataidentify.h"
2127e193 37#include "dev_interface.h"
832b75ed
GG
38#include "ataprint.h"
39#include "smartctl.h"
832b75ed
GG
40#include "utility.h"
41#include "knowndrives.h"
42
d2e702cf 43const char * ataprint_cpp_cvsid = "$Id: ataprint.cpp 3982 2014-08-16 21:07:19Z samm2 $"
2127e193 44 ATAPRINT_H_CVSID;
832b75ed 45
832b75ed 46
a37e7145
GG
47static const char * infofound(const char *output) {
48 return (*output ? output : "[No Information Found]");
832b75ed
GG
49}
50
cfbba5b9
GI
51// Return true if '-T permissive' is specified,
52// used to ignore missing capabilities
53static bool is_permissive()
54{
55 if (!failuretest_permissive)
56 return false;
57 failuretest_permissive--;
58 return true;
59}
832b75ed
GG
60
61/* For the given Command Register (CR) and Features Register (FR), attempts
62 * to construct a string that describes the contents of the Status
ee38a438
GI
63 * Register (ST) and Error Register (ER). If the meanings of the flags of
64 * the error register are not known for the given command then it returns an
65 * empty string.
832b75ed
GG
66 *
67 * The meanings of the flags of the error register for all commands are
68 * described in the ATA spec and could all be supported here in theory.
69 * Currently, only a few commands are supported (those that have been seen
70 * to produce errors). If many more are to be added then this function
71 * should probably be redesigned.
72 */
2127e193 73
ee38a438 74static std::string format_st_er_desc(
2127e193
GI
75 unsigned char CR, unsigned char FR,
76 unsigned char ST, unsigned char ER,
77 unsigned short SC,
78 const ata_smart_errorlog_error_struct * lba28_regs,
79 const ata_smart_exterrlog_error * lba48_regs
80)
81{
832b75ed
GG
82 const char *error_flag[8];
83 int i, print_lba=0, print_sector=0;
84
85 // Set of character strings corresponding to different error codes.
86 // Please keep in alphabetic order if you add more.
87 const char *abrt = "ABRT"; // ABORTED
88 const char *amnf = "AMNF"; // ADDRESS MARK NOT FOUND
ba59cff1 89 const char *ccto = "CCTO"; // COMMAND COMPLETION TIMED OUT
832b75ed
GG
90 const char *eom = "EOM"; // END OF MEDIA
91 const char *icrc = "ICRC"; // INTERFACE CRC ERROR
92 const char *idnf = "IDNF"; // ID NOT FOUND
93 const char *ili = "ILI"; // MEANING OF THIS BIT IS COMMAND-SET SPECIFIC
94 const char *mc = "MC"; // MEDIA CHANGED
95 const char *mcr = "MCR"; // MEDIA CHANGE REQUEST
96 const char *nm = "NM"; // NO MEDIA
97 const char *obs = "obs"; // OBSOLETE
98 const char *tk0nf = "TK0NF"; // TRACK 0 NOT FOUND
99 const char *unc = "UNC"; // UNCORRECTABLE
100 const char *wp = "WP"; // WRITE PROTECTED
101
102 /* If for any command the Device Fault flag of the status register is
103 * not used then used_device_fault should be set to 0 (in the CR switch
104 * below)
105 */
106 int uses_device_fault = 1;
107
108 /* A value of NULL means that the error flag isn't used */
109 for (i = 0; i < 8; i++)
110 error_flag[i] = NULL;
111
ee38a438
GI
112 std::string str;
113
832b75ed
GG
114 switch (CR) {
115 case 0x10: // RECALIBRATE
116 error_flag[2] = abrt;
117 error_flag[1] = tk0nf;
118 break;
119 case 0x20: /* READ SECTOR(S) */
120 case 0x21: // READ SECTOR(S)
121 case 0x24: // READ SECTOR(S) EXT
122 case 0xC4: /* READ MULTIPLE */
123 case 0x29: // READ MULTIPLE EXT
124 error_flag[6] = unc;
125 error_flag[5] = mc;
126 error_flag[4] = idnf;
127 error_flag[3] = mcr;
128 error_flag[2] = abrt;
129 error_flag[1] = nm;
130 error_flag[0] = amnf;
131 print_lba=1;
132 break;
133 case 0x22: // READ LONG (with retries)
134 case 0x23: // READ LONG (without retries)
135 error_flag[4] = idnf;
136 error_flag[2] = abrt;
137 error_flag[0] = amnf;
138 print_lba=1;
139 break;
140 case 0x2a: // READ STREAM DMA
141 case 0x2b: // READ STREAM PIO
142 if (CR==0x2a)
143 error_flag[7] = icrc;
144 error_flag[6] = unc;
145 error_flag[5] = mc;
146 error_flag[4] = idnf;
147 error_flag[3] = mcr;
148 error_flag[2] = abrt;
149 error_flag[1] = nm;
150 error_flag[0] = ccto;
151 print_lba=1;
2127e193 152 print_sector=SC;
832b75ed
GG
153 break;
154 case 0x3A: // WRITE STREAM DMA
155 case 0x3B: // WRITE STREAM PIO
156 if (CR==0x3A)
157 error_flag[7] = icrc;
158 error_flag[6] = wp;
159 error_flag[5] = mc;
160 error_flag[4] = idnf;
161 error_flag[3] = mcr;
162 error_flag[2] = abrt;
163 error_flag[1] = nm;
164 error_flag[0] = ccto;
165 print_lba=1;
2127e193 166 print_sector=SC;
832b75ed 167 break;
a7e8ffec 168 case 0x25: // READ DMA EXT
832b75ed
GG
169 case 0x26: // READ DMA QUEUED EXT
170 case 0xC7: // READ DMA QUEUED
a7e8ffec
GI
171 case 0xC8: // READ DMA (with retries)
172 case 0xC9: // READ DMA (without retries, obsolete since ATA-5)
173 case 0x60: // READ FPDMA QUEUED (NCQ)
832b75ed
GG
174 error_flag[7] = icrc;
175 error_flag[6] = unc;
176 error_flag[5] = mc;
177 error_flag[4] = idnf;
178 error_flag[3] = mcr;
179 error_flag[2] = abrt;
180 error_flag[1] = nm;
181 error_flag[0] = amnf;
182 print_lba=1;
183 if (CR==0x25 || CR==0xC8)
2127e193 184 print_sector=SC;
832b75ed
GG
185 break;
186 case 0x30: /* WRITE SECTOR(S) */
187 case 0x31: // WRITE SECTOR(S)
188 case 0x34: // WRITE SECTOR(S) EXT
189 case 0xC5: /* WRITE MULTIPLE */
190 case 0x39: // WRITE MULTIPLE EXT
191 case 0xCE: // WRITE MULTIPLE FUA EXT
192 error_flag[6] = wp;
193 error_flag[5] = mc;
194 error_flag[4] = idnf;
195 error_flag[3] = mcr;
196 error_flag[2] = abrt;
197 error_flag[1] = nm;
198 print_lba=1;
199 break;
200 case 0x32: // WRITE LONG (with retries)
201 case 0x33: // WRITE LONG (without retries)
202 error_flag[4] = idnf;
203 error_flag[2] = abrt;
204 print_lba=1;
205 break;
206 case 0x3C: // WRITE VERIFY
207 error_flag[6] = unc;
208 error_flag[4] = idnf;
209 error_flag[2] = abrt;
210 error_flag[0] = amnf;
211 print_lba=1;
212 break;
213 case 0x40: // READ VERIFY SECTOR(S) with retries
214 case 0x41: // READ VERIFY SECTOR(S) without retries
215 case 0x42: // READ VERIFY SECTOR(S) EXT
216 error_flag[6] = unc;
217 error_flag[5] = mc;
218 error_flag[4] = idnf;
219 error_flag[3] = mcr;
220 error_flag[2] = abrt;
221 error_flag[1] = nm;
222 error_flag[0] = amnf;
223 print_lba=1;
224 break;
225 case 0xA0: /* PACKET */
226 /* Bits 4-7 are all used for sense key (a 'command packet set specific error
227 * indication' according to the ATA/ATAPI-7 standard), so "Sense key" will
228 * be repeated in the error description string if more than one of those
229 * bits is set.
230 */
231 error_flag[7] = "Sense key (bit 3)",
232 error_flag[6] = "Sense key (bit 2)",
233 error_flag[5] = "Sense key (bit 1)",
234 error_flag[4] = "Sense key (bit 0)",
235 error_flag[2] = abrt;
236 error_flag[1] = eom;
237 error_flag[0] = ili;
238 break;
239 case 0xA1: /* IDENTIFY PACKET DEVICE */
240 case 0xEF: /* SET FEATURES */
241 case 0x00: /* NOP */
242 case 0xC6: /* SET MULTIPLE MODE */
243 error_flag[2] = abrt;
244 break;
245 case 0x2F: // READ LOG EXT
246 error_flag[6] = unc;
247 error_flag[4] = idnf;
248 error_flag[2] = abrt;
249 error_flag[0] = obs;
250 break;
251 case 0x3F: // WRITE LOG EXT
252 error_flag[4] = idnf;
253 error_flag[2] = abrt;
254 error_flag[0] = obs;
255 break;
256 case 0xB0: /* SMART */
257 switch(FR) {
258 case 0xD0: // SMART READ DATA
259 case 0xD1: // SMART READ ATTRIBUTE THRESHOLDS
260 case 0xD5: /* SMART READ LOG */
261 error_flag[6] = unc;
262 error_flag[4] = idnf;
263 error_flag[2] = abrt;
264 error_flag[0] = obs;
265 break;
266 case 0xD6: /* SMART WRITE LOG */
267 error_flag[4] = idnf;
268 error_flag[2] = abrt;
269 error_flag[0] = obs;
270 break;
271 case 0xD2: // Enable/Disable Attribute Autosave
272 case 0xD3: // SMART SAVE ATTRIBUTE VALUES (ATA-3)
273 case 0xD8: // SMART ENABLE OPERATIONS
274 case 0xD9: /* SMART DISABLE OPERATIONS */
275 case 0xDA: /* SMART RETURN STATUS */
276 case 0xDB: // Enable/Disable Auto Offline (SFF)
277 error_flag[2] = abrt;
278 break;
279 case 0xD4: // SMART EXECUTE IMMEDIATE OFFLINE
280 error_flag[4] = idnf;
281 error_flag[2] = abrt;
282 break;
283 default:
ee38a438 284 return str; // ""
832b75ed
GG
285 break;
286 }
287 break;
288 case 0xB1: /* DEVICE CONFIGURATION */
289 switch (FR) {
290 case 0xC0: /* DEVICE CONFIGURATION RESTORE */
291 error_flag[2] = abrt;
292 break;
293 default:
ee38a438 294 return str; // ""
832b75ed
GG
295 break;
296 }
297 break;
a7e8ffec
GI
298 case 0xCA: // WRITE DMA (with retries)
299 case 0xCB: // WRITE DMA (without retries, obsolete since ATA-5)
832b75ed
GG
300 case 0x35: // WRITE DMA EXT
301 case 0x3D: // WRITE DMA FUA EXT
302 case 0xCC: // WRITE DMA QUEUED
303 case 0x36: // WRITE DMA QUEUED EXT
304 case 0x3E: // WRITE DMA QUEUED FUA EXT
a7e8ffec 305 case 0x61: // WRITE FPDMA QUEUED (NCQ)
832b75ed
GG
306 error_flag[7] = icrc;
307 error_flag[6] = wp;
308 error_flag[5] = mc;
309 error_flag[4] = idnf;
310 error_flag[3] = mcr;
311 error_flag[2] = abrt;
312 error_flag[1] = nm;
313 error_flag[0] = amnf;
314 print_lba=1;
315 if (CR==0x35)
2127e193 316 print_sector=SC;
832b75ed
GG
317 break;
318 case 0xE4: // READ BUFFER
319 case 0xE8: // WRITE BUFFER
320 error_flag[2] = abrt;
321 break;
322 default:
ee38a438 323 return str; // ""
832b75ed
GG
324 }
325
832b75ed
GG
326 /* We ignore any status flags other than Device Fault and Error */
327
328 if (uses_device_fault && (ST & (1 << 5))) {
ee38a438 329 str = "Device Fault";
832b75ed 330 if (ST & 1) // Error flag
ee38a438 331 str += "; ";
832b75ed
GG
332 }
333 if (ST & 1) { // Error flag
334 int count = 0;
335
ee38a438 336 str += "Error: ";
832b75ed
GG
337 for (i = 7; i >= 0; i--)
338 if ((ER & (1 << i)) && (error_flag[i])) {
339 if (count++ > 0)
ee38a438
GI
340 str += ", ";
341 str += error_flag[i];
832b75ed
GG
342 }
343 }
344
345 // If the error was a READ or WRITE error, print the Logical Block
346 // Address (LBA) at which the read or write failed.
347 if (print_lba) {
832b75ed 348 // print number of sectors, if known, and append to print string
ee38a438
GI
349 if (print_sector)
350 str += strprintf(" %d sectors", print_sector);
832b75ed 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;
ee38a438 365 str += strprintf(" at LBA = 0x%08x = %u", lba, lba);
2127e193
GI
366 }
367 else if (lba48_regs) {
368 // This assumes that upper LBA registers are 0 for 28-bit commands
369 // (TODO: detect 48-bit commands above)
370 uint64_t lba48;
371 lba48 = lba48_regs->lba_high_register_hi;
372 lba48 <<= 8;
373 lba48 |= lba48_regs->lba_mid_register_hi;
374 lba48 <<= 8;
375 lba48 |= lba48_regs->lba_low_register_hi;
376 lba48 |= lba48_regs->device_register & 0xf;
377 lba48 <<= 8;
378 lba48 |= lba48_regs->lba_high_register;
379 lba48 <<= 8;
380 lba48 |= lba48_regs->lba_mid_register;
381 lba48 <<= 8;
382 lba48 |= lba48_regs->lba_low_register;
d2e702cf 383 str += strprintf(" at LBA = 0x%08" PRIx64 " = %" PRIu64, lba48, lba48);
2127e193 384 }
832b75ed
GG
385 }
386
ee38a438 387 return str;
832b75ed
GG
388}
389
ee38a438 390static inline std::string format_st_er_desc(
2127e193
GI
391 const ata_smart_errorlog_struct * data)
392{
ee38a438 393 return format_st_er_desc(
2127e193
GI
394 data->commands[4].commandreg,
395 data->commands[4].featuresreg,
396 data->error_struct.status,
397 data->error_struct.error_register,
398 data->error_struct.sector_count,
399 &data->error_struct, (const ata_smart_exterrlog_error *)0);
400}
832b75ed 401
ee38a438 402static inline std::string format_st_er_desc(
2127e193 403 const ata_smart_exterrlog_error_log * data)
a37e7145 404{
ee38a438 405 return format_st_er_desc(
2127e193
GI
406 data->commands[4].command_register,
407 data->commands[4].features_register,
408 data->error.status_register,
409 data->error.error_register,
410 data->error.count_register_hi << 8 | data->error.count_register,
411 (const ata_smart_errorlog_error_struct *)0, &data->error);
a37e7145
GG
412}
413
ee38a438
GI
414
415static int find_msb(unsigned short word)
416{
417 for (int bit = 15; bit >= 0; bit--)
418 if (word & (1 << bit))
419 return bit;
420 return -1;
421}
422
423static const char * get_ata_major_version(const ata_identify_device * drive)
424{
425 switch (find_msb(drive->major_rev_num)) {
426 case 10: return "ACS-3";
427 case 9: return "ACS-2";
428 case 8: return "ATA8-ACS";
429 case 7: return "ATA/ATAPI-7";
430 case 6: return "ATA/ATAPI-6";
431 case 5: return "ATA/ATAPI-5";
432 case 4: return "ATA/ATAPI-4";
433 case 3: return "ATA-3";
434 case 2: return "ATA-2";
435 case 1: return "ATA-1";
436 default: return 0;
437 }
438}
439
440static const char * get_ata_minor_version(const ata_identify_device * drive)
441{
442 switch (drive->minor_rev_num) {
443 case 0x0001: return "ATA-1 X3T9.2/781D prior to revision 4";
444 case 0x0002: return "ATA-1 published, ANSI X3.221-1994";
445 case 0x0003: return "ATA-1 X3T9.2/781D revision 4";
446 case 0x0004: return "ATA-2 published, ANSI X3.279-1996";
447 case 0x0005: return "ATA-2 X3T10/948D prior to revision 2k";
448 case 0x0006: return "ATA-3 X3T10/2008D revision 1";
449 case 0x0007: return "ATA-2 X3T10/948D revision 2k";
450 case 0x0008: return "ATA-3 X3T10/2008D revision 0";
451 case 0x0009: return "ATA-2 X3T10/948D revision 3";
452 case 0x000a: return "ATA-3 published, ANSI X3.298-1997";
453 case 0x000b: return "ATA-3 X3T10/2008D revision 6"; // 1st ATA-3 revision with SMART
454 case 0x000c: return "ATA-3 X3T13/2008D revision 7 and 7a";
455 case 0x000d: return "ATA/ATAPI-4 X3T13/1153D revision 6";
456 case 0x000e: return "ATA/ATAPI-4 T13/1153D revision 13";
457 case 0x000f: return "ATA/ATAPI-4 X3T13/1153D revision 7";
458 case 0x0010: return "ATA/ATAPI-4 T13/1153D revision 18";
459 case 0x0011: return "ATA/ATAPI-4 T13/1153D revision 15";
460 case 0x0012: return "ATA/ATAPI-4 published, ANSI NCITS 317-1998";
461 case 0x0013: return "ATA/ATAPI-5 T13/1321D revision 3";
462 case 0x0014: return "ATA/ATAPI-4 T13/1153D revision 14";
463 case 0x0015: return "ATA/ATAPI-5 T13/1321D revision 1";
464 case 0x0016: return "ATA/ATAPI-5 published, ANSI NCITS 340-2000";
465 case 0x0017: return "ATA/ATAPI-4 T13/1153D revision 17";
466 case 0x0018: return "ATA/ATAPI-6 T13/1410D revision 0";
467 case 0x0019: return "ATA/ATAPI-6 T13/1410D revision 3a";
468 case 0x001a: return "ATA/ATAPI-7 T13/1532D revision 1";
469 case 0x001b: return "ATA/ATAPI-6 T13/1410D revision 2";
470 case 0x001c: return "ATA/ATAPI-6 T13/1410D revision 1";
471 case 0x001d: return "ATA/ATAPI-7 published, ANSI INCITS 397-2005";
472 case 0x001e: return "ATA/ATAPI-7 T13/1532D revision 0";
473 case 0x001f: return "ACS-3 T13/2161-D revision 3b";
474
475 case 0x0021: return "ATA/ATAPI-7 T13/1532D revision 4a";
476 case 0x0022: return "ATA/ATAPI-6 published, ANSI INCITS 361-2002";
477
478 case 0x0027: return "ATA8-ACS T13/1699-D revision 3c";
479 case 0x0028: return "ATA8-ACS T13/1699-D revision 6";
480 case 0x0029: return "ATA8-ACS T13/1699-D revision 4";
481
482 case 0x0031: return "ACS-2 T13/2015-D revision 2";
483
484 case 0x0033: return "ATA8-ACS T13/1699-D revision 3e";
485
486 case 0x0039: return "ATA8-ACS T13/1699-D revision 4c";
487
488 case 0x0042: return "ATA8-ACS T13/1699-D revision 3f";
489
490 case 0x0052: return "ATA8-ACS T13/1699-D revision 3b";
491
492 case 0x0107: return "ATA8-ACS T13/1699-D revision 2d";
493
494 case 0x0110: return "ACS-2 T13/2015-D revision 3";
495
496 default: return 0;
497 }
498}
499
500static const char * get_sata_version(const ata_identify_device * drive)
501{
502 unsigned short word222 = drive->words088_255[222-88];
503 if ((word222 & 0xf000) != 0x1000)
504 return 0;
505 switch (find_msb(word222 & 0x0fff)) {
506 default: return "SATA >3.1";
507 case 6: return "SATA 3.1";
508 case 5: return "SATA 3.0";
509 case 4: return "SATA 2.6";
510 case 3: return "SATA 2.5";
511 case 2: return "SATA II Ext";
512 case 1: return "SATA 1.0a";
513 case 0: return "ATA8-AST";
514 case -1: return 0;
515 }
516}
517
518static const char * get_sata_speed(int level)
519{
520 if (level <= 0)
521 return 0;
522 switch (level) {
523 default: return ">6.0 Gb/s";
524 case 3: return "6.0 Gb/s";
525 case 2: return "3.0 Gb/s";
526 case 1: return "1.5 Gb/s";
527 }
528}
529
530static const char * get_sata_maxspeed(const ata_identify_device * drive)
531{
532 unsigned short word076 = drive->words047_079[76-47];
533 if (word076 & 0x0001)
534 return 0;
535 return get_sata_speed(find_msb(word076 & 0x00fe));
536}
537
538static const char * get_sata_curspeed(const ata_identify_device * drive)
539{
540 unsigned short word077 = drive->words047_079[77-47];
541 if (word077 & 0x0001)
542 return 0;
543 return get_sata_speed((word077 >> 1) & 0x7);
544}
545
546
cfbba5b9 547static void print_drive_info(const ata_identify_device * drive,
ee38a438 548 const ata_size_info & sizes, int rpm,
cfbba5b9
GI
549 const drive_settings * dbentry)
550{
551 // format drive information (with byte swapping as needed)
552 char model[40+1], serial[20+1], firmware[8+1];
553 ata_format_id_string(model, drive->model, sizeof(model)-1);
554 ata_format_id_string(serial, drive->serial_no, sizeof(serial)-1);
555 ata_format_id_string(firmware, drive->fw_rev, sizeof(firmware)-1);
832b75ed
GG
556
557 // Print model family if known
2127e193
GI
558 if (dbentry && *dbentry->modelfamily)
559 pout("Model Family: %s\n", dbentry->modelfamily);
832b75ed 560
a37e7145 561 pout("Device Model: %s\n", infofound(model));
a7e8ffec 562 if (!dont_print_serial_number) {
a37e7145 563 pout("Serial Number: %s\n", infofound(serial));
a7e8ffec
GI
564
565 unsigned oui = 0; uint64_t unique_id = 0;
566 int naa = ata_get_wwn(drive, oui, unique_id);
567 if (naa >= 0)
d2e702cf 568 pout("LU WWN Device Id: %x %06x %09" PRIx64 "\n", naa, oui, unique_id);
ee38a438
GI
569
570 // Additional Product Identifier (OEM Id) string in words 170-173
571 // (e08130r1, added in ACS-2 Revision 1, December 17, 2008)
572 if (0x2020 <= drive->words088_255[170-88] && drive->words088_255[170-88] <= 0x7e7e) {
573 char add[8+1];
574 ata_format_id_string(add, (const unsigned char *)(drive->words088_255+170-88), sizeof(add)-1);
575 if (add[0])
576 pout("Add. Product Id: %s\n", add);
577 }
a7e8ffec 578 }
cfbba5b9 579 pout("Firmware Version: %s\n", infofound(firmware));
832b75ed 580
a7e8ffec
GI
581 if (sizes.capacity) {
582 // Print capacity
583 char num[64], cap[32];
584 pout("User Capacity: %s bytes [%s]\n",
585 format_with_thousands_sep(num, sizeof(num), sizes.capacity),
586 format_capacity(cap, sizeof(cap), sizes.capacity));
587
588 // Print sector sizes.
589 if (sizes.phy_sector_size == sizes.log_sector_size)
590 pout("Sector Size: %u bytes logical/physical\n", sizes.log_sector_size);
591 else {
592 pout("Sector Sizes: %u bytes logical, %u bytes physical",
593 sizes.log_sector_size, sizes.phy_sector_size);
594 if (sizes.log_sector_offset)
595 pout(" (offset %u bytes)", sizes.log_sector_offset);
596 pout("\n");
597 }
cfbba5b9
GI
598 }
599
ee38a438
GI
600 // Print nominal media rotation rate if reported
601 if (rpm) {
602 if (rpm == 1)
603 pout("Rotation Rate: Solid State Device\n");
604 else if (rpm > 1)
605 pout("Rotation Rate: %d rpm\n", rpm);
606 else
607 pout("Rotation Rate: Unknown (0x%04x)\n", -rpm);
608 }
609
d2e702cf
GI
610 // Print form factor if reported
611 unsigned short word168 = drive->words088_255[168-88];
612 if (word168) {
613 const char * inches;
614 switch (word168) {
615 case 0x1: inches = "5.25"; break;
616 case 0x2: inches = "3.5"; break;
617 case 0x3: inches = "2.5"; break;
618 case 0x4: inches = "1.8"; break;
619 case 0x5: inches = "< 1.8"; break;
620 default : inches = 0;
621 }
622 if (inches)
623 pout("Form Factor: %s inches\n", inches);
624 else
625 pout("Form Factor: Unknown (0x%04x)\n", word168);
626 }
627
832b75ed 628 // See if drive is recognized
2127e193 629 pout("Device is: %s\n", !dbentry ?
832b75ed
GG
630 "Not in smartctl database [for details use: -P showall]":
631 "In smartctl database [for details use: -P show]");
632
ee38a438
GI
633 // Print ATA version
634 std::string ataver;
635 if ( (drive->major_rev_num != 0x0000 && drive->major_rev_num != 0xffff)
636 || (drive->minor_rev_num != 0x0000 && drive->minor_rev_num != 0xffff)) {
637 const char * majorver = get_ata_major_version(drive);
638 const char * minorver = get_ata_minor_version(drive);
639
640 if (majorver && minorver && str_starts_with(minorver, majorver)) {
641 // Major and minor strings match, print minor string only
642 ataver = minorver;
d008864d
GI
643 }
644 else {
ee38a438
GI
645 if (majorver)
646 ataver = majorver;
647 else
648 ataver = strprintf("Unknown(0x%04x)", drive->major_rev_num);
649
650 if (minorver)
651 ataver += strprintf(", %s", minorver);
652 else if (drive->minor_rev_num != 0x0000 && drive->minor_rev_num != 0xffff)
653 ataver += strprintf(" (unknown minor revision code: 0x%04x)", drive->minor_rev_num);
d008864d 654 else
ee38a438 655 ataver += " (minor revision not indicated)";
d008864d 656 }
a23d5117 657 }
ee38a438 658 pout("ATA Version is: %s\n", infofound(ataver.c_str()));
a23d5117 659
ee38a438
GI
660 // If SATA drive print SATA version and speed
661 const char * sataver = get_sata_version(drive);
662 if (sataver) {
663 const char * maxspeed = get_sata_maxspeed(drive);
664 const char * curspeed = get_sata_curspeed(drive);
665 pout("SATA Version is: %s%s%s%s%s%s\n", sataver,
666 (maxspeed ? ", " : ""), (maxspeed ? maxspeed : ""),
667 (curspeed ? " (current: " : ""), (curspeed ? curspeed : ""),
668 (curspeed ? ")" : ""));
669 }
a23d5117 670
832b75ed 671 // print current time and date and timezone
2127e193 672 char timedatetz[DATEANDEPOCHLEN]; dateandtimezone(timedatetz);
832b75ed
GG
673 pout("Local Time is: %s\n", timedatetz);
674
675 // Print warning message, if there is one
2127e193
GI
676 if (dbentry && *dbentry->warningmsg)
677 pout("\n==> WARNING: %s\n\n", dbentry->warningmsg);
832b75ed
GG
678}
679
2127e193
GI
680static const char *OfflineDataCollectionStatus(unsigned char status_byte)
681{
832b75ed
GG
682 unsigned char stat=status_byte & 0x7f;
683
684 switch(stat){
685 case 0x00:
686 return "was never started";
687 case 0x02:
688 return "was completed without error";
689 case 0x03:
690 if (status_byte == 0x03)
691 return "is in progress";
692 else
693 return "is in a Reserved state";
694 case 0x04:
695 return "was suspended by an interrupting command from host";
696 case 0x05:
697 return "was aborted by an interrupting command from host";
698 case 0x06:
699 return "was aborted by the device with a fatal error";
700 default:
701 if (stat >= 0x40)
2127e193 702 return "is in a Vendor Specific state";
832b75ed 703 else
2127e193 704 return "is in a Reserved state";
832b75ed
GG
705 }
706}
707
708
2127e193
GI
709// prints verbose value Off-line data collection status byte
710static void PrintSmartOfflineStatus(const ata_smart_values * data)
711{
832b75ed
GG
712 pout("Offline data collection status: (0x%02x)\t",
713 (int)data->offline_data_collection_status);
714
715 // Off-line data collection status byte is not a reserved
716 // or vendor specific value
717 pout("Offline data collection activity\n"
718 "\t\t\t\t\t%s.\n", OfflineDataCollectionStatus(data->offline_data_collection_status));
719
720 // Report on Automatic Data Collection Status. Only IBM documents
721 // this bit. See SFF 8035i Revision 2 for details.
722 if (data->offline_data_collection_status & 0x80)
723 pout("\t\t\t\t\tAuto Offline Data Collection: Enabled.\n");
724 else
725 pout("\t\t\t\t\tAuto Offline Data Collection: Disabled.\n");
726
727 return;
728}
729
2127e193 730static void PrintSmartSelfExecStatus(const ata_smart_values * data,
ee38a438 731 firmwarebug_defs firmwarebugs)
832b75ed
GG
732{
733 pout("Self-test execution status: ");
734
735 switch (data->self_test_exec_status >> 4)
736 {
737 case 0:
738 pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
739 (int)data->self_test_exec_status);
740 pout("without error or no self-test has ever \n\t\t\t\t\tbeen run.\n");
741 break;
742 case 1:
743 pout("(%4d)\tThe self-test routine was aborted by\n\t\t\t\t\t",
744 (int)data->self_test_exec_status);
745 pout("the host.\n");
746 break;
747 case 2:
748 pout("(%4d)\tThe self-test routine was interrupted\n\t\t\t\t\t",
749 (int)data->self_test_exec_status);
750 pout("by the host with a hard or soft reset.\n");
751 break;
752 case 3:
753 pout("(%4d)\tA fatal error or unknown test error\n\t\t\t\t\t",
754 (int)data->self_test_exec_status);
755 pout("occurred while the device was executing\n\t\t\t\t\t");
756 pout("its self-test routine and the device \n\t\t\t\t\t");
757 pout("was unable to complete the self-test \n\t\t\t\t\t");
758 pout("routine.\n");
759 break;
760 case 4:
761 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
762 (int)data->self_test_exec_status);
763 pout("a test element that failed and the test\n\t\t\t\t\t");
764 pout("element that failed is not known.\n");
765 break;
766 case 5:
767 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
768 (int)data->self_test_exec_status);
769 pout("the electrical element of the test\n\t\t\t\t\t");
770 pout("failed.\n");
771 break;
772 case 6:
773 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
774 (int)data->self_test_exec_status);
775 pout("the servo (and/or seek) element of the \n\t\t\t\t\t");
776 pout("test failed.\n");
777 break;
778 case 7:
779 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
780 (int)data->self_test_exec_status);
781 pout("the read element of the test failed.\n");
782 break;
a37e7145
GG
783 case 8:
784 pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
832b75ed 785 (int)data->self_test_exec_status);
a37e7145
GG
786 pout("a test element that failed and the\n\t\t\t\t\t");
787 pout("device is suspected of having handling\n\t\t\t\t\t");
788 pout("damage.\n");
789 break;
790 case 15:
ee38a438 791 if (firmwarebugs.is_set(BUG_SAMSUNG3) && data->self_test_exec_status == 0xf0) {
a37e7145
GG
792 pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
793 (int)data->self_test_exec_status);
794 pout("with unknown result or self-test in\n\t\t\t\t\t");
795 pout("progress with less than 10%% remaining.\n");
796 }
797 else {
798 pout("(%4d)\tSelf-test routine in progress...\n\t\t\t\t\t",
799 (int)data->self_test_exec_status);
800 pout("%1d0%% of test remaining.\n",
832b75ed 801 (int)(data->self_test_exec_status & 0x0f));
a37e7145 802 }
832b75ed
GG
803 break;
804 default:
805 pout("(%4d)\tReserved.\n",
806 (int)data->self_test_exec_status);
807 break;
808 }
809
810}
811
2127e193
GI
812static void PrintSmartTotalTimeCompleteOffline (const ata_smart_values * data)
813{
832b75ed 814 pout("Total time to complete Offline \n");
cfbba5b9 815 pout("data collection: \t\t(%5d) seconds.\n",
832b75ed
GG
816 (int)data->total_time_to_complete_off_line);
817}
818
2127e193
GI
819static void PrintSmartOfflineCollectCap(const ata_smart_values *data)
820{
832b75ed
GG
821 pout("Offline data collection\n");
822 pout("capabilities: \t\t\t (0x%02x) ",
823 (int)data->offline_data_collection_capability);
824
825 if (data->offline_data_collection_capability == 0x00){
826 pout("\tOffline data collection not supported.\n");
827 }
828 else {
829 pout( "%s\n", isSupportExecuteOfflineImmediate(data)?
830 "SMART execute Offline immediate." :
831 "No SMART execute Offline immediate.");
832
833 pout( "\t\t\t\t\t%s\n", isSupportAutomaticTimer(data)?
834 "Auto Offline data collection on/off support.":
835 "No Auto Offline data collection support.");
836
837 pout( "\t\t\t\t\t%s\n", isSupportOfflineAbort(data)?
838 "Abort Offline collection upon new\n\t\t\t\t\tcommand.":
839 "Suspend Offline collection upon new\n\t\t\t\t\tcommand.");
840
841 pout( "\t\t\t\t\t%s\n", isSupportOfflineSurfaceScan(data)?
842 "Offline surface scan supported.":
843 "No Offline surface scan supported.");
844
845 pout( "\t\t\t\t\t%s\n", isSupportSelfTest(data)?
846 "Self-test supported.":
847 "No Self-test supported.");
848
849 pout( "\t\t\t\t\t%s\n", isSupportConveyanceSelfTest(data)?
850 "Conveyance Self-test supported.":
851 "No Conveyance Self-test supported.");
852
853 pout( "\t\t\t\t\t%s\n", isSupportSelectiveSelfTest(data)?
854 "Selective Self-test supported.":
855 "No Selective Self-test supported.");
856 }
857}
858
2127e193 859static void PrintSmartCapability(const ata_smart_values *data)
832b75ed
GG
860{
861 pout("SMART capabilities: ");
862 pout("(0x%04x)\t", (int)data->smart_capability);
863
864 if (data->smart_capability == 0x00)
865 {
866 pout("Automatic saving of SMART data\t\t\t\t\tis not implemented.\n");
867 }
868 else
869 {
870
871 pout( "%s\n", (data->smart_capability & 0x01)?
872 "Saves SMART data before entering\n\t\t\t\t\tpower-saving mode.":
873 "Does not save SMART data before\n\t\t\t\t\tentering power-saving mode.");
874
875 if ( data->smart_capability & 0x02 )
876 {
877 pout("\t\t\t\t\tSupports SMART auto save timer.\n");
878 }
879 }
880}
881
2127e193 882static void PrintSmartErrorLogCapability(const ata_smart_values * data, const ata_identify_device * identity)
832b75ed 883{
832b75ed
GG
884 pout("Error logging capability: ");
885
886 if ( isSmartErrorLogCapable(data, identity) )
887 {
888 pout(" (0x%02x)\tError logging supported.\n",
889 (int)data->errorlog_capability);
890 }
891 else {
892 pout(" (0x%02x)\tError logging NOT supported.\n",
893 (int)data->errorlog_capability);
894 }
895}
896
2127e193
GI
897static void PrintSmartShortSelfTestPollingTime(const ata_smart_values * data)
898{
832b75ed
GG
899 pout("Short self-test routine \n");
900 if (isSupportSelfTest(data))
901 pout("recommended polling time: \t (%4d) minutes.\n",
902 (int)data->short_test_completion_time);
903 else
904 pout("recommended polling time: \t Not Supported.\n");
905}
906
2127e193
GI
907static void PrintSmartExtendedSelfTestPollingTime(const ata_smart_values * data)
908{
832b75ed
GG
909 pout("Extended self-test routine\n");
910 if (isSupportSelfTest(data))
911 pout("recommended polling time: \t (%4d) minutes.\n",
d008864d 912 TestTime(data, EXTEND_SELF_TEST));
832b75ed
GG
913 else
914 pout("recommended polling time: \t Not Supported.\n");
915}
916
2127e193
GI
917static void PrintSmartConveyanceSelfTestPollingTime(const ata_smart_values * data)
918{
832b75ed
GG
919 pout("Conveyance self-test routine\n");
920 if (isSupportConveyanceSelfTest(data))
921 pout("recommended polling time: \t (%4d) minutes.\n",
922 (int)data->conveyance_test_completion_time);
923 else
924 pout("recommended polling time: \t Not Supported.\n");
925}
926
bed94269
GI
927// Check SMART attribute table for Threshold failure
928// onlyfailed=0: are or were any age or prefailure attributes <= threshold
929// onlyfailed=1: are any prefailure attributes <= threshold now
930static int find_failed_attr(const ata_smart_values * data,
931 const ata_smart_thresholds_pvt * thresholds,
932 const ata_vendor_attr_defs & defs, int onlyfailed)
933{
934 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
935 const ata_smart_attribute & attr = data->vendor_attributes[i];
936
cfbba5b9 937 ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs);
bed94269
GI
938
939 if (!onlyfailed) {
940 if (state >= ATTRSTATE_FAILED_PAST)
941 return attr.id;
942 }
943 else {
944 if (state == ATTRSTATE_FAILED_NOW && ATTRIBUTE_FLAGS_PREFAILURE(attr.flags))
945 return attr.id;
946 }
947 }
948 return 0;
949}
950
832b75ed
GG
951// onlyfailed=0 : print all attribute values
952// onlyfailed=1: just ones that are currently failed and have prefailure bit set
953// onlyfailed=2: ones that are failed, or have failed with or without prefailure bit set
2127e193
GI
954static void PrintSmartAttribWithThres(const ata_smart_values * data,
955 const ata_smart_thresholds_pvt * thresholds,
ee38a438 956 const ata_vendor_attr_defs & defs, int rpm,
a7e8ffec 957 int onlyfailed, unsigned char format)
2127e193 958{
e165493d
GI
959 bool brief = !!(format & ata_print_options::FMT_BRIEF);
960 bool hexid = !!(format & ata_print_options::FMT_HEX_ID);
961 bool hexval = !!(format & ata_print_options::FMT_HEX_VAL);
bed94269
GI
962 bool needheader = true;
963
832b75ed 964 // step through all vendor attributes
2127e193 965 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
bed94269 966 const ata_smart_attribute & attr = data->vendor_attributes[i];
832b75ed 967
bed94269 968 // Check attribute and threshold
cfbba5b9
GI
969 unsigned char threshold = 0;
970 ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs, &threshold);
bed94269
GI
971 if (state == ATTRSTATE_NON_EXISTING)
972 continue;
832b75ed 973
bed94269
GI
974 // These break out of the loop if we are only printing certain entries...
975 if (onlyfailed == 1 && !(ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) && state == ATTRSTATE_FAILED_NOW))
976 continue;
832b75ed 977
bed94269
GI
978 if (onlyfailed == 2 && state < ATTRSTATE_FAILED_PAST)
979 continue;
832b75ed 980
bed94269
GI
981 // print header only if needed
982 if (needheader) {
983 if (!onlyfailed) {
984 pout("SMART Attributes Data Structure revision number: %d\n",(int)data->revnumber);
985 pout("Vendor Specific SMART Attributes with Thresholds:\n");
832b75ed 986 }
e165493d
GI
987 if (!brief)
988 pout("ID#%s ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE\n",
989 (!hexid ? "" : " "));
a7e8ffec 990 else
e165493d
GI
991 pout("ID#%s ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE\n",
992 (!hexid ? "" : " "));
bed94269
GI
993 needheader = false;
994 }
995
996 // Format value, worst, threshold
a23d5117 997 std::string valstr, worstr, threstr;
bed94269 998 if (state > ATTRSTATE_NO_NORMVAL)
e165493d
GI
999 valstr = (!hexval ? strprintf("%.3d", attr.current)
1000 : strprintf("0x%02x", attr.current));
bed94269 1001 else
e165493d 1002 valstr = (!hexval ? "---" : "----");
a23d5117 1003 if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL))
e165493d
GI
1004 worstr = (!hexval ? strprintf("%.3d", attr.worst)
1005 : strprintf("0x%02x", attr.worst));
a23d5117 1006 else
e165493d 1007 worstr = (!hexval ? "---" : "----");
bed94269 1008 if (state > ATTRSTATE_NO_THRESHOLD)
e165493d
GI
1009 threstr = (!hexval ? strprintf("%.3d", threshold)
1010 : strprintf("0x%02x", threshold));
bed94269 1011 else
e165493d 1012 threstr = (!hexval ? "---" : "----");
bed94269
GI
1013
1014 // Print line for each valid attribute
e165493d
GI
1015 std::string idstr = (!hexid ? strprintf("%3d", attr.id)
1016 : strprintf("0x%02x", attr.id));
ee38a438 1017 std::string attrname = ata_get_smart_attr_name(attr.id, defs, rpm);
a7e8ffec
GI
1018 std::string rawstr = ata_format_attr_raw_value(attr, defs);
1019
e165493d
GI
1020 if (!brief)
1021 pout("%s %-24s0x%04x %-4s %-4s %-4s %-10s%-9s%-12s%s\n",
1022 idstr.c_str(), attrname.c_str(), attr.flags,
a7e8ffec
GI
1023 valstr.c_str(), worstr.c_str(), threstr.c_str(),
1024 (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? "Pre-fail" : "Old_age"),
1025 (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? "Always" : "Offline"),
1026 (state == ATTRSTATE_FAILED_NOW ? "FAILING_NOW" :
1027 state == ATTRSTATE_FAILED_PAST ? "In_the_past"
1028 : " -" ) ,
1029 rawstr.c_str());
1030 else
e165493d
GI
1031 pout("%s %-24s%c%c%c%c%c%c%c %-4s %-4s %-4s %-5s%s\n",
1032 idstr.c_str(), attrname.c_str(),
a7e8ffec
GI
1033 (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? 'P' : '-'),
1034 (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? 'O' : '-'),
1035 (ATTRIBUTE_FLAGS_PERFORMANCE(attr.flags) ? 'S' : '-'),
1036 (ATTRIBUTE_FLAGS_ERRORRATE(attr.flags) ? 'R' : '-'),
1037 (ATTRIBUTE_FLAGS_EVENTCOUNT(attr.flags) ? 'C' : '-'),
1038 (ATTRIBUTE_FLAGS_SELFPRESERVING(attr.flags) ? 'K' : '-'),
1039 (ATTRIBUTE_FLAGS_OTHER(attr.flags) ? '+' : ' '),
1040 valstr.c_str(), worstr.c_str(), threstr.c_str(),
1041 (state == ATTRSTATE_FAILED_NOW ? "NOW" :
1042 state == ATTRSTATE_FAILED_PAST ? "Past"
1043 : "-" ),
1044 rawstr.c_str());
1045
1046 }
1047
1048 if (!needheader) {
e165493d
GI
1049 if (!onlyfailed && brief) {
1050 int n = (!hexid ? 28 : 29);
1051 pout("%*s||||||_ K auto-keep\n"
1052 "%*s|||||__ C event count\n"
1053 "%*s||||___ R error rate\n"
1054 "%*s|||____ S speed/performance\n"
1055 "%*s||_____ O updated online\n"
1056 "%*s|______ P prefailure warning\n",
1057 n, "", n, "", n, "", n, "", n, "", n, "");
1058 }
a7e8ffec
GI
1059 pout("\n");
1060 }
832b75ed
GG
1061}
1062
a37e7145
GG
1063// Print SMART related SCT capabilities
1064static void ataPrintSCTCapability(const ata_identify_device *drive)
1065{
1066 unsigned short sctcaps = drive->words088_255[206-88];
1067 if (!(sctcaps & 0x01))
1068 return;
1069 pout("SCT capabilities: \t (0x%04x)\tSCT Status supported.\n", sctcaps);
7f0798ef
GI
1070 if (sctcaps & 0x08)
1071 pout("\t\t\t\t\tSCT Error Recovery Control supported.\n");
a37e7145
GG
1072 if (sctcaps & 0x10)
1073 pout("\t\t\t\t\tSCT Feature Control supported.\n");
1074 if (sctcaps & 0x20)
1075 pout("\t\t\t\t\tSCT Data Table supported.\n");
1076}
1077
1078
2127e193 1079static void PrintGeneralSmartValues(const ata_smart_values *data, const ata_identify_device *drive,
ee38a438 1080 firmwarebug_defs firmwarebugs)
2127e193 1081{
832b75ed
GG
1082 pout("General SMART Values:\n");
1083
1084 PrintSmartOfflineStatus(data);
1085
1086 if (isSupportSelfTest(data)){
ee38a438 1087 PrintSmartSelfExecStatus(data, firmwarebugs);
832b75ed
GG
1088 }
1089
1090 PrintSmartTotalTimeCompleteOffline(data);
1091 PrintSmartOfflineCollectCap(data);
1092 PrintSmartCapability(data);
1093
1094 PrintSmartErrorLogCapability(data, drive);
1095
1096 pout( "\t\t\t\t\t%s\n", isGeneralPurposeLoggingCapable(drive)?
1097 "General Purpose Logging supported.":
1098 "No General Purpose Logging support.");
1099
1100 if (isSupportSelfTest(data)){
1101 PrintSmartShortSelfTestPollingTime (data);
1102 PrintSmartExtendedSelfTestPollingTime (data);
1103 }
1104 if (isSupportConveyanceSelfTest(data))
1105 PrintSmartConveyanceSelfTestPollingTime (data);
a37e7145
GG
1106
1107 ataPrintSCTCapability(drive);
1108
832b75ed
GG
1109 pout("\n");
1110}
1111
2127e193
GI
1112// Get # sectors of a log addr, 0 if log does not exist.
1113static unsigned GetNumLogSectors(const ata_smart_log_directory * logdir, unsigned logaddr, bool gpl)
1114{
1115 if (!logdir)
1116 return 0;
1117 if (logaddr > 0xff)
1118 return 0;
1119 if (logaddr == 0)
1120 return 1;
1121 unsigned n = logdir->entry[logaddr-1].numsectors;
1122 if (gpl)
1123 // GP logs may have >255 sectors
1124 n |= logdir->entry[logaddr-1].reserved << 8;
1125 return n;
1126}
832b75ed 1127
2127e193 1128// Get name of log.
ee38a438 1129// Table A.2 of T13/2161-D (ACS-3) Revision 4, September 4, 2012
2127e193
GI
1130static const char * GetLogName(unsigned logaddr)
1131{
1132 switch (logaddr) {
1133 case 0x00: return "Log Directory";
1134 case 0x01: return "Summary SMART error log";
1135 case 0x02: return "Comprehensive SMART error log";
1136 case 0x03: return "Ext. Comprehensive SMART error log";
d008864d 1137 case 0x04: return "Device Statistics log";
ee38a438 1138 case 0x05: return "Reserved for CFA"; // ACS-2
2127e193
GI
1139 case 0x06: return "SMART self-test log";
1140 case 0x07: return "Extended self-test log";
d008864d 1141 case 0x08: return "Power Conditions log"; // ACS-2
2127e193 1142 case 0x09: return "Selective self-test log";
ee38a438
GI
1143 case 0x0a: return "Device Statistics Notification"; // ACS-3
1144 case 0x0b: return "Reserved for CFA"; // ACS-3
d2e702cf 1145 case 0x0c: return "Pending Defects log"; // ACS-4
cfbba5b9 1146 case 0x0d: return "LPS Mis-alignment log"; // ACS-2
ee38a438 1147
d008864d 1148 case 0x10: return "NCQ Command Error log";
2127e193 1149 case 0x11: return "SATA Phy Event Counters";
e165493d
GI
1150 case 0x12: return "SATA NCQ Queue Management log"; // ACS-3
1151 case 0x13: return "SATA NCQ Send and Receive log"; // ACS-3
1152 case 0x14:
1153 case 0x15:
d2e702cf
GI
1154 case 0x16:
1155 case 0x17: return "Reserved for Serial ATA";
ee38a438 1156
d008864d 1157 case 0x19: return "LBA Status log"; // ACS-3
ee38a438
GI
1158
1159 case 0x20: return "Streaming performance log [OBS-8]";
2127e193
GI
1160 case 0x21: return "Write stream error log";
1161 case 0x22: return "Read stream error log";
ee38a438 1162 case 0x23: return "Delayed sector log [OBS-8]";
e165493d
GI
1163 case 0x24: return "Current Device Internal Status Data log"; // ACS-3
1164 case 0x25: return "Saved Device Internal Status Data log"; // ACS-3
ee38a438 1165
d008864d 1166 case 0x30: return "IDENTIFY DEVICE data log"; // ACS-3
ee38a438 1167
2127e193
GI
1168 case 0xe0: return "SCT Command/Status";
1169 case 0xe1: return "SCT Data Transfer";
832b75ed 1170 default:
2127e193
GI
1171 if (0xa0 <= logaddr && logaddr <= 0xdf)
1172 return "Device vendor specific log";
1173 if (0x80 <= logaddr && logaddr <= 0x9f)
1174 return "Host vendor specific log";
2127e193
GI
1175 return "Reserved";
1176 }
1177 /*NOTREACHED*/
1178}
832b75ed 1179
ee38a438
GI
1180// Get log access permissions
1181static const char * get_log_rw(unsigned logaddr)
1182{
1183 if ( ( logaddr <= 0x08)
d2e702cf 1184 || (0x0c <= logaddr && logaddr <= 0x0d)
ee38a438
GI
1185 || (0x10 <= logaddr && logaddr <= 0x13)
1186 || (0x19 == logaddr)
1187 || (0x20 <= logaddr && logaddr <= 0x25)
1188 || (0x30 == logaddr))
1189 return "R/O";
1190
1191 if ( (0x09 <= logaddr && logaddr <= 0x0a)
1192 || (0x80 <= logaddr && logaddr <= 0x9f)
1193 || (0xe0 <= logaddr && logaddr <= 0xe1))
1194 return "R/W";
1195
1196 if (0xa0 <= logaddr && logaddr <= 0xdf)
1197 return "VS"; // Vendor specific
1198
1199 return "-"; // Unknown/Reserved
1200}
1201
1202// Init a fake log directory, assume that standard logs are supported
1203const ata_smart_log_directory * fake_logdir(ata_smart_log_directory * logdir,
1204 const ata_print_options & options)
1205{
1206 memset(logdir, 0, sizeof(*logdir));
1207 logdir->logversion = 255;
1208 logdir->entry[0x01-1].numsectors = 1;
1209 logdir->entry[0x03-1].numsectors = (options.smart_ext_error_log + (4-1)) / 4;
1210 logdir->entry[0x04-1].numsectors = 8;
1211 logdir->entry[0x06-1].numsectors = 1;
1212 logdir->entry[0x07-1].numsectors = (options.smart_ext_selftest_log + (19-1)) / 19;
1213 logdir->entry[0x09-1].numsectors = 1;
1214 logdir->entry[0x11-1].numsectors = 1;
1215 return logdir;
1216}
1217
2127e193
GI
1218// Print SMART and/or GP Log Directory
1219static void PrintLogDirectories(const ata_smart_log_directory * gplogdir,
1220 const ata_smart_log_directory * smartlogdir)
1221{
1222 if (gplogdir)
1223 pout("General Purpose Log Directory Version %u\n", gplogdir->logversion);
1224 if (smartlogdir)
1225 pout("SMART %sLog Directory Version %u%s\n",
1226 (gplogdir ? " " : ""), smartlogdir->logversion,
1227 (smartlogdir->logversion==1 ? " [multi-sector log support]" : ""));
1228
ee38a438
GI
1229 pout("Address Access R/W Size Description\n");
1230
2127e193
GI
1231 for (unsigned i = 0; i <= 0xff; i++) {
1232 // Get number of sectors
1233 unsigned smart_numsect = GetNumLogSectors(smartlogdir, i, false);
1234 unsigned gp_numsect = GetNumLogSectors(gplogdir , i, true );
1235
1236 if (!(smart_numsect || gp_numsect))
1237 continue; // Log does not exist
1238
ee38a438
GI
1239 const char * acc; unsigned size;
1240 if (smart_numsect == gp_numsect) {
1241 acc = "GPL,SL"; size = gp_numsect;
1242 }
1243 else if (!smart_numsect) {
1244 acc = "GPL"; size = gp_numsect;
1245 }
1246 else if (!gp_numsect) {
1247 acc = " SL"; size = smart_numsect;
1248 }
1249 else {
1250 acc = 0; size = 0;
1251 }
1252
1253 unsigned i2 = i;
1254 if (acc && ((0x80 <= i && i < 0x9f) || (0xa0 <= i && i < 0xdf))) {
1255 // Find range of Host/Device vendor specific logs with same size
1256 unsigned imax = (i < 0x9f ? 0x9f : 0xdf);
1257 for (unsigned j = i+1; j <= imax; j++) {
1258 unsigned sn = GetNumLogSectors(smartlogdir, j, false);
1259 unsigned gn = GetNumLogSectors(gplogdir , j, true );
1260
1261 if (!(sn == smart_numsect && gn == gp_numsect))
1262 break;
1263 i2 = j;
1264 }
1265 }
1266
2127e193 1267 const char * name = GetLogName(i);
ee38a438 1268 const char * rw = get_log_rw(i);
2127e193 1269
ee38a438
GI
1270 if (i2 > i) {
1271 pout("0x%02x-0x%02x %-6s %-3s %5u %s\n", i, i2, acc, rw, size, name);
1272 i = i2;
1273 }
1274 else if (acc)
1275 pout( "0x%02x %-6s %-3s %5u %s\n", i, acc, rw, size, name);
2127e193 1276 else {
ee38a438
GI
1277 // GPL and SL support different sizes
1278 pout( "0x%02x %-6s %-3s %5u %s\n", i, "GPL", rw, gp_numsect, name);
1279 pout( "0x%02x %-6s %-3s %5u %s\n", i, "SL", rw, smart_numsect, name);
832b75ed
GG
1280 }
1281 }
2127e193 1282 pout("\n");
832b75ed
GG
1283}
1284
2127e193
GI
1285// Print hexdump of log pages.
1286// Format is compatible with 'xxd -r'.
1287static void PrintLogPages(const char * type, const unsigned char * data,
1288 unsigned char logaddr, unsigned page,
1289 unsigned num_pages, unsigned max_pages)
1290{
1291 pout("%s Log 0x%02x [%s], Page %u-%u (of %u)\n",
1292 type, logaddr, GetLogName(logaddr), page, page+num_pages-1, max_pages);
1293 for (unsigned i = 0; i < num_pages * 512; i += 16) {
1294 const unsigned char * p = data+i;
1295 pout("%07x: %02x %02x %02x %02x %02x %02x %02x %02x "
a23d5117 1296 "%02x %02x %02x %02x %02x %02x %02x %02x ",
2127e193
GI
1297 (page * 512) + i,
1298 p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
1299 p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15]);
d008864d 1300#define P(n) (' ' <= p[n] && p[n] <= '~' ? (int)p[n] : '.')
a23d5117
GI
1301 pout("|%c%c%c%c%c%c%c%c"
1302 "%c%c%c%c%c%c%c%c|\n",
1303 P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
1304 P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15));
1305#undef P
2127e193
GI
1306 if ((i & 0x1ff) == 0x1f0)
1307 pout("\n");
1308 }
1309}
1310
d008864d
GI
1311///////////////////////////////////////////////////////////////////////
1312// Device statistics (Log 0x04)
1313
1314// See Section A.5 of
1315// ATA/ATAPI Command Set - 3 (ACS-3)
e165493d 1316// T13/2161-D Revision 2, February 21, 2012.
d008864d
GI
1317
1318struct devstat_entry_info
1319{
1320 short size; // #bytes of value, -1 for signed char
1321 const char * name;
1322};
1323
1324const devstat_entry_info devstat_info_0x00[] = {
1325 { 2, "List of supported log pages" },
1326 { 0, 0 }
1327};
1328
1329const devstat_entry_info devstat_info_0x01[] = {
1330 { 2, "General Statistics" },
1331 { 4, "Lifetime Power-On Resets" },
1332 { 4, "Power-on Hours" }, // spec says no flags(?)
1333 { 6, "Logical Sectors Written" },
1334 { 6, "Number of Write Commands" },
1335 { 6, "Logical Sectors Read" },
1336 { 6, "Number of Read Commands" },
e165493d 1337 { 6, "Date and Time TimeStamp" }, // ACS-3
d008864d
GI
1338 { 0, 0 }
1339};
1340
1341const devstat_entry_info devstat_info_0x02[] = {
e165493d 1342 { 2, "Free-Fall Statistics" },
d008864d
GI
1343 { 4, "Number of Free-Fall Events Detected" },
1344 { 4, "Overlimit Shock Events" },
1345 { 0, 0 }
1346};
1347
1348const devstat_entry_info devstat_info_0x03[] = {
1349 { 2, "Rotating Media Statistics" },
1350 { 4, "Spindle Motor Power-on Hours" },
1351 { 4, "Head Flying Hours" },
1352 { 4, "Head Load Events" },
1353 { 4, "Number of Reallocated Logical Sectors" },
1354 { 4, "Read Recovery Attempts" },
1355 { 4, "Number of Mechanical Start Failures" },
1356 { 4, "Number of Realloc. Candidate Logical Sectors" }, // ACS-3
1357 { 0, 0 }
1358};
1359
1360const devstat_entry_info devstat_info_0x04[] = {
1361 { 2, "General Errors Statistics" },
1362 { 4, "Number of Reported Uncorrectable Errors" },
1363//{ 4, "Number of Resets Between Command Acceptance and Command Completion" },
1364 { 4, "Resets Between Cmd Acceptance and Completion" },
1365 { 0, 0 }
1366};
1367
1368const devstat_entry_info devstat_info_0x05[] = {
1369 { 2, "Temperature Statistics" },
1370 { -1, "Current Temperature" },
1371 { -1, "Average Short Term Temperature" },
1372 { -1, "Average Long Term Temperature" },
1373 { -1, "Highest Temperature" },
1374 { -1, "Lowest Temperature" },
1375 { -1, "Highest Average Short Term Temperature" },
1376 { -1, "Lowest Average Short Term Temperature" },
1377 { -1, "Highest Average Long Term Temperature" },
1378 { -1, "Lowest Average Long Term Temperature" },
1379 { 4, "Time in Over-Temperature" },
1380 { -1, "Specified Maximum Operating Temperature" },
1381 { 4, "Time in Under-Temperature" },
1382 { -1, "Specified Minimum Operating Temperature" },
1383 { 0, 0 }
1384};
1385
1386const devstat_entry_info devstat_info_0x06[] = {
1387 { 2, "Transport Statistics" },
1388 { 4, "Number of Hardware Resets" },
1389 { 4, "Number of ASR Events" },
1390 { 4, "Number of Interface CRC Errors" },
1391 { 0, 0 }
1392};
1393
1394const devstat_entry_info devstat_info_0x07[] = {
1395 { 2, "Solid State Device Statistics" },
1396 { 1, "Percentage Used Endurance Indicator" },
1397 { 0, 0 }
1398};
1399
1400const devstat_entry_info * devstat_infos[] = {
1401 devstat_info_0x00,
1402 devstat_info_0x01,
1403 devstat_info_0x02,
1404 devstat_info_0x03,
1405 devstat_info_0x04,
1406 devstat_info_0x05,
1407 devstat_info_0x06,
1408 devstat_info_0x07
1409};
1410
1411const int num_devstat_infos = sizeof(devstat_infos)/sizeof(devstat_infos[0]);
1412
1413static void print_device_statistics_page(const unsigned char * data, int page,
1414 bool & need_trailer)
1415{
1416 const devstat_entry_info * info = (page < num_devstat_infos ? devstat_infos[page] : 0);
1417 const char * name = (info ? info[0].name : "Unknown Statistics");
1418
1419 // Check page number in header
1420 static const char line[] = " ===== = = == ";
1421 if (!data[2]) {
1422 pout("%3d%s%s (empty) ==\n", page, line, name);
1423 return;
1424 }
1425 if (data[2] != page) {
1426 pout("%3d%s%s (invalid page %d in header) ==\n", page, line, name, data[2]);
1427 return;
1428 }
1429
1430 pout("%3d%s%s (rev %d) ==\n", page, line, name, data[0]);
1431
1432 // Print entries
1433 for (int i = 1, offset = 8; offset < 512-7; i++, offset+=8) {
1434 // Check for last known entry
1435 if (info && !info[i].size)
1436 info = 0;
1437
1438 // Skip unsupported entries
1439 unsigned char flags = data[offset+7];
1440 if (!(flags & 0x80))
1441 continue;
1442
d2e702cf
GI
1443 // Stop if unknown entries contain garbage data due to buggy firmware
1444 if (!info && (data[offset+5] || data[offset+6])) {
1445 pout("%3d 0x%03x - - [Trailing garbage ignored]\n", page, offset);
1446 break;
1447 }
1448
d008864d
GI
1449 // Get value size, default to max if unknown
1450 int size = (info ? info[i].size : 7);
1451
1452 // Format value
1453 char valstr[32];
1454 if (flags & 0x40) { // valid flag
1455 // Get value
1456 int64_t val;
1457 if (size < 0) {
1458 val = (signed char)data[offset];
1459 }
1460 else {
1461 val = 0;
1462 for (int j = 0; j < size; j++)
1463 val |= (int64_t)data[offset+j] << (j*8);
1464 }
d2e702cf 1465 snprintf(valstr, sizeof(valstr), "%" PRId64, val);
d008864d
GI
1466 }
1467 else {
1468 // Value not known (yet)
ee38a438 1469 valstr[0] = '-'; valstr[1] = 0;
d008864d
GI
1470 }
1471
1472 pout("%3d 0x%03x %d%c %15s%c %s\n",
1473 page, offset,
1474 abs(size),
1475 (flags & 0x1f ? '+' : ' '), // unknown flags
1476 valstr,
1477 (flags & 0x20 ? '~' : ' '), // normalized flag
1478 (info ? info[i].name : "Unknown"));
1479 if (flags & 0x20)
1480 need_trailer = true;
1481 }
1482}
1483
1484static bool print_device_statistics(ata_device * device, unsigned nsectors,
d2e702cf
GI
1485 const std::vector<int> & single_pages, bool all_pages, bool ssd_page,
1486 bool use_gplog)
d008864d
GI
1487{
1488 // Read list of supported pages from page 0
1489 unsigned char page_0[512] = {0, };
d2e702cf
GI
1490 int rc;
1491
1492 if (use_gplog)
1493 rc = ataReadLogExt(device, 0x04, 0, 0, page_0, 1);
1494 else
1495 rc = ataReadSmartLog(device, 0x04, page_0, 1);
1496 if (!rc) {
ee38a438 1497 pout("Read Device Statistics page 0 failed\n\n");
d008864d 1498 return false;
ee38a438 1499 }
d008864d
GI
1500
1501 unsigned char nentries = page_0[8];
1502 if (!(page_0[2] == 0 && nentries > 0)) {
ee38a438 1503 pout("Device Statistics page 0 is invalid (page=%d, nentries=%d)\n\n", page_0[2], nentries);
d008864d
GI
1504 return false;
1505 }
1506
1507 // Prepare list of pages to print
1508 std::vector<int> pages;
1509 unsigned i;
1510 if (all_pages) {
1511 // Add all supported pages
1512 for (i = 0; i < nentries; i++) {
1513 int page = page_0[8+1+i];
1514 if (page)
1515 pages.push_back(page);
1516 }
1517 ssd_page = false;
1518 }
1519 // Add manually specified pages
1520 bool print_page_0 = false;
1521 for (i = 0; i < single_pages.size() || ssd_page; i++) {
1522 int page = (i < single_pages.size() ? single_pages[i] : 7);
1523 if (!page)
1524 print_page_0 = true;
1525 else if (page >= (int)nsectors)
1526 pout("Device Statistics Log has only %u pages\n", nsectors);
1527 else
1528 pages.push_back(page);
1529 if (page == 7)
1530 ssd_page = false;
1531 }
1532
1533 // Print list of supported pages if requested
1534 if (print_page_0) {
d2e702cf
GI
1535 pout("Device Statistics (%s Log 0x04) supported pages\n",
1536 use_gplog ? "GP" : "SMART");
d008864d
GI
1537 pout("Page Description\n");
1538 for (i = 0; i < nentries; i++) {
1539 int page = page_0[8+1+i];
1540 pout("%3d %s\n", page,
1541 (page < num_devstat_infos ? devstat_infos[page][0].name : "Unknown Statistics"));
1542 }
1543 pout("\n");
1544 }
1545
1546 // Read & print pages
1547 if (!pages.empty()) {
d2e702cf
GI
1548 pout("Device Statistics (%s Log 0x04)\n",
1549 use_gplog ? "GP" : "SMART");
d008864d
GI
1550 pout("Page Offset Size Value Description\n");
1551 bool need_trailer = false;
d2e702cf
GI
1552 int max_page = 0;
1553
1554 if (!use_gplog)
1555 for (i = 0; i < pages.size(); i++) {
1556 int page = pages[i];
1557 if (max_page < page && page < 0xff)
1558 max_page = page;
1559 }
1560
1561 raw_buffer pages_buf((max_page+1) * 512);
1562
1563 if (!use_gplog && !ataReadSmartLog(device, 0x04, pages_buf.data(), max_page+1)) {
1564 pout("Read Device Statistics pages 0-%d failed\n\n", max_page);
1565 return false;
1566 }
d008864d
GI
1567
1568 for (i = 0; i < pages.size(); i++) {
1569 int page = pages[i];
d2e702cf 1570 if (use_gplog && !ataReadLogExt(device, 0x04, 0, page, pages_buf.data(), 1)) {
ee38a438 1571 pout("Read Device Statistics page %d failed\n\n", page);
d008864d 1572 return false;
ee38a438 1573 }
d2e702cf
GI
1574
1575 int offset = (use_gplog ? 0 : page * 512);
1576 print_device_statistics_page(pages_buf.data() + offset, page, need_trailer);
d008864d
GI
1577 }
1578
1579 if (need_trailer)
1580 pout("%30s|_ ~ normalized value\n", "");
1581 pout("\n");
1582 }
1583
1584 return true;
1585}
1586
1587
1588///////////////////////////////////////////////////////////////////////
1589
2127e193
GI
1590// Print log 0x11
1591static void PrintSataPhyEventCounters(const unsigned char * data, bool reset)
1592{
1593 if (checksum(data))
1594 checksumwarning("SATA Phy Event Counters");
1595 pout("SATA Phy Event Counters (GP Log 0x11)\n");
1596 if (data[0] || data[1] || data[2] || data[3])
1597 pout("[Reserved: 0x%02x 0x%02x 0x%02x 0x%02x]\n",
1598 data[0], data[1], data[2], data[3]);
1599 pout("ID Size Value Description\n");
1600
1601 for (unsigned i = 4; ; ) {
1602 // Get counter id and size (bits 14:12)
1603 unsigned id = data[i] | (data[i+1] << 8);
1604 unsigned size = ((id >> 12) & 0x7) << 1;
1605 id &= 0x8fff;
1606
1607 // End of counter table ?
1608 if (!id)
1609 break;
1610 i += 2;
832b75ed 1611
2127e193
GI
1612 if (!(2 <= size && size <= 8 && i + size < 512)) {
1613 pout("0x%04x %u: Invalid entry\n", id, size);
1614 break;
1615 }
1616
1617 // Get value
1618 uint64_t val = 0, max_val = 0;
1619 for (unsigned j = 0; j < size; j+=2) {
1620 val |= (uint64_t)(data[i+j] | (data[i+j+1] << 8)) << (j*8);
1621 max_val |= (uint64_t)0xffffU << (j*8);
1622 }
1623 i += size;
1624
1625 // Get name
1626 const char * name;
1627 switch (id) {
1628 case 0x001: name = "Command failed due to ICRC error"; break; // Mandatory
1629 case 0x002: name = "R_ERR response for data FIS"; break;
1630 case 0x003: name = "R_ERR response for device-to-host data FIS"; break;
1631 case 0x004: name = "R_ERR response for host-to-device data FIS"; break;
1632 case 0x005: name = "R_ERR response for non-data FIS"; break;
1633 case 0x006: name = "R_ERR response for device-to-host non-data FIS"; break;
1634 case 0x007: name = "R_ERR response for host-to-device non-data FIS"; break;
1635 case 0x008: name = "Device-to-host non-data FIS retries"; break;
1636 case 0x009: name = "Transition from drive PhyRdy to drive PhyNRdy"; break;
1637 case 0x00A: name = "Device-to-host register FISes sent due to a COMRESET"; break; // Mandatory
1638 case 0x00B: name = "CRC errors within host-to-device FIS"; break;
1639 case 0x00D: name = "Non-CRC errors within host-to-device FIS"; break;
1640 case 0x00F: name = "R_ERR response for host-to-device data FIS, CRC"; break;
1641 case 0x010: name = "R_ERR response for host-to-device data FIS, non-CRC"; break;
1642 case 0x012: name = "R_ERR response for host-to-device non-data FIS, CRC"; break;
1643 case 0x013: name = "R_ERR response for host-to-device non-data FIS, non-CRC"; break;
1644 default: name = (id & 0x8000 ? "Vendor specific" : "Unknown"); break;
1645 }
1646
1647 // Counters stop at max value, add '+' in this case
d2e702cf 1648 pout("0x%04x %u %12" PRIu64 "%c %s\n", id, size, val,
2127e193
GI
1649 (val == max_val ? '+' : ' '), name);
1650 }
1651 if (reset)
1652 pout("All counters reset\n");
1653 pout("\n");
1654}
1655
ee38a438
GI
1656// Format milliseconds from error log entry as "DAYS+H:M:S.MSEC"
1657static std::string format_milliseconds(unsigned msec)
1658{
1659 unsigned days = msec / 86400000U;
1660 msec -= days * 86400000U;
1661 unsigned hours = msec / 3600000U;
1662 msec -= hours * 3600000U;
1663 unsigned min = msec / 60000U;
1664 msec -= min * 60000U;
1665 unsigned sec = msec / 1000U;
1666 msec -= sec * 1000U;
1667
1668 std::string str;
1669 if (days)
1670 str = strprintf("%2ud+", days);
1671 str += strprintf("%02u:%02u:%02u.%03u", hours, min, sec, msec);
1672 return str;
1673}
1674
2127e193
GI
1675// Get description for 'state' value from SMART Error Logs
1676static const char * get_error_log_state_desc(unsigned state)
1677{
1678 state &= 0x0f;
1679 switch (state){
1680 case 0x0: return "in an unknown state";
1681 case 0x1: return "sleeping";
1682 case 0x2: return "in standby mode";
1683 case 0x3: return "active or idle";
1684 case 0x4: return "doing SMART Offline or Self-test";
1685 default:
1686 return (state < 0xb ? "in a reserved state"
1687 : "in a vendor specific state");
1688 }
1689}
1690
1691// returns number of errors
1692static int PrintSmartErrorlog(const ata_smart_errorlog *data,
ee38a438 1693 firmwarebug_defs firmwarebugs)
2127e193 1694{
832b75ed
GG
1695 pout("SMART Error Log Version: %d\n", (int)data->revnumber);
1696
1697 // if no errors logged, return
1698 if (!data->error_log_pointer){
1699 pout("No Errors Logged\n\n");
1700 return 0;
1701 }
cfbba5b9 1702 print_on();
832b75ed
GG
1703 // If log pointer out of range, return
1704 if (data->error_log_pointer>5){
1705 pout("Invalid Error Log index = 0x%02x (T13/1321D rev 1c "
1706 "Section 8.41.6.8.2.2 gives valid range from 1 to 5)\n\n",
1707 (int)data->error_log_pointer);
1708 return 0;
1709 }
1710
1711 // Some internal consistency checking of the data structures
ee38a438 1712 if ((data->ata_error_count-data->error_log_pointer) % 5 && !firmwarebugs.is_set(BUG_SAMSUNG2)) {
832b75ed
GG
1713 pout("Warning: ATA error count %d inconsistent with error log pointer %d\n\n",
1714 data->ata_error_count,data->error_log_pointer);
1715 }
1716
1717 // starting printing error log info
1718 if (data->ata_error_count<=5)
1719 pout( "ATA Error Count: %d\n", (int)data->ata_error_count);
1720 else
1721 pout( "ATA Error Count: %d (device log contains only the most recent five errors)\n",
1722 (int)data->ata_error_count);
cfbba5b9 1723 print_off();
832b75ed
GG
1724 pout("\tCR = Command Register [HEX]\n"
1725 "\tFR = Features Register [HEX]\n"
1726 "\tSC = Sector Count Register [HEX]\n"
1727 "\tSN = Sector Number Register [HEX]\n"
1728 "\tCL = Cylinder Low Register [HEX]\n"
1729 "\tCH = Cylinder High Register [HEX]\n"
1730 "\tDH = Device/Head Register [HEX]\n"
1731 "\tDC = Device Command Register [HEX]\n"
1732 "\tER = Error register [HEX]\n"
1733 "\tST = Status register [HEX]\n"
1734 "Powered_Up_Time is measured from power on, and printed as\n"
1735 "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
1736 "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
1737
1738 // now step through the five error log data structures (table 39 of spec)
2127e193 1739 for (int k = 4; k >= 0; k-- ) {
832b75ed
GG
1740
1741 // The error log data structure entries are a circular buffer
1742 int j, i=(data->error_log_pointer+k)%5;
2127e193
GI
1743 const ata_smart_errorlog_struct * elog = data->errorlog_struct+i;
1744 const ata_smart_errorlog_error_struct * summary = &(elog->error_struct);
832b75ed
GG
1745
1746 // Spec says: unused error log structures shall be zero filled
a23d5117 1747 if (nonempty(elog, sizeof(*elog))){
832b75ed 1748 // Table 57 of T13/1532D Volume 1 Revision 3
2127e193 1749 const char *msgstate = get_error_log_state_desc(summary->state);
832b75ed
GG
1750 int days = (int)summary->timestamp/24;
1751
832b75ed 1752 // See table 42 of ATA5 spec
cfbba5b9 1753 print_on();
832b75ed
GG
1754 pout("Error %d occurred at disk power-on lifetime: %d hours (%d days + %d hours)\n",
1755 (int)(data->ata_error_count+k-4), (int)summary->timestamp, days, (int)(summary->timestamp-24*days));
cfbba5b9 1756 print_off();
832b75ed
GG
1757 pout(" When the command that caused the error occurred, the device was %s.\n\n",msgstate);
1758 pout(" After command completion occurred, registers were:\n"
1759 " ER ST SC SN CL CH DH\n"
1760 " -- -- -- -- -- -- --\n"
1761 " %02x %02x %02x %02x %02x %02x %02x",
1762 (int)summary->error_register,
1763 (int)summary->status,
1764 (int)summary->sector_count,
1765 (int)summary->sector_number,
1766 (int)summary->cylinder_low,
1767 (int)summary->cylinder_high,
1768 (int)summary->drive_head);
1769 // Add a description of the contents of the status and error registers
1770 // if possible
ee38a438
GI
1771 std::string st_er_desc = format_st_er_desc(elog);
1772 if (!st_er_desc.empty())
1773 pout(" %s", st_er_desc.c_str());
832b75ed
GG
1774 pout("\n\n");
1775 pout(" Commands leading to the command that caused the error were:\n"
1776 " CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name\n"
1777 " -- -- -- -- -- -- -- -- ---------------- --------------------\n");
1778 for ( j = 4; j >= 0; j--){
2127e193 1779 const ata_smart_errorlog_command_struct * thiscommand = elog->commands+j;
832b75ed
GG
1780
1781 // Spec says: unused data command structures shall be zero filled
a23d5117 1782 if (nonempty(thiscommand, sizeof(*thiscommand))) {
832b75ed
GG
1783 pout(" %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
1784 (int)thiscommand->commandreg,
1785 (int)thiscommand->featuresreg,
1786 (int)thiscommand->sector_count,
1787 (int)thiscommand->sector_number,
1788 (int)thiscommand->cylinder_low,
1789 (int)thiscommand->cylinder_high,
1790 (int)thiscommand->drive_head,
1791 (int)thiscommand->devicecontrolreg,
ee38a438 1792 format_milliseconds(thiscommand->timestamp).c_str(),
832b75ed
GG
1793 look_up_ata_command(thiscommand->commandreg, thiscommand->featuresreg));
1794 }
1795 }
1796 pout("\n");
1797 }
1798 }
cfbba5b9
GI
1799 print_on();
1800 if (printing_is_switchable)
832b75ed 1801 pout("\n");
cfbba5b9 1802 print_off();
832b75ed
GG
1803 return data->ata_error_count;
1804}
1805
2127e193
GI
1806// Print SMART Extended Comprehensive Error Log (GP Log 0x03)
1807static int PrintSmartExtErrorLog(const ata_smart_exterrlog * log,
1808 unsigned nsectors, unsigned max_errors)
1809{
1810 pout("SMART Extended Comprehensive Error Log Version: %u (%u sectors)\n",
1811 log->version, nsectors);
1812
1813 if (!log->device_error_count) {
1814 pout("No Errors Logged\n\n");
1815 return 0;
1816 }
cfbba5b9 1817 print_on();
2127e193
GI
1818
1819 // Check index
1820 unsigned nentries = nsectors * 4;
1821 unsigned erridx = log->error_log_index;
1822 if (!(1 <= erridx && erridx <= nentries)){
1823 // Some Samsung disks (at least SP1614C/SW100-25, HD300LJ/ZT100-12) use the
1824 // former index from Summary Error Log (byte 1, now reserved) and set byte 2-3
1825 // to 0.
1826 if (!(erridx == 0 && 1 <= log->reserved1 && log->reserved1 <= nentries)) {
1827 pout("Invalid Error Log index = 0x%04x (reserved = 0x%02x)\n", erridx, log->reserved1);
1828 return 0;
1829 }
1830 pout("Invalid Error Log index = 0x%04x, trying reserved byte (0x%02x) instead\n", erridx, log->reserved1);
1831 erridx = log->reserved1;
1832 }
1833
1834 // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
1835 // it is 1-based in practice.
1836 erridx--;
1837
1838 // Calculate #errors to print
1839 unsigned errcnt = log->device_error_count;
1840
1841 if (errcnt <= nentries)
1842 pout("Device Error Count: %u\n", log->device_error_count);
1843 else {
1844 errcnt = nentries;
1845 pout("Device Error Count: %u (device log contains only the most recent %u errors)\n",
1846 log->device_error_count, errcnt);
1847 }
1848
1849 if (max_errors < errcnt)
1850 errcnt = max_errors;
1851
cfbba5b9 1852 print_off();
2127e193
GI
1853 pout("\tCR = Command Register\n"
1854 "\tFEATR = Features Register\n"
1855 "\tCOUNT = Count (was: Sector Count) Register\n"
1856 "\tLBA_48 = Upper bytes of LBA High/Mid/Low Registers ] ATA-8\n"
1857 "\tLH = LBA High (was: Cylinder High) Register ] LBA\n"
1858 "\tLM = LBA Mid (was: Cylinder Low) Register ] Register\n"
1859 "\tLL = LBA Low (was: Sector Number) Register ]\n"
1860 "\tDV = Device (was: Device/Head) Register\n"
1861 "\tDC = Device Control Register\n"
1862 "\tER = Error register\n"
1863 "\tST = Status register\n"
1864 "Powered_Up_Time is measured from power on, and printed as\n"
1865 "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
1866 "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
1867
1868 // Iterate through circular buffer in reverse direction
1869 for (unsigned i = 0, errnum = log->device_error_count;
1870 i < errcnt; i++, errnum--, erridx = (erridx > 0 ? erridx - 1 : nentries - 1)) {
1871
1872 const ata_smart_exterrlog_error_log & entry = log[erridx / 4].error_logs[erridx % 4];
1873
1874 // Skip unused entries
1875 if (!nonempty(&entry, sizeof(entry))) {
1876 pout("Error %u [%u] log entry is empty\n", errnum, erridx);
1877 continue;
1878 }
1879
1880 // Print error information
cfbba5b9 1881 print_on();
2127e193
GI
1882 const ata_smart_exterrlog_error & err = entry.error;
1883 pout("Error %u [%u] occurred at disk power-on lifetime: %u hours (%u days + %u hours)\n",
1884 errnum, erridx, err.timestamp, err.timestamp / 24, err.timestamp % 24);
cfbba5b9 1885 print_off();
2127e193
GI
1886
1887 pout(" When the command that caused the error occurred, the device was %s.\n\n",
1888 get_error_log_state_desc(err.state));
1889
1890 // Print registers
1891 pout(" After command completion occurred, registers were:\n"
1892 " ER -- ST COUNT LBA_48 LH LM LL DV DC\n"
1893 " -- -- -- == -- == == == -- -- -- -- --\n"
1894 " %02x -- %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
1895 err.error_register,
1896 err.status_register,
1897 err.count_register_hi,
1898 err.count_register,
1899 err.lba_high_register_hi,
1900 err.lba_mid_register_hi,
1901 err.lba_low_register_hi,
1902 err.lba_high_register,
1903 err.lba_mid_register,
1904 err.lba_low_register,
1905 err.device_register,
1906 err.device_control_register);
1907
1908 // Add a description of the contents of the status and error registers
1909 // if possible
ee38a438
GI
1910 std::string st_er_desc = format_st_er_desc(&entry);
1911 if (!st_er_desc.empty())
1912 pout(" %s", st_er_desc.c_str());
2127e193
GI
1913 pout("\n\n");
1914
1915 // Print command history
1916 pout(" Commands leading to the command that caused the error were:\n"
1917 " CR FEATR COUNT LBA_48 LH LM LL DV DC Powered_Up_Time Command/Feature_Name\n"
1918 " -- == -- == -- == == == -- -- -- -- -- --------------- --------------------\n");
1919 for (int ci = 4; ci >= 0; ci--) {
1920 const ata_smart_exterrlog_command & cmd = entry.commands[ci];
1921
1922 // Skip unused entries
1923 if (!nonempty(&cmd, sizeof(cmd)))
1924 continue;
1925
1926 // Print registers, timestamp and ATA command name
2127e193
GI
1927 pout(" %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
1928 cmd.command_register,
1929 cmd.features_register_hi,
1930 cmd.features_register,
1931 cmd.count_register_hi,
1932 cmd.count_register,
1933 cmd.lba_high_register_hi,
1934 cmd.lba_mid_register_hi,
1935 cmd.lba_low_register_hi,
1936 cmd.lba_high_register,
1937 cmd.lba_mid_register,
1938 cmd.lba_low_register,
1939 cmd.device_register,
1940 cmd.device_control_register,
ee38a438 1941 format_milliseconds(cmd.timestamp).c_str(),
2127e193
GI
1942 look_up_ata_command(cmd.command_register, cmd.features_register));
1943 }
1944 pout("\n");
1945 }
1946
cfbba5b9
GI
1947 print_on();
1948 if (printing_is_switchable)
2127e193 1949 pout("\n");
cfbba5b9 1950 print_off();
2127e193
GI
1951 return log->device_error_count;
1952}
1953
1954// Print SMART Extended Self-test Log (GP Log 0x07)
cfbba5b9
GI
1955static int PrintSmartExtSelfTestLog(const ata_smart_extselftestlog * log,
1956 unsigned nsectors, unsigned max_entries)
2127e193
GI
1957{
1958 pout("SMART Extended Self-test Log Version: %u (%u sectors)\n",
1959 log->version, nsectors);
1960
1961 if (!log->log_desc_index){
1962 pout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n\n");
cfbba5b9 1963 return 0;
2127e193
GI
1964 }
1965
1966 // Check index
1967 unsigned nentries = nsectors * 19;
1968 unsigned logidx = log->log_desc_index;
1969 if (logidx > nentries) {
1970 pout("Invalid Self-test Log index = 0x%04x (reserved = 0x%02x)\n", logidx, log->reserved1);
cfbba5b9 1971 return 0;
2127e193
GI
1972 }
1973
1974 // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
1975 // it is 1-based in practice.
1976 logidx--;
1977
1978 bool print_header = true;
cfbba5b9
GI
1979 int errcnt = 0, igncnt = 0;
1980 int ext_ok_testnum = -1;
2127e193
GI
1981
1982 // Iterate through circular buffer in reverse direction
1983 for (unsigned i = 0, testnum = 1;
1984 i < nentries && testnum <= max_entries;
1985 i++, logidx = (logidx > 0 ? logidx - 1 : nentries - 1)) {
1986
1987 const ata_smart_extselftestlog_desc & entry = log[logidx / 19].log_descs[logidx % 19];
1988
1989 // Skip unused entries
1990 if (!nonempty(&entry, sizeof(entry)))
1991 continue;
1992
1993 // Get LBA
1994 const unsigned char * b = entry.failing_lba;
1995 uint64_t lba48 = b[0]
1996 | ( b[1] << 8)
1997 | ( b[2] << 16)
1998 | ((uint64_t)b[3] << 24)
1999 | ((uint64_t)b[4] << 32)
2000 | ((uint64_t)b[5] << 40);
2001
2002 // Print entry
cfbba5b9 2003 int state = ataPrintSmartSelfTestEntry(testnum, entry.self_test_type,
2127e193
GI
2004 entry.self_test_status, entry.timestamp, lba48,
2005 false /*!print_error_only*/, print_header);
cfbba5b9
GI
2006
2007 if (state < 0) {
2008 // Self-test showed an error
2009 if (ext_ok_testnum < 0)
2010 errcnt++;
2011 else
2012 // Newer successful extended self-test exits
2013 igncnt++;
2014 }
2015 else if (state > 0 && ext_ok_testnum < 0) {
2016 // Latest successful extended self-test
2017 ext_ok_testnum = testnum;
2018 }
2019 testnum++;
2127e193 2020 }
cfbba5b9
GI
2021
2022 if (igncnt)
2023 pout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
2024 igncnt, igncnt+errcnt, ext_ok_testnum);
2025
2127e193 2026 pout("\n");
cfbba5b9 2027 return errcnt;
2127e193
GI
2028}
2029
2030static void ataPrintSelectiveSelfTestLog(const ata_selective_self_test_log * log, const ata_smart_values * sv)
2031{
832b75ed 2032 int i,field1,field2;
2127e193 2033 const char *msg;
832b75ed
GG
2034 char tmp[64];
2035 uint64_t maxl=0,maxr=0;
2036 uint64_t current=log->currentlba;
2037 uint64_t currentend=current+65535;
2038
2039 // print data structure revision number
2040 pout("SMART Selective self-test log data structure revision number %d\n",(int)log->logversion);
2041 if (1 != log->logversion)
2127e193 2042 pout("Note: revision number not 1 implies that no selective self-test has ever been run\n");
832b75ed
GG
2043
2044 switch((sv->self_test_exec_status)>>4){
2045 case 0:msg="Completed";
2046 break;
2047 case 1:msg="Aborted_by_host";
2048 break;
2049 case 2:msg="Interrupted";
2050 break;
2051 case 3:msg="Fatal_error";
2052 break;
2053 case 4:msg="Completed_unknown_failure";
2054 break;
2055 case 5:msg="Completed_electrical_failure";
2056 break;
2057 case 6:msg="Completed_servo/seek_failure";
2058 break;
2059 case 7:msg="Completed_read_failure";
2060 break;
2061 case 8:msg="Completed_handling_damage??";
2062 break;
2063 case 15:msg="Self_test_in_progress";
2064 break;
2065 default:msg="Unknown_status ";
2066 break;
2067 }
2068
2069 // find the number of columns needed for printing. If in use, the
2070 // start/end of span being read-scanned...
2071 if (log->currentspan>5) {
2072 maxl=current;
2073 maxr=currentend;
2074 }
2075 for (i=0; i<5; i++) {
2076 uint64_t start=log->span[i].start;
2077 uint64_t end =log->span[i].end;
2078 // ... plus max start/end of each of the five test spans.
2079 if (start>maxl)
2080 maxl=start;
2081 if (end > maxr)
2082 maxr=end;
2083 }
2084
2085 // we need at least 7 characters wide fields to accomodate the
2086 // labels
d2e702cf 2087 if ((field1=snprintf(tmp,64, "%" PRIu64, maxl))<7)
832b75ed 2088 field1=7;
d2e702cf 2089 if ((field2=snprintf(tmp,64, "%" PRIu64, maxr))<7)
832b75ed
GG
2090 field2=7;
2091
2092 // now print the five test spans
2093 pout(" SPAN %*s %*s CURRENT_TEST_STATUS\n", field1, "MIN_LBA", field2, "MAX_LBA");
2094
2095 for (i=0; i<5; i++) {
2096 uint64_t start=log->span[i].start;
2097 uint64_t end=log->span[i].end;
2098
2099 if ((i+1)==(int)log->currentspan)
2100 // this span is currently under test
d2e702cf 2101 pout(" %d %*" PRIu64 " %*" PRIu64 " %s [%01d0%% left] (%" PRIu64 "-%" PRIu64 ")\n",
832b75ed 2102 i+1, field1, start, field2, end, msg,
ba59cff1 2103 (int)(sv->self_test_exec_status & 0xf), current, currentend);
832b75ed
GG
2104 else
2105 // this span is not currently under test
d2e702cf 2106 pout(" %d %*" PRIu64 " %*" PRIu64 " Not_testing\n",
832b75ed
GG
2107 i+1, field1, start, field2, end);
2108 }
2109
2110 // if we are currently read-scanning, print LBAs and the status of
2111 // the read scan
2112 if (log->currentspan>5)
d2e702cf 2113 pout("%5d %*" PRIu64 " %*" PRIu64 " Read_scanning %s\n",
832b75ed
GG
2114 (int)log->currentspan, field1, current, field2, currentend,
2115 OfflineDataCollectionStatus(sv->offline_data_collection_status));
2116
2117 /* Print selective self-test flags. Possible flag combinations are
2118 (numbering bits from 0-15):
2119 Bit-1 Bit-3 Bit-4
2120 Scan Pending Active
2121 0 * * Don't scan
2122 1 0 0 Will carry out scan after selective test
2123 1 1 0 Waiting to carry out scan after powerup
2124 1 0 1 Currently scanning
2125 1 1 1 Currently scanning
2126 */
2127
2128 pout("Selective self-test flags (0x%x):\n", (unsigned int)log->flags);
2129 if (log->flags & SELECTIVE_FLAG_DOSCAN) {
2130 if (log->flags & SELECTIVE_FLAG_ACTIVE)
2131 pout(" Currently read-scanning the remainder of the disk.\n");
2132 else if (log->flags & SELECTIVE_FLAG_PENDING)
2133 pout(" Read-scan of remainder of disk interrupted; will resume %d min after power-up.\n",
2134 (int)log->pendingtime);
2135 else
2136 pout(" After scanning selected spans, read-scan remainder of disk.\n");
2137 }
2138 else
2139 pout(" After scanning selected spans, do NOT read-scan remainder of disk.\n");
2140
2141 // print pending time
2142 pout("If Selective self-test is pending on power-up, resume after %d minute delay.\n",
2143 (int)log->pendingtime);
2144
2145 return;
2146}
2147
a37e7145 2148// Format SCT Temperature value
ee38a438 2149static const char * sct_ptemp(signed char x, char (& buf)[20])
a37e7145
GG
2150{
2151 if (x == -128 /*0x80 = unknown*/)
ee38a438
GI
2152 return " ?";
2153 snprintf(buf, sizeof(buf), "%2d", x);
a37e7145
GG
2154 return buf;
2155}
2156
ee38a438 2157static const char * sct_pbar(int x, char (& buf)[64])
a37e7145
GG
2158{
2159 if (x <= 19)
2160 x = 0;
2161 else
2162 x -= 19;
2163 bool ov = false;
2164 if (x > 40) {
2165 x = 40; ov = true;
2166 }
2167 if (x > 0) {
2168 memset(buf, '*', x);
2169 if (ov)
2170 buf[x-1] = '+';
2171 buf[x] = 0;
2172 }
2173 else {
2174 buf[0] = '-'; buf[1] = 0;
2175 }
2176 return buf;
2177}
2178
2179static const char * sct_device_state_msg(unsigned char state)
2180{
2181 switch (state) {
2182 case 0: return "Active";
2183 case 1: return "Stand-by";
2184 case 2: return "Sleep";
2185 case 3: return "DST executing in background";
2186 case 4: return "SMART Off-line Data Collection executing in background";
2187 case 5: return "SCT command executing in background";
2188 default:return "Unknown";
2189 }
2190}
2191
2192// Print SCT Status
2193static int ataPrintSCTStatus(const ata_sct_status_response * sts)
2194{
2195 pout("SCT Status Version: %u\n", sts->format_version);
2196 pout("SCT Version (vendor specific): %u (0x%04x)\n", sts->sct_version, sts->sct_version);
2197 pout("SCT Support Level: %u\n", sts->sct_spec);
2198 pout("Device State: %s (%u)\n",
2199 sct_device_state_msg(sts->device_state), sts->device_state);
2200 char buf1[20], buf2[20];
d008864d
GI
2201 if ( !sts->min_temp && !sts->life_min_temp
2202 && !sts->under_limit_count && !sts->over_limit_count) {
a37e7145 2203 // "Reserved" fields not set, assume "old" format version 2
d008864d
GI
2204 // Table 11 of T13/1701DT-N (SMART Command Transport) Revision 5, February 2005
2205 // Table 54 of T13/1699-D (ATA8-ACS) Revision 3e, July 2006
a37e7145
GG
2206 pout("Current Temperature: %s Celsius\n",
2207 sct_ptemp(sts->hda_temp, buf1));
2208 pout("Power Cycle Max Temperature: %s Celsius\n",
2209 sct_ptemp(sts->max_temp, buf2));
2210 pout("Lifetime Max Temperature: %s Celsius\n",
2211 sct_ptemp(sts->life_max_temp, buf2));
2212 }
2213 else {
2214 // Assume "new" format version 2 or version 3
d008864d
GI
2215 // T13/e06152r0-3 (Additional SCT Temperature Statistics), August - October 2006
2216 // Table 60 of T13/1699-D (ATA8-ACS) Revision 3f, December 2006 (format version 2)
2217 // Table 80 of T13/1699-D (ATA8-ACS) Revision 6a, September 2008 (format version 3)
a37e7145
GG
2218 pout("Current Temperature: %s Celsius\n",
2219 sct_ptemp(sts->hda_temp, buf1));
2220 pout("Power Cycle Min/Max Temperature: %s/%s Celsius\n",
2221 sct_ptemp(sts->min_temp, buf1), sct_ptemp(sts->max_temp, buf2));
2222 pout("Lifetime Min/Max Temperature: %s/%s Celsius\n",
2223 sct_ptemp(sts->life_min_temp, buf1), sct_ptemp(sts->life_max_temp, buf2));
d008864d
GI
2224 signed char avg = sts->byte205; // Average Temperature from e06152r0-2, removed in e06152r3
2225 if (0 < avg && sts->life_min_temp <= avg && avg <= sts->life_max_temp)
2226 pout("Lifetime Average Temperature: %2d Celsius\n", avg);
a37e7145
GG
2227 pout("Under/Over Temperature Limit Count: %2u/%u\n",
2228 sts->under_limit_count, sts->over_limit_count);
2229 }
2230 return 0;
2231}
2232
2233// Print SCT Temperature History Table
2234static int ataPrintSCTTempHist(const ata_sct_temperature_history_table * tmh)
2235{
ee38a438
GI
2236 char buf1[20], buf2[20], buf3[64];
2237 pout("SCT Temperature History Version: %u%s\n", tmh->format_version,
2238 (tmh->format_version != 2 ? " (Unknown, should be 2)" : ""));
a37e7145
GG
2239 pout("Temperature Sampling Period: %u minute%s\n",
2240 tmh->sampling_period, (tmh->sampling_period==1?"":"s"));
2241 pout("Temperature Logging Interval: %u minute%s\n",
2242 tmh->interval, (tmh->interval==1?"":"s"));
2243 pout("Min/Max recommended Temperature: %s/%s Celsius\n",
2244 sct_ptemp(tmh->min_op_limit, buf1), sct_ptemp(tmh->max_op_limit, buf2));
2245 pout("Min/Max Temperature Limit: %s/%s Celsius\n",
2246 sct_ptemp(tmh->under_limit, buf1), sct_ptemp(tmh->over_limit, buf2));
2247 pout("Temperature History Size (Index): %u (%u)\n", tmh->cb_size, tmh->cb_index);
ee38a438 2248
a37e7145 2249 if (!(0 < tmh->cb_size && tmh->cb_size <= sizeof(tmh->cb) && tmh->cb_index < tmh->cb_size)) {
ee38a438
GI
2250 if (!tmh->cb_size)
2251 pout("Temperature History is empty\n");
2252 else
2253 pout("Invalid Temperature History Size or Index\n");
a37e7145
GG
2254 return 0;
2255 }
2256
2257 // Print table
2258 pout("\nIndex Estimated Time Temperature Celsius\n");
2259 unsigned n = 0, i = (tmh->cb_index+1) % tmh->cb_size;
2260 unsigned interval = (tmh->interval > 0 ? tmh->interval : 1);
2261 time_t t = time(0) - (tmh->cb_size-1) * interval * 60;
2262 t -= t % (interval * 60);
2263 while (n < tmh->cb_size) {
2264 // Find range of identical temperatures
2265 unsigned n1 = n, n2 = n+1, i2 = (i+1) % tmh->cb_size;
2266 while (n2 < tmh->cb_size && tmh->cb[i2] == tmh->cb[i]) {
2267 n2++; i2 = (i2+1) % tmh->cb_size;
2268 }
2269 // Print range
2270 while (n < n2) {
2271 if (n == n1 || n == n2-1 || n2 <= n1+3) {
2272 char date[30];
2273 // TODO: Don't print times < boot time
2274 strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&t));
2275 pout(" %3u %s %s %s\n", i, date,
ee38a438 2276 sct_ptemp(tmh->cb[i], buf1), sct_pbar(tmh->cb[i], buf3));
a37e7145
GG
2277 }
2278 else if (n == n1+1) {
2279 pout(" ... ..(%3u skipped). .. %s\n",
ee38a438 2280 n2-n1-2, sct_pbar(tmh->cb[i], buf3));
a37e7145
GG
2281 }
2282 t += interval * 60; i = (i+1) % tmh->cb_size; n++;
2283 }
2284 }
2285 //assert(n == tmh->cb_size && i == (tmh->cb_index+1) % tmh->cb_size);
2286
2287 return 0;
2288}
2289
7f0798ef 2290// Print SCT Error Recovery Control timers
cfbba5b9 2291static void ataPrintSCTErrorRecoveryControl(bool set, unsigned short read_timer, unsigned short write_timer)
7f0798ef 2292{
cfbba5b9 2293 pout("SCT Error Recovery Control%s:\n", (set ? " set to" : ""));
7f0798ef
GI
2294 if (!read_timer)
2295 pout(" Read: Disabled\n");
2296 else
2297 pout(" Read: %6d (%0.1f seconds)\n", read_timer, read_timer/10.0);
2298 if (!write_timer)
2299 pout(" Write: Disabled\n");
2300 else
2301 pout(" Write: %6d (%0.1f seconds)\n", write_timer, write_timer/10.0);
2302}
2303
d008864d
GI
2304static void print_aam_level(const char * msg, int level, int recommended = -1)
2305{
2306 // Table 56 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
2307 // Obsolete since T13/2015-D (ACS-2) Revision 4a, December 9, 2010
2308 const char * s;
2309 if (level == 0)
2310 s = "vendor specific";
2311 else if (level < 128)
2312 s = "unknown/retired";
2313 else if (level == 128)
2314 s = "quiet";
2315 else if (level < 254)
2316 s = "intermediate";
2317 else if (level == 254)
2318 s = "maximum performance";
2319 else
2320 s = "reserved";
2321
2322 if (recommended >= 0)
2323 pout("%s%d (%s), recommended: %d\n", msg, level, s, recommended);
2324 else
2325 pout("%s%d (%s)\n", msg, level, s);
2326}
2327
2328static void print_apm_level(const char * msg, int level)
2329{
2330 // Table 120 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
2331 const char * s;
2332 if (!(1 <= level && level <= 254))
2333 s = "reserved";
2334 else if (level == 1)
2335 s = "minimum power consumption with standby";
2336 else if (level < 128)
2337 s = "intermediate level with standby";
2338 else if (level == 128)
2339 s = "minimum power consumption without standby";
2340 else if (level < 254)
2341 s = "intermediate level without standby";
2342 else
2343 s = "maximum performance";
2344
2345 pout("%s%d (%s)\n", msg, level, s);
2346}
2347
2348static void print_ata_security_status(const char * msg, unsigned short state)
2349{
2350 const char * s1, * s2 = "", * s3 = "", * s4 = "";
2351
2352 // Table 6 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
2353 if (!(state & 0x0001))
2354 s1 = "Unavailable";
2355 else if (!(state & 0x0002)) {
2356 s1 = "Disabled, ";
2357 if (!(state & 0x0008))
2358 s2 = "NOT FROZEN [SEC1]";
2359 else
2360 s2 = "frozen [SEC2]";
2361 }
2362 else {
2363 s1 = "ENABLED, PW level ";
2364 if (!(state & 0x0020))
2365 s2 = "HIGH";
2366 else
2367 s2 = "MAX";
2368
2369 if (!(state & 0x0004)) {
2370 s3 = ", not locked, ";
2371 if (!(state & 0x0008))
2372 s4 = "not frozen [SEC5]";
2373 else
2374 s4 = "frozen [SEC6]";
2375 }
2376 else {
2377 s3 = ", **LOCKED** [SEC4]";
2378 if (state & 0x0010)
2379 s4 = ", PW ATTEMPTS EXCEEDED";
2380 }
2381 }
2382
2383 pout("%s%s%s%s%s\n", msg, s1, s2, s3, s4);
2384}
2385
2386static void print_standby_timer(const char * msg, int timer, const ata_identify_device & drive)
2387{
2388 const char * s1 = 0;
2389 int hours = 0, minutes = 0 , seconds = 0;
2390
2391 // Table 63 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
2392 if (timer == 0)
2393 s1 = "disabled";
2394 else if (timer <= 240)
2395 seconds = timer * 5, minutes = seconds / 60, seconds %= 60;
2396 else if (timer <= 251)
2397 minutes = (timer - 240) * 30, hours = minutes / 60, minutes %= 60;
2398 else if (timer == 252)
2399 minutes = 21;
2400 else if (timer == 253)
2401 s1 = "between 8 hours and 12 hours";
2402 else if (timer == 255)
2403 minutes = 21, seconds = 15;
2404 else
2405 s1 = "reserved";
2406
2407 const char * s2 = "", * s3 = "";
2408 if (!(drive.words047_079[49-47] & 0x2000))
2409 s2 = " or vendor-specific";
2410 if (timer > 0 && (drive.words047_079[50-47] & 0xc001) == 0x4001)
2411 s3 = ", a vendor-specific minimum applies";
2412
2413 if (s1)
2414 pout("%s%d (%s%s%s)\n", msg, timer, s1, s2, s3);
2415 else
2416 pout("%s%d (%02d:%02d:%02d%s%s)\n", msg, timer, hours, minutes, seconds, s2, s3);
2417}
2418
a37e7145 2419
2127e193
GI
2420int ataPrintMain (ata_device * device, const ata_print_options & options)
2421{
4d59bff9 2422 // If requested, check power mode first
e9583e0c
GI
2423 const char * powername = 0;
2424 bool powerchg = false;
2127e193 2425 if (options.powermode) {
4d59bff9 2426 unsigned char powerlimit = 0xff;
2127e193 2427 int powermode = ataCheckPowerMode(device);
4d59bff9
GG
2428 switch (powermode) {
2429 case -1:
f4e463df 2430 if (device->is_syscall_unsup()) {
cfbba5b9 2431 pout("CHECK POWER MODE not implemented, ignoring -n option\n"); break;
4d59bff9
GG
2432 }
2433 powername = "SLEEP"; powerlimit = 2;
2434 break;
2435 case 0:
2436 powername = "STANDBY"; powerlimit = 3; break;
2437 case 0x80:
2438 powername = "IDLE"; powerlimit = 4; break;
2439 case 0xff:
2440 powername = "ACTIVE or IDLE"; break;
2441 default:
cfbba5b9 2442 pout("CHECK POWER MODE returned unknown value 0x%02x, ignoring -n option\n", powermode);
4d59bff9
GG
2443 break;
2444 }
2445 if (powername) {
2127e193 2446 if (options.powermode >= powerlimit) {
4d59bff9
GG
2447 pout("Device is in %s mode, exit(%d)\n", powername, FAILPOWER);
2448 return FAILPOWER;
2449 }
2450 powerchg = (powermode != 0xff); // SMART tests will spin up drives
2451 }
2452 }
832b75ed 2453
e9583e0c
GI
2454 // SMART values needed ?
2455 bool need_smart_val = (
2456 options.smart_check_status
2457 || options.smart_general_values
2458 || options.smart_vendor_attrib
2459 || options.smart_error_log
2460 || options.smart_selftest_log
2461 || options.smart_selective_selftest_log
2462 || options.smart_ext_error_log
2463 || options.smart_ext_selftest_log
2464 || options.smart_auto_offl_enable
2465 || options.smart_auto_offl_disable
2466 || options.smart_selftest_type != -1
2467 );
2468
2469 // SMART must be enabled ?
2470 bool need_smart_enabled = (
2471 need_smart_val
2472 || options.smart_auto_save_enable
2473 || options.smart_auto_save_disable
2474 );
2475
2476 // SMART feature set needed ?
2477 bool need_smart_support = (
2478 need_smart_enabled
2479 || options.smart_enable
2480 || options.smart_disable
2481 );
2482
cfbba5b9 2483 // SMART and GP log directories needed ?
d2e702cf
GI
2484 bool need_smart_logdir = (
2485 options.smart_logdir
2486 || options.devstat_all_pages // devstat fallback to smartlog if needed
2487 || options.devstat_ssd_page
2488 || !options.devstat_pages.empty()
2489 );
cfbba5b9
GI
2490
2491 bool need_gp_logdir = (
2492 options.gp_logdir
2493 || options.smart_ext_error_log
2494 || options.smart_ext_selftest_log
d008864d
GI
2495 || options.devstat_all_pages
2496 || options.devstat_ssd_page
2497 || !options.devstat_pages.empty()
cfbba5b9
GI
2498 );
2499
2500 unsigned i;
2501 for (i = 0; i < options.log_requests.size(); i++) {
2502 if (options.log_requests[i].gpl)
2503 need_gp_logdir = true;
2504 else
2505 need_smart_logdir = true;
2506 }
2507
2508 // SCT commands needed ?
2509 bool need_sct_support = (
2510 options.sct_temp_sts
2511 || options.sct_temp_hist
2512 || options.sct_temp_int
2513 || options.sct_erc_get
2514 || options.sct_erc_set
3d17a85c
GI
2515 || options.sct_wcache_reorder_get
2516 || options.sct_wcache_reorder_set
cfbba5b9
GI
2517 );
2518
2519 // Exit if no further options specified
ee38a438
GI
2520 if (!( options.drive_info || options.show_presets
2521 || need_smart_support || need_smart_logdir
2522 || need_gp_logdir || need_sct_support
2523 || options.sataphy
2524 || options.identify_word_level >= 0
2525 || options.get_set_used )) {
cfbba5b9
GI
2526 if (powername)
2527 pout("Device is in %s mode\n", powername);
2528 else
2529 pout("ATA device successfully opened\n\n"
2530 "Use 'smartctl -a' (or '-x') to print SMART (and more) information\n\n");
2531 return 0;
2532 }
2533
832b75ed 2534 // Start by getting Drive ID information. We need this, to know if SMART is supported.
cfbba5b9 2535 int returnval = 0;
e9583e0c 2536 ata_identify_device drive; memset(&drive, 0, sizeof(drive));
ee38a438
GI
2537 unsigned char raw_drive[sizeof(drive)]; memset(&raw_drive, 0, sizeof(raw_drive));
2538
a7e8ffec 2539 device->clear_err();
ee38a438 2540 int retid = ata_read_identity(device, &drive, options.fix_swapped_id, raw_drive);
e9583e0c 2541 if (retid < 0) {
ee38a438 2542 pout("Read Device Identity failed: %s\n\n",
a7e8ffec
GI
2543 (device->get_errno() ? device->get_errmsg() : "Unknown error"));
2544 failuretest(MANDATORY_CMD, returnval|=FAILID);
2545 }
2546 else if (!nonempty(&drive, sizeof(drive))) {
ee38a438 2547 pout("Read Device Identity failed: empty IDENTIFY data\n\n");
832b75ed
GG
2548 failuretest(MANDATORY_CMD, returnval|=FAILID);
2549 }
2550
2551 // If requested, show which presets would be used for this drive and exit.
2127e193 2552 if (options.show_presets) {
cfbba5b9 2553 show_presets(&drive);
a23d5117 2554 return 0;
832b75ed
GG
2555 }
2556
2557 // Use preset vendor attribute options unless user has requested otherwise.
bed94269 2558 ata_vendor_attr_defs attribute_defs = options.attribute_defs;
ee38a438 2559 firmwarebug_defs firmwarebugs = options.firmwarebugs;
cfbba5b9 2560 const drive_settings * dbentry = 0;
2127e193 2561 if (!options.ignore_presets)
cfbba5b9 2562 dbentry = lookup_drive_apply_presets(&drive, attribute_defs,
ee38a438 2563 firmwarebugs);
832b75ed 2564
ee38a438 2565 // Get capacity, sector sizes and rotation rate
a7e8ffec
GI
2566 ata_size_info sizes;
2567 ata_get_size_info(&drive, sizes);
ee38a438
GI
2568 int rpm = ata_get_rotation_rate(&drive);
2569
2570 // Print ATA IDENTIFY info if requested
2571 if (options.identify_word_level >= 0) {
2572 pout("=== ATA IDENTIFY DATA ===\n");
2573 // Pass raw data without endianness adjustments
2574 ata_print_identify_data(raw_drive, (options.identify_word_level > 0), options.identify_bit_level);
2575 }
a7e8ffec 2576
832b75ed 2577 // Print most drive identity information if requested
2127e193 2578 if (options.drive_info) {
832b75ed 2579 pout("=== START OF INFORMATION SECTION ===\n");
ee38a438 2580 print_drive_info(&drive, sizes, rpm, dbentry);
832b75ed
GG
2581 }
2582
e9583e0c
GI
2583 // Check and print SMART support and state
2584 int smart_supported = -1, smart_enabled = -1;
2585 if (need_smart_support || options.drive_info) {
832b75ed 2586
e9583e0c
GI
2587 // Packet device ?
2588 if (retid > 0) {
2589 pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n",
2590 packetdevicetype(retid-1));
832b75ed
GG
2591 }
2592 else {
e9583e0c
GI
2593 // Disk device: SMART supported and enabled ?
2594 smart_supported = ataSmartSupport(&drive);
2595 smart_enabled = ataIsSmartEnabled(&drive);
2596
2597 if (smart_supported < 0)
2598 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
2599 if (smart_supported && smart_enabled < 0) {
2600 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
2601 if (need_smart_support) {
2602 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2603 // check SMART support by trying a command
2604 pout(" Checking to be sure by trying SMART RETURN STATUS command.\n");
2605 if (ataDoesSmartWork(device))
2606 smart_supported = smart_enabled = 1;
2607 }
2608 }
cfbba5b9 2609 else if (smart_supported < 0 && (smart_enabled > 0 || dbentry))
e9583e0c
GI
2610 // Assume supported if enabled or in drive database
2611 smart_supported = 1;
2612
2613 if (smart_supported < 0)
2614 pout("SMART support is: Unknown - Try option -s with argument 'on' to enable it.");
2615 else if (!smart_supported)
2616 pout("SMART support is: Unavailable - device lacks SMART capability.\n");
2617 else {
2618 if (options.drive_info)
2619 pout("SMART support is: Available - device has SMART capability.\n");
2620 if (smart_enabled >= 0) {
2621 if (device->ata_identify_is_cached()) {
2622 if (options.drive_info)
2623 pout(" %sabled status cached by OS, trying SMART RETURN STATUS cmd.\n",
2624 (smart_enabled?"En":"Dis"));
2625 smart_enabled = ataDoesSmartWork(device);
2626 }
2627 if (options.drive_info)
2628 pout("SMART support is: %s\n",
2629 (smart_enabled ? "Enabled" : "Disabled"));
2630 }
832b75ed 2631 }
832b75ed 2632 }
e9583e0c 2633 }
832b75ed 2634
d008864d
GI
2635 // Print AAM status
2636 if (options.get_aam) {
2637 if ((drive.command_set_2 & 0xc200) != 0x4200) // word083
2638 pout("AAM feature is: Unavailable\n");
2639 else if (!(drive.word086 & 0x0200))
2640 pout("AAM feature is: Disabled\n");
2641 else
2642 print_aam_level("AAM level is: ", drive.words088_255[94-88] & 0xff,
2643 drive.words088_255[94-88] >> 8);
2644 }
2645
2646 // Print APM status
2647 if (options.get_apm) {
2648 if ((drive.command_set_2 & 0xc008) != 0x4008) // word083
2649 pout("APM feature is: Unavailable\n");
2650 else if (!(drive.word086 & 0x0008))
2651 pout("APM feature is: Disabled\n");
2652 else
2653 print_apm_level("APM level is: ", drive.words088_255[91-88] & 0xff);
2654 }
2655
2656 // Print read look-ahead status
2657 if (options.get_lookahead) {
2658 pout("Rd look-ahead is: %s\n",
2659 ( (drive.command_set_2 & 0xc000) != 0x4000 // word083
2660 || !(drive.command_set_1 & 0x0040)) ? "Unavailable" : // word082
2661 !(drive.cfs_enable_1 & 0x0040) ? "Disabled" : "Enabled"); // word085
2662 }
2663
2664 // Print write cache status
2665 if (options.get_wcache) {
2666 pout("Write cache is: %s\n",
2667 ( (drive.command_set_2 & 0xc000) != 0x4000 // word083
2668 || !(drive.command_set_1 & 0x0020)) ? "Unavailable" : // word082
2669 !(drive.cfs_enable_1 & 0x0020) ? "Disabled" : "Enabled"); // word085
2670 }
2671
2672 // Print ATA security status
2673 if (options.get_security)
2674 print_ata_security_status("ATA Security is: ", drive.words088_255[128-88]);
2675
d2e702cf
GI
2676 // Print write cache reordering status
2677 if (options.sct_wcache_reorder_get) {
2678 if (isSCTFeatureControlCapable(&drive)) {
2679 int wcache_reorder = ataGetSetSCTWriteCacheReordering(device,
2680 false /*enable*/, false /*persistent*/, false /*set*/);
2681
2682 if (-1 <= wcache_reorder && wcache_reorder <= 2)
2683 pout("Wt Cache Reorder: %s\n",
2684 (wcache_reorder == -1 ? "Unknown (SCT Feature Control command failed)" :
2685 wcache_reorder == 0 ? "Unknown" : // not defined in standard but returned on some drives if not set
2686 wcache_reorder == 1 ? "Enabled" : "Disabled"));
2687 else
2688 pout("Wt Cache Reorder: Unknown (0x%02x)\n", wcache_reorder);
3d17a85c
GI
2689 }
2690 else
d2e702cf 2691 pout("Wt Cache Reorder: Unavailable\n");
3d17a85c
GI
2692 }
2693
e9583e0c
GI
2694 // Print remaining drive info
2695 if (options.drive_info) {
4d59bff9
GG
2696 // Print the (now possibly changed) power mode if available
2697 if (powername)
2698 pout("Power mode %s %s\n", (powerchg?"was:":"is: "), powername);
832b75ed
GG
2699 pout("\n");
2700 }
e9583e0c
GI
2701
2702 // Exit if SMART is not supported but must be available to proceed
2703 if (smart_supported <= 0 && need_smart_support)
2704 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2705
832b75ed 2706 // START OF THE ENABLE/DISABLE SECTION OF THE CODE
2127e193
GI
2707 if ( options.smart_disable || options.smart_enable
2708 || options.smart_auto_save_disable || options.smart_auto_save_enable
3d17a85c
GI
2709 || options.smart_auto_offl_disable || options.smart_auto_offl_enable
2710 || options.set_aam || options.set_apm || options.set_lookahead
2711 || options.set_wcache || options.set_security_freeze || options.set_standby
2712 || options.sct_wcache_reorder_set)
832b75ed
GG
2713 pout("=== START OF ENABLE/DISABLE COMMANDS SECTION ===\n");
2714
d008864d
GI
2715 // Enable/Disable AAM
2716 if (options.set_aam) {
2717 if (options.set_aam > 0) {
2718 if (!ata_set_features(device, ATA_ENABLE_AAM, options.set_aam-1)) {
2719 pout("AAM enable failed: %s\n", device->get_errmsg());
2720 returnval |= FAILSMART;
2721 }
2722 else
2723 print_aam_level("AAM set to level ", options.set_aam-1);
2724 }
2725 else {
2726 if (!ata_set_features(device, ATA_DISABLE_AAM)) {
2727 pout("AAM disable failed: %s\n", device->get_errmsg());
2728 returnval |= FAILSMART;
2729 }
2730 else
2731 pout("AAM disabled\n");
2732 }
2733 }
2734
2735 // Enable/Disable APM
2736 if (options.set_apm) {
2737 if (options.set_apm > 0) {
2738 if (!ata_set_features(device, ATA_ENABLE_APM, options.set_apm-1)) {
2739 pout("APM enable failed: %s\n", device->get_errmsg());
2740 returnval |= FAILSMART;
2741 }
2742 else
2743 print_apm_level("APM set to level ", options.set_apm-1);
2744 }
2745 else {
2746 if (!ata_set_features(device, ATA_DISABLE_APM)) {
2747 pout("APM disable failed: %s\n", device->get_errmsg());
2748 returnval |= FAILSMART;
2749 }
2750 else
2751 pout("APM disabled\n");
2752 }
2753 }
2754
2755 // Enable/Disable read look-ahead
2756 if (options.set_lookahead) {
2757 bool enable = (options.set_lookahead > 0);
2758 if (!ata_set_features(device, (enable ? ATA_ENABLE_READ_LOOK_AHEAD : ATA_DISABLE_READ_LOOK_AHEAD))) {
2759 pout("Read look-ahead %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
2760 returnval |= FAILSMART;
2761 }
2762 else
2763 pout("Read look-ahead %sabled\n", (enable ? "en" : "dis"));
2764 }
2765
2766 // Enable/Disable write cache
2767 if (options.set_wcache) {
2768 bool enable = (options.set_wcache > 0);
2769 if (!ata_set_features(device, (enable ? ATA_ENABLE_WRITE_CACHE : ATA_DISABLE_WRITE_CACHE))) {
2770 pout("Write cache %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
2771 returnval |= FAILSMART;
2772 }
2773 else
2774 pout("Write cache %sabled\n", (enable ? "en" : "dis"));
2775 }
2776
3d17a85c 2777 // Enable/Disable write cache reordering
d2e702cf 2778 if (options.sct_wcache_reorder_set) {
3d17a85c 2779 bool enable = (options.sct_wcache_reorder_set > 0);
d2e702cf
GI
2780 if (!isSCTFeatureControlCapable(&drive))
2781 pout("Write cache reordering %sable failed: SCT Feature Control command not supported\n",
2782 (enable ? "en" : "dis"));
2783 else if (ataGetSetSCTWriteCacheReordering(device,
2784 enable, false /*persistent*/, true /*set*/) < 0) {
2785 pout("Write cache reordering %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
2786 returnval |= FAILSMART;
3d17a85c
GI
2787 }
2788 else
2789 pout("Write cache reordering %sabled\n", (enable ? "en" : "dis"));
2790 }
2791
d008864d
GI
2792 // Freeze ATA security
2793 if (options.set_security_freeze) {
2794 if (!ata_nodata_command(device, ATA_SECURITY_FREEZE_LOCK)) {
2795 pout("ATA SECURITY FREEZE LOCK failed: %s\n", device->get_errmsg());
2796 returnval |= FAILSMART;
2797 }
2798 else
2799 pout("ATA Security set to frozen mode\n");
2800 }
2801
2802 // Set standby timer
2803 if (options.set_standby) {
2804 if (!ata_nodata_command(device, ATA_IDLE, options.set_standby-1)) {
2805 pout("ATA IDLE command failed: %s\n", device->get_errmsg());
2806 returnval |= FAILSMART;
2807 }
2808 else
2809 print_standby_timer("Standby timer set to ", options.set_standby-1, drive);
2810 }
2811
832b75ed 2812 // Enable/Disable SMART commands
2127e193
GI
2813 if (options.smart_enable) {
2814 if (ataEnableSmart(device)) {
ee38a438 2815 pout("SMART Enable failed: %s\n\n", device->get_errmsg());
832b75ed
GG
2816 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2817 }
e9583e0c 2818 else {
832b75ed 2819 pout("SMART Enabled.\n");
e9583e0c
GI
2820 smart_enabled = 1;
2821 }
832b75ed 2822 }
e9583e0c 2823
832b75ed 2824 // Turn off SMART on device
2127e193
GI
2825 if (options.smart_disable) {
2826 if (ataDisableSmart(device)) {
ee38a438 2827 pout("SMART Disable failed: %s\n\n", device->get_errmsg());
832b75ed
GG
2828 failuretest(MANDATORY_CMD,returnval|=FAILSMART);
2829 }
e9583e0c
GI
2830 }
2831
2832 // Exit if SMART is disabled but must be enabled to proceed
ee38a438 2833 if (options.smart_disable || (smart_enabled <= 0 && need_smart_enabled && !is_permissive())) {
832b75ed 2834 pout("SMART Disabled. Use option -s with argument 'on' to enable it.\n");
ee38a438
GI
2835 if (!options.smart_disable)
2836 pout("(override with '-T permissive' option)\n");
e9583e0c 2837 return returnval;
832b75ed 2838 }
832b75ed
GG
2839
2840 // Enable/Disable Auto-save attributes
2127e193
GI
2841 if (options.smart_auto_save_enable) {
2842 if (ataEnableAutoSave(device)){
ee38a438 2843 pout("SMART Enable Attribute Autosave failed: %s\n\n", device->get_errmsg());
832b75ed
GG
2844 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2845 }
2846 else
2847 pout("SMART Attribute Autosave Enabled.\n");
2848 }
2127e193
GI
2849
2850 if (options.smart_auto_save_disable) {
2851 if (ataDisableAutoSave(device)){
ee38a438 2852 pout("SMART Disable Attribute Autosave failed: %s\n\n", device->get_errmsg());
832b75ed
GG
2853 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2854 }
2855 else
2856 pout("SMART Attribute Autosave Disabled.\n");
2857 }
e9583e0c
GI
2858
2859 // Read SMART values and thresholds if necessary
2860 ata_smart_values smartval; memset(&smartval, 0, sizeof(smartval));
2861 ata_smart_thresholds_pvt smartthres; memset(&smartthres, 0, sizeof(smartthres));
2862 bool smart_val_ok = false, smart_thres_ok = false;
2863
2864 if (need_smart_val) {
2865 if (ataReadSmartValues(device, &smartval)) {
ee38a438 2866 pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
e9583e0c
GI
2867 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2868 }
2869 else {
2870 smart_val_ok = true;
2871
2872 if (options.smart_check_status || options.smart_vendor_attrib) {
2873 if (ataReadSmartThresholds(device, &smartthres)){
ee38a438 2874 pout("Read SMART Thresholds failed: %s\n\n", device->get_errmsg());
e9583e0c
GI
2875 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2876 }
2877 else
2878 smart_thres_ok = true;
2879 }
2880 }
832b75ed
GG
2881 }
2882
2883 // Enable/Disable Off-line testing
e9583e0c 2884 bool needupdate = false;
2127e193 2885 if (options.smart_auto_offl_enable) {
832b75ed 2886 if (!isSupportAutomaticTimer(&smartval)){
ee38a438 2887 pout("SMART Automatic Timers not supported\n\n");
832b75ed
GG
2888 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2889 }
e9583e0c 2890 needupdate = smart_val_ok;
2127e193 2891 if (ataEnableAutoOffline(device)){
ee38a438 2892 pout("SMART Enable Automatic Offline failed: %s\n\n", device->get_errmsg());
832b75ed
GG
2893 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2894 }
2895 else
2896 pout("SMART Automatic Offline Testing Enabled every four hours.\n");
2897 }
2127e193
GI
2898
2899 if (options.smart_auto_offl_disable) {
832b75ed 2900 if (!isSupportAutomaticTimer(&smartval)){
ee38a438 2901 pout("SMART Automatic Timers not supported\n\n");
832b75ed
GG
2902 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2903 }
e9583e0c 2904 needupdate = smart_val_ok;
2127e193 2905 if (ataDisableAutoOffline(device)){
ee38a438 2906 pout("SMART Disable Automatic Offline failed: %s\n\n", device->get_errmsg());
832b75ed
GG
2907 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2908 }
2909 else
2910 pout("SMART Automatic Offline Testing Disabled.\n");
2911 }
2912
2127e193 2913 if (needupdate && ataReadSmartValues(device, &smartval)){
ee38a438 2914 pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
832b75ed 2915 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
e9583e0c 2916 smart_val_ok = false;
832b75ed
GG
2917 }
2918
2919 // all this for a newline!
2127e193
GI
2920 if ( options.smart_disable || options.smart_enable
2921 || options.smart_auto_save_disable || options.smart_auto_save_enable
3d17a85c
GI
2922 || options.smart_auto_offl_disable || options.smart_auto_offl_enable
2923 || options.set_aam || options.set_apm || options.set_lookahead
2924 || options.set_wcache || options.set_security_freeze || options.set_standby
2925 || options.sct_wcache_reorder_set)
832b75ed
GG
2926 pout("\n");
2927
2928 // START OF READ-ONLY OPTIONS APART FROM -V and -i
2127e193
GI
2929 if ( options.smart_check_status || options.smart_general_values
2930 || options.smart_vendor_attrib || options.smart_error_log
2931 || options.smart_selftest_log || options.smart_selective_selftest_log
2932 || options.smart_ext_error_log || options.smart_ext_selftest_log
2933 || options.sct_temp_sts || options.sct_temp_hist )
832b75ed
GG
2934 pout("=== START OF READ SMART DATA SECTION ===\n");
2935
e9583e0c 2936 // Check SMART status
2127e193 2937 if (options.smart_check_status) {
e9583e0c
GI
2938
2939 switch (ataSmartStatus2(device)) {
832b75ed
GG
2940
2941 case 0:
2942 // The case where the disk health is OK
2943 pout("SMART overall-health self-assessment test result: PASSED\n");
e9583e0c 2944 if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
2127e193 2945 if (options.smart_vendor_attrib)
832b75ed
GG
2946 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
2947 else {
cfbba5b9 2948 print_on();
832b75ed 2949 pout("Please note the following marginal Attributes:\n");
ee38a438 2950 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 2, options.output_format);
832b75ed
GG
2951 }
2952 returnval|=FAILAGE;
2953 }
2954 else
2955 pout("\n");
2956 break;
2957
2958 case 1:
2959 // The case where the disk health is NOT OK
cfbba5b9 2960 print_on();
832b75ed
GG
2961 pout("SMART overall-health self-assessment test result: FAILED!\n"
2962 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
cfbba5b9 2963 print_off();
e9583e0c 2964 if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
832b75ed 2965 returnval|=FAILATTR;
2127e193 2966 if (options.smart_vendor_attrib)
832b75ed
GG
2967 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
2968 else {
cfbba5b9 2969 print_on();
832b75ed 2970 pout("Failed Attributes:\n");
ee38a438 2971 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 1, options.output_format);
832b75ed
GG
2972 }
2973 }
2974 else
2975 pout("No failed Attributes found.\n\n");
2976 returnval|=FAILSTATUS;
cfbba5b9 2977 print_off();
832b75ed
GG
2978 break;
2979
2980 case -1:
2981 default:
e9583e0c
GI
2982 // Something went wrong with the SMART STATUS command.
2983 // The ATA SMART RETURN STATUS command provides the result in the ATA output
2984 // registers. Buggy ATA/SATA drivers and SAT Layers often do not properly
2985 // return the registers values.
d2e702cf
GI
2986 pout("SMART Status %s: %s\n",
2987 (device->is_syscall_unsup() ? "not supported" : "command failed"),
2988 device->get_errmsg());
e9583e0c 2989 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
d2e702cf 2990
e9583e0c 2991 if (!(smart_val_ok && smart_thres_ok)) {
cfbba5b9 2992 print_on();
e9583e0c
GI
2993 pout("SMART overall-health self-assessment test result: UNKNOWN!\n"
2994 "SMART Status, Attributes and Thresholds cannot be read.\n\n");
2995 }
2996 else if (find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
cfbba5b9 2997 print_on();
832b75ed
GG
2998 pout("SMART overall-health self-assessment test result: FAILED!\n"
2999 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
d2e702cf 3000 pout("Warning: This result is based on an Attribute check.\n");
cfbba5b9 3001 print_off();
832b75ed
GG
3002 returnval|=FAILATTR;
3003 returnval|=FAILSTATUS;
2127e193 3004 if (options.smart_vendor_attrib)
832b75ed
GG
3005 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
3006 else {
cfbba5b9 3007 print_on();
832b75ed 3008 pout("Failed Attributes:\n");
ee38a438 3009 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 1, options.output_format);
832b75ed
GG
3010 }
3011 }
3012 else {
3013 pout("SMART overall-health self-assessment test result: PASSED\n");
e9583e0c
GI
3014 pout("Warning: This result is based on an Attribute check.\n");
3015 if (find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
2127e193 3016 if (options.smart_vendor_attrib)
832b75ed
GG
3017 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
3018 else {
cfbba5b9 3019 print_on();
832b75ed 3020 pout("Please note the following marginal Attributes:\n");
ee38a438 3021 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 2, options.output_format);
832b75ed
GG
3022 }
3023 returnval|=FAILAGE;
3024 }
3025 else
3026 pout("\n");
3027 }
cfbba5b9 3028 print_off();
832b75ed
GG
3029 break;
3030 } // end of switch statement
3031
cfbba5b9 3032 print_off();
832b75ed
GG
3033 } // end of checking SMART Status
3034
3035 // Print general SMART values
e9583e0c 3036 if (smart_val_ok && options.smart_general_values)
ee38a438 3037 PrintGeneralSmartValues(&smartval, &drive, firmwarebugs);
832b75ed
GG
3038
3039 // Print vendor-specific attributes
e9583e0c 3040 if (smart_val_ok && options.smart_vendor_attrib) {
cfbba5b9 3041 print_on();
ee38a438 3042 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm,
a7e8ffec 3043 (printing_is_switchable ? 2 : 0), options.output_format);
cfbba5b9 3044 print_off();
832b75ed
GG
3045 }
3046
cfbba5b9
GI
3047 // If GP Log is supported use smart log directory for
3048 // error and selftest log support check.
3049 if ( isGeneralPurposeLoggingCapable(&drive)
3050 && ( options.smart_error_log || options.smart_selftest_log
3051 || options.retry_error_log || options.retry_selftest_log))
3052 need_smart_logdir = true;
3053
2127e193
GI
3054 ata_smart_log_directory smartlogdir_buf, gplogdir_buf;
3055 const ata_smart_log_directory * smartlogdir = 0, * gplogdir = 0;
3056
cfbba5b9
GI
3057 // Read SMART Log directory
3058 if (need_smart_logdir) {
ee38a438
GI
3059 if (firmwarebugs.is_set(BUG_NOLOGDIR))
3060 smartlogdir = fake_logdir(&smartlogdir_buf, options);
3061 else if (ataReadLogDirectory(device, &smartlogdir_buf, false)) {
3062 pout("Read SMART Log Directory failed: %s\n\n", device->get_errmsg());
cfbba5b9 3063 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2127e193 3064 }
cfbba5b9
GI
3065 else
3066 smartlogdir = &smartlogdir_buf;
3067 }
2127e193 3068
cfbba5b9
GI
3069 // Read GP Log directory
3070 if (need_gp_logdir) {
ee38a438
GI
3071 if (firmwarebugs.is_set(BUG_NOLOGDIR))
3072 gplogdir = fake_logdir(&gplogdir_buf, options);
3073 else if (ataReadLogDirectory(device, &gplogdir_buf, true)) {
3074 pout("Read GP Log Directory failed\n\n");
cfbba5b9 3075 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
832b75ed 3076 }
cfbba5b9
GI
3077 else
3078 gplogdir = &gplogdir_buf;
3079 }
2127e193 3080
cfbba5b9 3081 // Print log directories
ee38a438
GI
3082 if ((options.gp_logdir && gplogdir) || (options.smart_logdir && smartlogdir)) {
3083 if (firmwarebugs.is_set(BUG_NOLOGDIR))
3084 pout("Log Directories not read due to '-F nologdir' option\n\n");
3085 else
3086 PrintLogDirectories(gplogdir, smartlogdir);
3087 }
2127e193 3088
cfbba5b9
GI
3089 // Print log pages
3090 for (i = 0; i < options.log_requests.size(); i++) {
3091 const ata_log_request & req = options.log_requests[i];
2127e193 3092
cfbba5b9
GI
3093 const char * type;
3094 unsigned max_nsectors;
3095 if (req.gpl) {
3096 type = "General Purpose";
3097 max_nsectors = GetNumLogSectors(gplogdir, req.logaddr, true);
3098 }
3099 else {
3100 type = "SMART";
3101 max_nsectors = GetNumLogSectors(smartlogdir, req.logaddr, false);
3102 }
2127e193 3103
cfbba5b9
GI
3104 if (!max_nsectors) {
3105 if (!is_permissive()) {
3106 pout("%s Log 0x%02x does not exist (override with '-T permissive' option)\n", type, req.logaddr);
2127e193
GI
3107 continue;
3108 }
cfbba5b9
GI
3109 max_nsectors = req.page+1;
3110 }
3111 if (max_nsectors <= req.page) {
3112 pout("%s Log 0x%02x has only %u sectors, output skipped\n", type, req.logaddr, max_nsectors);
3113 continue;
3114 }
2127e193 3115
cfbba5b9
GI
3116 unsigned ns = req.nsectors;
3117 if (ns > max_nsectors - req.page) {
3118 if (req.nsectors != ~0U) // "FIRST-max"
3119 pout("%s Log 0x%02x has only %u sectors, output truncated\n", type, req.logaddr, max_nsectors);
3120 ns = max_nsectors - req.page;
3121 }
2127e193 3122
cfbba5b9
GI
3123 // SMART log don't support sector offset, start with first sector
3124 unsigned offs = (req.gpl ? 0 : req.page);
2127e193 3125
cfbba5b9
GI
3126 raw_buffer log_buf((offs + ns) * 512);
3127 bool ok;
3128 if (req.gpl)
3129 ok = ataReadLogExt(device, req.logaddr, 0x00, req.page, log_buf.data(), ns);
3130 else
3131 ok = ataReadSmartLog(device, req.logaddr, log_buf.data(), offs + ns);
3132 if (!ok)
3133 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3134 else
3135 PrintLogPages(type, log_buf.data() + offs*512, req.logaddr, req.page, ns, max_nsectors);
832b75ed 3136 }
2127e193
GI
3137
3138 // Print SMART Extendend Comprehensive Error Log
3139 bool do_smart_error_log = options.smart_error_log;
3140 if (options.smart_ext_error_log) {
3141 bool ok = false;
3142 unsigned nsectors = GetNumLogSectors(gplogdir, 0x03, true);
3143 if (!nsectors)
ee38a438 3144 pout("SMART Extended Comprehensive Error Log (GP Log 0x03) not supported\n\n");
2127e193 3145 else if (nsectors >= 256)
ee38a438 3146 pout("SMART Extended Comprehensive Error Log size %u not supported\n\n", nsectors);
2127e193
GI
3147 else {
3148 raw_buffer log_03_buf(nsectors * 512);
3149 ata_smart_exterrlog * log_03 = (ata_smart_exterrlog *)log_03_buf.data();
ee38a438
GI
3150 if (!ataReadExtErrorLog(device, log_03, nsectors, firmwarebugs)) {
3151 pout("Read SMART Extended Comprehensive Error Log failed\n\n");
2127e193 3152 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
ee38a438 3153 }
2127e193 3154 else {
cfbba5b9
GI
3155 if (PrintSmartExtErrorLog(log_03, nsectors, options.smart_ext_error_log))
3156 returnval |= FAILERR;
2127e193
GI
3157 ok = true;
3158 }
3159 }
3160
3161 if (!ok) {
3162 if (options.retry_error_log)
3163 do_smart_error_log = true;
3164 else if (!do_smart_error_log)
3165 pout("Try '-l [xerror,]error' to read traditional SMART Error Log\n");
3166 }
3167 }
3168
832b75ed 3169 // Print SMART error log
2127e193 3170 if (do_smart_error_log) {
cfbba5b9
GI
3171 if (!( ( smartlogdir && GetNumLogSectors(smartlogdir, 0x01, false))
3172 || (!smartlogdir && isSmartErrorLogCapable(&smartval, &drive) )
3173 || is_permissive() )) {
ee38a438 3174 pout("SMART Error Log not supported\n\n");
832b75ed
GG
3175 }
3176 else {
cfbba5b9 3177 ata_smart_errorlog smarterror; memset(&smarterror, 0, sizeof(smarterror));
ee38a438
GI
3178 if (ataReadErrorLog(device, &smarterror, firmwarebugs)) {
3179 pout("Read SMART Error Log failed: %s\n\n", device->get_errmsg());
cfbba5b9
GI
3180 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3181 }
3182 else {
3183 // quiet mode is turned on inside PrintSmartErrorLog()
ee38a438 3184 if (PrintSmartErrorlog(&smarterror, firmwarebugs))
cfbba5b9
GI
3185 returnval|=FAILERR;
3186 print_off();
3187 }
832b75ed
GG
3188 }
3189 }
2127e193
GI
3190
3191 // Print SMART Extendend Self-test Log
3192 bool do_smart_selftest_log = options.smart_selftest_log;
3193 if (options.smart_ext_selftest_log) {
3194 bool ok = false;
3195 unsigned nsectors = GetNumLogSectors(gplogdir, 0x07, true);
3196 if (!nsectors)
ee38a438 3197 pout("SMART Extended Self-test Log (GP Log 0x07) not supported\n\n");
2127e193 3198 else if (nsectors >= 256)
ee38a438 3199 pout("SMART Extended Self-test Log size %u not supported\n\n", nsectors);
2127e193
GI
3200 else {
3201 raw_buffer log_07_buf(nsectors * 512);
3202 ata_smart_extselftestlog * log_07 = (ata_smart_extselftestlog *)log_07_buf.data();
ee38a438
GI
3203 if (!ataReadExtSelfTestLog(device, log_07, nsectors)) {
3204 pout("Read SMART Extended Self-test Log failed\n\n");
2127e193 3205 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
ee38a438 3206 }
2127e193 3207 else {
cfbba5b9 3208 if (PrintSmartExtSelfTestLog(log_07, nsectors, options.smart_ext_selftest_log))
e9583e0c 3209 returnval |= FAILLOG;
cfbba5b9 3210 ok = true;
2127e193
GI
3211 }
3212 }
3213
3214 if (!ok) {
3215 if (options.retry_selftest_log)
3216 do_smart_selftest_log = true;
3217 else if (!do_smart_selftest_log)
3218 pout("Try '-l [xselftest,]selftest' to read traditional SMART Self Test Log\n");
3219 }
3220 }
3221
832b75ed 3222 // Print SMART self-test log
2127e193 3223 if (do_smart_selftest_log) {
cfbba5b9
GI
3224 if (!( ( smartlogdir && GetNumLogSectors(smartlogdir, 0x06, false))
3225 || (!smartlogdir && isSmartTestLogCapable(&smartval, &drive) )
3226 || is_permissive() )) {
ee38a438 3227 pout("SMART Self-test Log not supported\n\n");
832b75ed
GG
3228 }
3229 else {
cfbba5b9 3230 ata_smart_selftestlog smartselftest; memset(&smartselftest, 0, sizeof(smartselftest));
ee38a438
GI
3231 if (ataReadSelfTestLog(device, &smartselftest, firmwarebugs)) {
3232 pout("Read SMART Self-test Log failed: %s\n\n", device->get_errmsg());
cfbba5b9
GI
3233 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3234 }
3235 else {
3236 print_on();
ee38a438 3237 if (ataPrintSmartSelfTestlog(&smartselftest, !printing_is_switchable, firmwarebugs))
cfbba5b9
GI
3238 returnval |= FAILLOG;
3239 print_off();
3240 pout("\n");
3241 }
832b75ed
GG
3242 }
3243 }
3244
3245 // Print SMART selective self-test log
2127e193
GI
3246 if (options.smart_selective_selftest_log) {
3247 ata_selective_self_test_log log;
3248
832b75ed 3249 if (!isSupportSelectiveSelfTest(&smartval))
ee38a438 3250 pout("Selective Self-tests/Logging not supported\n\n");
2127e193 3251 else if(ataReadSelectiveSelfTestLog(device, &log)) {
ee38a438 3252 pout("Read SMART Selective Self-test Log failed: %s\n\n", device->get_errmsg());
832b75ed
GG
3253 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3254 }
3255 else {
cfbba5b9 3256 print_on();
2127e193
GI
3257 // If any errors were found, they are logged in the SMART Self-test log.
3258 // So there is no need to print the Selective Self Test log in silent
3259 // mode.
cfbba5b9
GI
3260 if (!printing_is_switchable)
3261 ataPrintSelectiveSelfTestLog(&log, &smartval);
3262 print_off();
832b75ed
GG
3263 pout("\n");
3264 }
3265 }
3266
d2e702cf
GI
3267 // Check if SCT commands available
3268 bool sct_ok = isSCTCapable(&drive);
3d17a85c
GI
3269 if(!sct_ok && (options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int
3270 || options.sct_erc_get || options.sct_erc_set ))
3271 pout("SCT Commands not supported\n\n");
7f0798ef 3272
2127e193 3273 // Print SCT status and temperature history table
7f0798ef 3274 if (sct_ok && (options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int)) {
a37e7145 3275 for (;;) {
d2e702cf
GI
3276 bool sct_temp_hist_ok = isSCTDataTableCapable(&drive);
3277 ata_sct_status_response sts;
3278
3279 if (options.sct_temp_sts || (options.sct_temp_hist && sct_temp_hist_ok)) {
3280 // Read SCT status
3281 if (ataReadSCTStatus(device, &sts)) {
3282 pout("\n");
3283 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3284 break;
a37e7145 3285 }
d2e702cf 3286 if (options.sct_temp_sts) {
a37e7145 3287 ataPrintSCTStatus(&sts);
d2e702cf
GI
3288 pout("\n");
3289 }
3290 }
3291
3292 if (!sct_temp_hist_ok && (options.sct_temp_hist || options.sct_temp_int)) {
3293 pout("SCT Data Table command not supported\n\n");
3294 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3295 break;
3296 }
3297
3298 if (options.sct_temp_hist) {
3299 // Read SCT temperature history,
3300 // requires initial SCT status from above
3301 ata_sct_temperature_history_table tmh;
3302 if (ataReadSCTTempHist(device, &tmh, &sts)) {
3303 pout("Read SCT Temperature History failed\n\n");
3304 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3305 break;
3306 }
3307 ataPrintSCTTempHist(&tmh);
a37e7145
GG
3308 pout("\n");
3309 }
d2e702cf 3310
2127e193 3311 if (options.sct_temp_int) {
a37e7145
GG
3312 // Set new temperature logging interval
3313 if (!isSCTFeatureControlCapable(&drive)) {
ee38a438 3314 pout("SCT Feature Control command not supported\n\n");
a37e7145
GG
3315 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3316 break;
3317 }
2127e193 3318 if (ataSetSCTTempInterval(device, options.sct_temp_int, options.sct_temp_int_pers)) {
ee38a438 3319 pout("Write Temperature Logging Interval failed\n\n");
a37e7145
GG
3320 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3321 break;
3322 }
3323 pout("Temperature Logging Interval set to %u minute%s (%s)\n",
2127e193
GI
3324 options.sct_temp_int, (options.sct_temp_int == 1 ? "" : "s"),
3325 (options.sct_temp_int_pers ? "persistent" : "volatile"));
a37e7145
GG
3326 }
3327 break;
3328 }
3329 }
3330
7f0798ef
GI
3331 // SCT Error Recovery Control
3332 if (sct_ok && (options.sct_erc_get || options.sct_erc_set)) {
3333 if (!isSCTErrorRecoveryControlCapable(&drive)) {
ee38a438 3334 pout("SCT Error Recovery Control command not supported\n\n");
7f0798ef
GI
3335 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3336 }
3337 else {
3338 bool sct_erc_get = options.sct_erc_get;
3339 if (options.sct_erc_set) {
3340 // Set SCT Error Recovery Control
3341 if ( ataSetSCTErrorRecoveryControltime(device, 1, options.sct_erc_readtime )
3342 || ataSetSCTErrorRecoveryControltime(device, 2, options.sct_erc_writetime)) {
ee38a438 3343 pout("SCT (Set) Error Recovery Control command failed\n");
cfbba5b9
GI
3344 if (!( (options.sct_erc_readtime == 70 && options.sct_erc_writetime == 70)
3345 || (options.sct_erc_readtime == 0 && options.sct_erc_writetime == 0)))
3346 pout("Retry with: 'scterc,70,70' to enable ERC or 'scterc,0,0' to disable\n");
7f0798ef
GI
3347 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3348 sct_erc_get = false;
3349 }
cfbba5b9
GI
3350 else if (!sct_erc_get)
3351 ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
3352 options.sct_erc_writetime);
7f0798ef
GI
3353 }
3354
3355 if (sct_erc_get) {
3356 // Print SCT Error Recovery Control
3357 unsigned short read_timer, write_timer;
3358 if ( ataGetSCTErrorRecoveryControltime(device, 1, read_timer )
3359 || ataGetSCTErrorRecoveryControltime(device, 2, write_timer)) {
ee38a438 3360 pout("SCT (Get) Error Recovery Control command failed\n");
cfbba5b9 3361 if (options.sct_erc_set) {
7f0798ef 3362 pout("The previous SCT (Set) Error Recovery Control command succeeded\n");
cfbba5b9
GI
3363 ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
3364 options.sct_erc_writetime);
3365 }
7f0798ef
GI
3366 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3367 }
3368 else
cfbba5b9 3369 ataPrintSCTErrorRecoveryControl(false, read_timer, write_timer);
7f0798ef
GI
3370 }
3371 pout("\n");
3372 }
3373 }
3374
d008864d
GI
3375 // Print Device Statistics
3376 if (options.devstat_all_pages || options.devstat_ssd_page || !options.devstat_pages.empty()) {
d2e702cf
GI
3377 bool use_gplog = true;
3378 unsigned nsectors = 0;
3379 if (gplogdir)
3380 nsectors = GetNumLogSectors(gplogdir, 0x04, false);
3381 else if (smartlogdir){ // for systems without ATA_READ_LOG_EXT
3382 nsectors = GetNumLogSectors(smartlogdir, 0x04, false);
3383 use_gplog = false;
3384 }
d008864d 3385 if (!nsectors)
d2e702cf 3386 pout("Device Statistics (GP/SMART Log 0x04) not supported\n\n");
d008864d 3387 else if (!print_device_statistics(device, nsectors, options.devstat_pages,
d2e702cf 3388 options.devstat_all_pages, options.devstat_ssd_page, use_gplog))
d008864d
GI
3389 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3390 }
3391
2127e193
GI
3392 // Print SATA Phy Event Counters
3393 if (options.sataphy) {
bed94269 3394 unsigned nsectors = GetNumLogSectors(gplogdir, 0x11, true);
ee38a438
GI
3395 // Packet interface devices do not provide a log directory, check support bit
3396 if (!nsectors && (drive.words047_079[76-47] & 0x0401) == 0x0400)
3397 nsectors = 1;
bed94269 3398 if (!nsectors)
ee38a438 3399 pout("SATA Phy Event Counters (GP Log 0x11) not supported\n\n");
bed94269 3400 else if (nsectors != 1)
ee38a438 3401 pout("SATA Phy Event Counters with %u sectors not supported\n\n", nsectors);
bed94269
GI
3402 else {
3403 unsigned char log_11[512] = {0, };
3404 unsigned char features = (options.sataphy_reset ? 0x01 : 0x00);
ee38a438
GI
3405 if (!ataReadLogExt(device, 0x11, features, 0, log_11, 1)) {
3406 pout("Read SATA Phy Event Counters failed\n\n");
bed94269 3407 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
ee38a438 3408 }
bed94269
GI
3409 else
3410 PrintSataPhyEventCounters(log_11, options.sataphy_reset);
3411 }
2127e193
GI
3412 }
3413
d008864d
GI
3414 // Set to standby (spindown) mode
3415 // (Above commands may spinup drive)
3416 if (options.set_standby_now) {
3417 if (!ata_nodata_command(device, ATA_STANDBY_IMMEDIATE)) {
3418 pout("ATA STANDBY IMMEDIATE command failed: %s\n", device->get_errmsg());
3419 returnval |= FAILSMART;
3420 }
3421 else
3422 pout("Device placed in STANDBY mode\n");
3423 }
3424
832b75ed 3425 // START OF THE TESTING SECTION OF THE CODE. IF NO TESTING, RETURN
e9583e0c 3426 if (!smart_val_ok || options.smart_selftest_type == -1)
832b75ed
GG
3427 return returnval;
3428
3429 pout("=== START OF OFFLINE IMMEDIATE AND SELF-TEST SECTION ===\n");
3430 // if doing a self-test, be sure it's supported by the hardware
2127e193 3431 switch (options.smart_selftest_type) {
832b75ed
GG
3432 case OFFLINE_FULL_SCAN:
3433 if (!isSupportExecuteOfflineImmediate(&smartval)){
ee38a438 3434 pout("Execute Offline Immediate function not supported\n\n");
832b75ed
GG
3435 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3436 }
3437 break;
3438 case ABORT_SELF_TEST:
3439 case SHORT_SELF_TEST:
3440 case EXTEND_SELF_TEST:
3441 case SHORT_CAPTIVE_SELF_TEST:
3442 case EXTEND_CAPTIVE_SELF_TEST:
3443 if (!isSupportSelfTest(&smartval)){
ee38a438 3444 pout("Self-test functions not supported\n\n");
832b75ed
GG
3445 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3446 }
3447 break;
3448 case CONVEYANCE_SELF_TEST:
3449 case CONVEYANCE_CAPTIVE_SELF_TEST:
3450 if (!isSupportConveyanceSelfTest(&smartval)){
ee38a438 3451 pout("Conveyance Self-test functions not supported\n\n");
832b75ed
GG
3452 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3453 }
3454 break;
3455 case SELECTIVE_SELF_TEST:
3456 case SELECTIVE_CAPTIVE_SELF_TEST:
3457 if (!isSupportSelectiveSelfTest(&smartval)){
ee38a438 3458 pout("Selective Self-test functions not supported\n\n");
832b75ed
GG
3459 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
3460 }
3461 break;
3462 default:
cfbba5b9 3463 break; // Vendor specific type
832b75ed
GG
3464 }
3465
3466 // Now do the test. Note ataSmartTest prints its own error/success
3467 // messages
d008864d
GI
3468 if (ataSmartTest(device, options.smart_selftest_type, options.smart_selftest_force,
3469 options.smart_selective_args, &smartval, sizes.sectors ))
832b75ed
GG
3470 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3471 else {
3472 // Tell user how long test will take to complete. This is tricky
3473 // because in the case of an Offline Full Scan, the completion
3474 // timer is volatile, and needs to be read AFTER the command is
3475 // given. If this will interrupt the Offline Full Scan, we don't
3476 // do it, just warn user.
2127e193 3477 if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
832b75ed
GG
3478 if (isSupportOfflineAbort(&smartval))
3479 pout("Note: giving further SMART commands will abort Offline testing\n");
2127e193 3480 else if (ataReadSmartValues(device, &smartval)){
ee38a438 3481 pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
832b75ed
GG
3482 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3483 }
3484 }
3485
3486 // Now say how long the test will take to complete
e9583e0c
GI
3487 int timewait = TestTime(&smartval, options.smart_selftest_type);
3488 if (timewait) {
832b75ed 3489 time_t t=time(NULL);
2127e193 3490 if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
832b75ed
GG
3491 t+=timewait;
3492 pout("Please wait %d seconds for test to complete.\n", (int)timewait);
3493 } else {
3494 t+=timewait*60;
3495 pout("Please wait %d minutes for test to complete.\n", (int)timewait);
3496 }
3497 pout("Test will complete after %s\n", ctime(&t));
3498
2127e193
GI
3499 if ( options.smart_selftest_type != SHORT_CAPTIVE_SELF_TEST
3500 && options.smart_selftest_type != EXTEND_CAPTIVE_SELF_TEST
3501 && options.smart_selftest_type != CONVEYANCE_CAPTIVE_SELF_TEST
3502 && options.smart_selftest_type != SELECTIVE_CAPTIVE_SELF_TEST )
3503 pout("Use smartctl -X to abort test.\n");
832b75ed
GG
3504 }
3505 }
3506
3507 return returnval;
3508}