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