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