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