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