smartmontools SVN Rev 5474
Utility to control and monitor storage systems with "S.M.A.R.T."
ataprint.cpp
Go to the documentation of this file.
1/*
2 * ataprint.cpp
3 *
4 * Home page of code is: https://www.smartmontools.org
5 *
6 * Copyright (C) 2002-11 Bruce Allen
7 * Copyright (C) 2008-22 Christian Franke
8 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
9 *
10 * SPDX-License-Identifier: GPL-2.0-or-later
11 */
12
13#include "config.h"
14#define __STDC_FORMAT_MACROS 1 // enable PRI* for C++
15
16#include <ctype.h>
17#include <errno.h>
18#include <inttypes.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22
23#include "atacmdnames.h"
24#include "atacmds.h"
25#include "ataidentify.h"
26#include "dev_interface.h"
27#include "ataprint.h"
28#include "smartctl.h"
29#include "sg_unaligned.h"
30#include "utility.h"
31#include "knowndrives.h"
32
33#include "farmcmds.h"
34#include "farmprint.h"
35
36const char * ataprint_cpp_cvsid = "$Id: ataprint.cpp 5462 2023-03-13 10:45:06Z chrfranke $"
38
39
40static const char * infofound(const char *output) {
41 return (*output ? output : "[No Information Found]");
42}
43
44// Return true if '-T permissive' is specified,
45// used to ignore missing capabilities
46static bool is_permissive()
47{
49 return false;
51 return true;
52}
53
54/* For the given Command Register (CR) and Features Register (FR), attempts
55 * to construct a string that describes the contents of the Status
56 * Register (ST) and Error Register (ER). If the meanings of the flags of
57 * the error register are not known for the given command then it returns an
58 * empty string.
59 *
60 * The meanings of the flags of the error register for all commands are
61 * described in the ATA spec and could all be supported here in theory.
62 * Currently, only a few commands are supported (those that have been seen
63 * to produce errors). If many more are to be added then this function
64 * should probably be redesigned.
65 */
66
67static std::string format_st_er_desc(
68 unsigned char CR, unsigned char FR,
69 unsigned char ST, unsigned char ER,
70 unsigned short SC,
71 const ata_smart_errorlog_error_struct * lba28_regs,
72 const ata_smart_exterrlog_error * lba48_regs
73)
74{
75 const char *error_flag[8];
76 int i, print_lba=0, print_sector=0;
77
78 // Set of character strings corresponding to different error codes.
79 // Please keep in alphabetic order if you add more.
80 const char *abrt = "ABRT"; // ABORTED
81 const char *amnf = "AMNF"; // ADDRESS MARK NOT FOUND
82 const char *ccto = "CCTO"; // COMMAND COMPLETION TIMED OUT
83 const char *eom = "EOM"; // END OF MEDIA
84 const char *icrc = "ICRC"; // INTERFACE CRC ERROR
85 const char *idnf = "IDNF"; // ID NOT FOUND
86 const char *ili = "ILI"; // MEANING OF THIS BIT IS COMMAND-SET SPECIFIC
87 const char *mc = "MC"; // MEDIA CHANGED
88 const char *mcr = "MCR"; // MEDIA CHANGE REQUEST
89 const char *nm = "NM"; // NO MEDIA
90 const char *obs = "obs"; // OBSOLETE
91 const char *tk0nf = "TK0NF"; // TRACK 0 NOT FOUND
92 const char *unc = "UNC"; // UNCORRECTABLE
93 const char *wp = "WP"; // WRITE PROTECTED
94
95 /* If for any command the Device Fault flag of the status register is
96 * not used then used_device_fault should be set to 0 (in the CR switch
97 * below)
98 */
99 int uses_device_fault = 1;
100
101 /* A value of NULL means that the error flag isn't used */
102 for (i = 0; i < 8; i++)
103 error_flag[i] = NULL;
104
105 std::string str;
106
107 switch (CR) {
108 case 0x10: // RECALIBRATE
109 error_flag[2] = abrt;
110 error_flag[1] = tk0nf;
111 break;
112 case 0x20: /* READ SECTOR(S) */
113 case 0x21: // READ SECTOR(S)
114 case 0x24: // READ SECTOR(S) EXT
115 case 0xC4: /* READ MULTIPLE */
116 case 0x29: // READ MULTIPLE EXT
117 error_flag[6] = unc;
118 error_flag[5] = mc;
119 error_flag[4] = idnf;
120 error_flag[3] = mcr;
121 error_flag[2] = abrt;
122 error_flag[1] = nm;
123 error_flag[0] = amnf;
124 print_lba=1;
125 break;
126 case 0x22: // READ LONG (with retries)
127 case 0x23: // READ LONG (without retries)
128 error_flag[4] = idnf;
129 error_flag[2] = abrt;
130 error_flag[0] = amnf;
131 print_lba=1;
132 break;
133 case 0x2a: // READ STREAM DMA
134 case 0x2b: // READ STREAM PIO
135 if (CR==0x2a)
136 error_flag[7] = icrc;
137 error_flag[6] = unc;
138 error_flag[5] = mc;
139 error_flag[4] = idnf;
140 error_flag[3] = mcr;
141 error_flag[2] = abrt;
142 error_flag[1] = nm;
143 error_flag[0] = ccto;
144 print_lba=1;
145 print_sector=SC;
146 break;
147 case 0x3A: // WRITE STREAM DMA
148 case 0x3B: // WRITE STREAM PIO
149 if (CR==0x3A)
150 error_flag[7] = icrc;
151 error_flag[6] = wp;
152 error_flag[5] = mc;
153 error_flag[4] = idnf;
154 error_flag[3] = mcr;
155 error_flag[2] = abrt;
156 error_flag[1] = nm;
157 error_flag[0] = ccto;
158 print_lba=1;
159 print_sector=SC;
160 break;
161 case 0x25: // READ DMA EXT
162 case 0x26: // READ DMA QUEUED EXT
163 case 0xC7: // READ DMA QUEUED
164 case 0xC8: // READ DMA (with retries)
165 case 0xC9: // READ DMA (without retries, obsolete since ATA-5)
166 case 0x60: // READ FPDMA QUEUED (NCQ)
167 error_flag[7] = icrc;
168 error_flag[6] = unc;
169 error_flag[5] = mc;
170 error_flag[4] = idnf;
171 error_flag[3] = mcr;
172 error_flag[2] = abrt;
173 error_flag[1] = nm;
174 error_flag[0] = amnf;
175 print_lba=1;
176 if (CR==0x25 || CR==0xC8)
177 print_sector=SC;
178 break;
179 case 0x30: /* WRITE SECTOR(S) */
180 case 0x31: // WRITE SECTOR(S)
181 case 0x34: // WRITE SECTOR(S) EXT
182 case 0xC5: /* WRITE MULTIPLE */
183 case 0x39: // WRITE MULTIPLE EXT
184 case 0xCE: // WRITE MULTIPLE FUA EXT
185 error_flag[6] = wp;
186 error_flag[5] = mc;
187 error_flag[4] = idnf;
188 error_flag[3] = mcr;
189 error_flag[2] = abrt;
190 error_flag[1] = nm;
191 print_lba=1;
192 break;
193 case 0x32: // WRITE LONG (with retries)
194 case 0x33: // WRITE LONG (without retries)
195 error_flag[4] = idnf;
196 error_flag[2] = abrt;
197 print_lba=1;
198 break;
199 case 0x3C: // WRITE VERIFY
200 error_flag[6] = unc;
201 error_flag[4] = idnf;
202 error_flag[2] = abrt;
203 error_flag[0] = amnf;
204 print_lba=1;
205 break;
206 case 0x40: // READ VERIFY SECTOR(S) with retries
207 case 0x41: // READ VERIFY SECTOR(S) without retries
208 case 0x42: // READ VERIFY SECTOR(S) EXT
209 error_flag[6] = unc;
210 error_flag[5] = mc;
211 error_flag[4] = idnf;
212 error_flag[3] = mcr;
213 error_flag[2] = abrt;
214 error_flag[1] = nm;
215 error_flag[0] = amnf;
216 print_lba=1;
217 break;
218 case 0xA0: /* PACKET */
219 /* Bits 4-7 are all used for sense key (a 'command packet set specific error
220 * indication' according to the ATA/ATAPI-7 standard), so "Sense key" will
221 * be repeated in the error description string if more than one of those
222 * bits is set.
223 */
224 error_flag[7] = "Sense key (bit 3)",
225 error_flag[6] = "Sense key (bit 2)",
226 error_flag[5] = "Sense key (bit 1)",
227 error_flag[4] = "Sense key (bit 0)",
228 error_flag[2] = abrt;
229 error_flag[1] = eom;
230 error_flag[0] = ili;
231 break;
232 case 0xA1: /* IDENTIFY PACKET DEVICE */
233 case 0xEF: /* SET FEATURES */
234 case 0x00: /* NOP */
235 case 0xC6: /* SET MULTIPLE MODE */
236 error_flag[2] = abrt;
237 break;
238 case 0x2F: // READ LOG EXT
239 error_flag[6] = unc;
240 error_flag[4] = idnf;
241 error_flag[2] = abrt;
242 error_flag[0] = obs;
243 break;
244 case 0x3F: // WRITE LOG EXT
245 error_flag[4] = idnf;
246 error_flag[2] = abrt;
247 error_flag[0] = obs;
248 break;
249 case 0xB0: /* SMART */
250 switch(FR) {
251 case 0xD0: // SMART READ DATA
252 case 0xD1: // SMART READ ATTRIBUTE THRESHOLDS
253 case 0xD5: /* SMART READ LOG */
254 error_flag[6] = unc;
255 error_flag[4] = idnf;
256 error_flag[2] = abrt;
257 error_flag[0] = obs;
258 break;
259 case 0xD6: /* SMART WRITE LOG */
260 error_flag[4] = idnf;
261 error_flag[2] = abrt;
262 error_flag[0] = obs;
263 break;
264 case 0xD2: // Enable/Disable Attribute Autosave
265 case 0xD3: // SMART SAVE ATTRIBUTE VALUES (ATA-3)
266 case 0xD8: // SMART ENABLE OPERATIONS
267 case 0xD9: /* SMART DISABLE OPERATIONS */
268 case 0xDA: /* SMART RETURN STATUS */
269 case 0xDB: // Enable/Disable Auto Offline (SFF)
270 error_flag[2] = abrt;
271 break;
272 case 0xD4: // SMART EXECUTE IMMEDIATE OFFLINE
273 error_flag[4] = idnf;
274 error_flag[2] = abrt;
275 break;
276 default:
277 return str; // ""
278 break;
279 }
280 break;
281 case 0xB1: /* DEVICE CONFIGURATION */
282 switch (FR) {
283 case 0xC0: /* DEVICE CONFIGURATION RESTORE */
284 error_flag[2] = abrt;
285 break;
286 default:
287 return str; // ""
288 break;
289 }
290 break;
291 case 0xCA: // WRITE DMA (with retries)
292 case 0xCB: // WRITE DMA (without retries, obsolete since ATA-5)
293 case 0x35: // WRITE DMA EXT
294 case 0x3D: // WRITE DMA FUA EXT
295 case 0xCC: // WRITE DMA QUEUED
296 case 0x36: // WRITE DMA QUEUED EXT
297 case 0x3E: // WRITE DMA QUEUED FUA EXT
298 case 0x61: // WRITE FPDMA QUEUED (NCQ)
299 error_flag[7] = icrc;
300 error_flag[6] = wp;
301 error_flag[5] = mc;
302 error_flag[4] = idnf;
303 error_flag[3] = mcr;
304 error_flag[2] = abrt;
305 error_flag[1] = nm;
306 error_flag[0] = amnf;
307 print_lba=1;
308 if (CR==0x35)
309 print_sector=SC;
310 break;
311 case 0xE4: // READ BUFFER
312 case 0xE8: // WRITE BUFFER
313 error_flag[2] = abrt;
314 break;
315 default:
316 return str; // ""
317 }
318
319 /* We ignore any status flags other than Device Fault and Error */
320
321 if (uses_device_fault && (ST & (1 << 5))) {
322 str = "Device Fault";
323 if (ST & 1) // Error flag
324 str += "; ";
325 }
326 if (ST & 1) { // Error flag
327 int count = 0;
328
329 str += "Error: ";
330 for (i = 7; i >= 0; i--)
331 if ((ER & (1 << i)) && (error_flag[i])) {
332 if (count++ > 0)
333 str += ", ";
334 str += error_flag[i];
335 }
336 }
337
338 // If the error was a READ or WRITE error, print the Logical Block
339 // Address (LBA) at which the read or write failed.
340 if (print_lba) {
341 // print number of sectors, if known, and append to print string
342 if (print_sector)
343 str += strprintf(" %d sectors", print_sector);
344
345 if (lba28_regs) {
346 unsigned lba;
347 // bits 24-27: bits 0-3 of DH
348 lba = 0xf & lba28_regs->drive_head;
349 lba <<= 8;
350 // bits 16-23: CH
351 lba |= lba28_regs->cylinder_high;
352 lba <<= 8;
353 // bits 8-15: CL
354 lba |= lba28_regs->cylinder_low;
355 lba <<= 8;
356 // bits 0-7: SN
357 lba |= lba28_regs->sector_number;
358 str += strprintf(" at LBA = 0x%08x = %u", lba, lba);
359 }
360 else if (lba48_regs) {
361 // This assumes that upper LBA registers are 0 for 28-bit commands
362 // (TODO: detect 48-bit commands above)
363 uint64_t lba48;
364 lba48 = lba48_regs->lba_high_register_hi;
365 lba48 <<= 8;
366 lba48 |= lba48_regs->lba_mid_register_hi;
367 lba48 <<= 8;
368 lba48 |= lba48_regs->lba_low_register_hi;
369 lba48 |= lba48_regs->device_register & 0xf;
370 lba48 <<= 8;
371 lba48 |= lba48_regs->lba_high_register;
372 lba48 <<= 8;
373 lba48 |= lba48_regs->lba_mid_register;
374 lba48 <<= 8;
375 lba48 |= lba48_regs->lba_low_register;
376 str += strprintf(" at LBA = 0x%08" PRIx64 " = %" PRIu64, lba48, lba48);
377 }
378 }
379
380 return str;
381}
382
383static inline std::string format_st_er_desc(
385{
386 return format_st_er_desc(
387 data->commands[4].commandreg,
388 data->commands[4].featuresreg,
389 data->error_struct.status,
390 data->error_struct.error_register,
391 data->error_struct.sector_count,
392 &data->error_struct, (const ata_smart_exterrlog_error *)0);
393}
394
395static inline std::string format_st_er_desc(
397{
398 return format_st_er_desc(
399 data->commands[4].command_register,
400 data->commands[4].features_register,
401 data->error.status_register,
402 data->error.error_register,
403 data->error.count_register_hi << 8 | data->error.count_register,
404 (const ata_smart_errorlog_error_struct *)0, &data->error);
405}
406
407
408static const char * get_form_factor(unsigned short word168)
409{
410 // Bits 0:3 are the form factor
411 // Table A.32 of T13/2161-D (ACS-3) Revision 5, October 28, 2013
412 // Table 247 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
413 // Table 254 of T13/BSR INCITS 558 (ACS-5) Revision 10, March 3, 2021
414 switch (word168 & 0xF) {
415 case 0x1: return "5.25 inches";
416 case 0x2: return "3.5 inches";
417 case 0x3: return "2.5 inches";
418 case 0x4: return "1.8 inches";
419 case 0x5: return "< 1.8 inches";
420 case 0x6: return "mSATA"; // ACS-4
421 case 0x7: return "M.2"; // ACS-4
422 case 0x8: return "MicroSSD"; // ACS-4
423 case 0x9: return "CFast"; // ACS-4
424 default : return 0;
425 }
426}
427
428static int find_msb(unsigned short word)
429{
430 for (int bit = 15; bit >= 0; bit--)
431 if (word & (1 << bit))
432 return bit;
433 return -1;
434}
435
436static const char * get_ata_major_version(const ata_identify_device * drive)
437{
438 // Table 13 of T13/1153D (ATA/ATAPI-4) revision 18, August 19, 1998
439 // Table 29 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
440 // Table 55 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
441 // Table 57 of T13/BSR INCITS 558 (ACS-5) Revision 10, March 3, 2021
442 switch (find_msb(drive->major_rev_num)) {
443 case 15: return "ACS >5 (15)";
444 case 14: return "ACS >5 (14)";
445 case 13: return "ACS >5 (13)";
446 case 12: return "ACS-5";
447 case 11: return "ACS-4";
448 case 10: return "ACS-3";
449 case 9: return "ACS-2";
450 case 8: return "ATA8-ACS";
451 case 7: return "ATA/ATAPI-7";
452 case 6: return "ATA/ATAPI-6";
453 case 5: return "ATA/ATAPI-5";
454 case 4: return "ATA/ATAPI-4";
455 case 3: return "ATA-3";
456 case 2: return "ATA-2";
457 case 1: return "ATA-1";
458 default: return 0;
459 }
460}
461
462static const char * get_ata_minor_version(const ata_identify_device * drive)
463{
464 // Table 10 of X3T13/2008D (ATA-3) Revision 7b, January 27, 1997
465 // Table 28 of T13/1410D (ATA/ATAPI-6) Revision 3b, February 26, 2002
466 // Table 31 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
467 // Table 52 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
468 // Table 47 of T13/2161-D (ACS-3) Revision 5, October 28, 2013
469 // Table 57 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
470 // Table 59 of T13/BSR INCITS 558 (ACS-5) Revision 10, March 3, 2021
471 switch (drive->minor_rev_num) {
472 case 0x0001: return "ATA-1 X3T9.2/781D prior to revision 4";
473 case 0x0002: return "ATA-1 published, ANSI X3.221-1994";
474 case 0x0003: return "ATA-1 X3T9.2/781D revision 4";
475 case 0x0004: return "ATA-2 published, ANSI X3.279-1996";
476 case 0x0005: return "ATA-2 X3T10/948D prior to revision 2k";
477 case 0x0006: return "ATA-3 X3T10/2008D revision 1";
478 case 0x0007: return "ATA-2 X3T10/948D revision 2k";
479 case 0x0008: return "ATA-3 X3T10/2008D revision 0";
480 case 0x0009: return "ATA-2 X3T10/948D revision 3";
481 case 0x000a: return "ATA-3 published, ANSI X3.298-1997";
482 case 0x000b: return "ATA-3 X3T10/2008D revision 6"; // 1st ATA-3 revision with SMART
483 case 0x000c: return "ATA-3 X3T13/2008D revision 7 and 7a";
484 case 0x000d: return "ATA/ATAPI-4 X3T13/1153D revision 6";
485 case 0x000e: return "ATA/ATAPI-4 T13/1153D revision 13";
486 case 0x000f: return "ATA/ATAPI-4 X3T13/1153D revision 7";
487 case 0x0010: return "ATA/ATAPI-4 T13/1153D revision 18";
488 case 0x0011: return "ATA/ATAPI-4 T13/1153D revision 15";
489 case 0x0012: return "ATA/ATAPI-4 published, ANSI NCITS 317-1998";
490 case 0x0013: return "ATA/ATAPI-5 T13/1321D revision 3";
491 case 0x0014: return "ATA/ATAPI-4 T13/1153D revision 14";
492 case 0x0015: return "ATA/ATAPI-5 T13/1321D revision 1";
493 case 0x0016: return "ATA/ATAPI-5 published, ANSI NCITS 340-2000";
494 case 0x0017: return "ATA/ATAPI-4 T13/1153D revision 17";
495 case 0x0018: return "ATA/ATAPI-6 T13/1410D revision 0";
496 case 0x0019: return "ATA/ATAPI-6 T13/1410D revision 3a";
497 case 0x001a: return "ATA/ATAPI-7 T13/1532D revision 1";
498 case 0x001b: return "ATA/ATAPI-6 T13/1410D revision 2";
499 case 0x001c: return "ATA/ATAPI-6 T13/1410D revision 1";
500 case 0x001d: return "ATA/ATAPI-7 published, ANSI INCITS 397-2005";
501 case 0x001e: return "ATA/ATAPI-7 T13/1532D revision 0";
502 case 0x001f: return "ACS-3 T13/2161-D revision 3b";
503
504 case 0x0021: return "ATA/ATAPI-7 T13/1532D revision 4a";
505 case 0x0022: return "ATA/ATAPI-6 published, ANSI INCITS 361-2002";
506
507 case 0x0027: return "ATA8-ACS T13/1699-D revision 3c";
508 case 0x0028: return "ATA8-ACS T13/1699-D revision 6";
509 case 0x0029: return "ATA8-ACS T13/1699-D revision 4";
510
511 case 0x0031: return "ACS-2 T13/2015-D revision 2";
512
513 case 0x0033: return "ATA8-ACS T13/1699-D revision 3e";
514
515 case 0x0039: return "ATA8-ACS T13/1699-D revision 4c";
516
517 case 0x0042: return "ATA8-ACS T13/1699-D revision 3f";
518
519 case 0x0052: return "ATA8-ACS T13/1699-D revision 3b";
520
521 case 0x005e: return "ACS-4 T13/BSR INCITS 529 revision 5";
522
523 case 0x006d: return "ACS-3 T13/2161-D revision 5";
524
525 case 0x0082: return "ACS-2 published, ANSI INCITS 482-2012";
526
527 case 0x009c: return "ACS-4 published, ANSI INCITS 529-2018";
528
529 case 0x0107: return "ATA8-ACS T13/1699-D revision 2d";
530
531 case 0x010a: return "ACS-3 published, ANSI INCITS 522-2014";
532
533 case 0x0110: return "ACS-2 T13/2015-D revision 3";
534
535 case 0x011b: return "ACS-3 T13/2161-D revision 4";
536
537 default: return 0;
538 }
539}
540
541static const char * get_pata_version(unsigned short word222, char (& buf)[32])
542{
543 // Table 29 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
544 // Table 57 of T13/BSR INCITS 558 (ACS-5) Revision 10, March 3, 2021
545 switch (word222 & 0x0fff) {
546 default: snprintf(buf, sizeof(buf),
547 "Unknown (0x%03x)", word222 & 0x0fff); return buf;
548 case 0x001:
549 case 0x003: return "ATA8-APT";
550 case 0x002: return "ATA/ATAPI-7";
551 }
552}
553
554static const char * get_sata_version(unsigned short word222)
555{
556 // Table 29 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
557 // Table 50 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
558 // Table 45 of T13/2161-D (ACS-3) Revision 5, October 28, 2013
559 // Table 55 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
560 // Table 57 of T13/BSR INCITS 558 (ACS-5) Revision 10, March 3, 2021
561 switch (find_msb(word222 & 0x0fff)) {
562 case 11: return "SATA >3.5 (11)";
563 case 10: return "SATA 3.5"; // ACS-5
564 case 9: return "SATA 3.4"; // ACS-5
565 case 8: return "SATA 3.3"; // ACS-4
566 case 7: return "SATA 3.2"; // ACS-4
567 case 6: return "SATA 3.1"; // ACS-3
568 case 5: return "SATA 3.0"; // ACS-2
569 case 4: return "SATA 2.6";
570 case 3: return "SATA 2.5";
571 case 2: return "SATA II Ext";
572 case 1: return "SATA 1.0a";
573 case 0: return "ATA8-AST";
574 default: return 0;
575 }
576}
577
578static const char * get_sata_speed(int speed)
579{
580 if (speed <= 0)
581 return 0;
582 // Table 29 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
583 // Table 50 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
584 // Table 45 of T13/2161-D (ACS-3) Revision 5, October 28, 2013
585 // Table 57 of T13/BSR INCITS 558 (ACS-5) Revision 10, March 3, 2021
586 switch (speed) {
587 default: return ">6.0 Gb/s (7)";
588 case 6: return ">6.0 Gb/s (6)";
589 case 5: return ">6.0 Gb/s (5)";
590 case 4: return ">6.0 Gb/s (4)";
591 case 3: return "6.0 Gb/s"; // ACS-3
592 case 2: return "3.0 Gb/s";
593 case 1: return "1.5 Gb/s"; // ATA8-ACS
594 }
595}
596
597static void jset_sata_speed(const char * key, int value, int speed, const char * str)
598{
599 if (speed <= 0)
600 return;
601 json::ref jref = jglb["interface_speed"][key];
602 jref["sata_value"] = value;
603 if (str)
604 jref["string"] = str;
605 int ups;
606 switch (speed) {
607 case 3: ups = 60; break;
608 case 2: ups = 30; break;
609 case 1: ups = 15; break;
610 default: return;
611 }
612 jref["units_per_second"] = ups;
613 jref["bits_per_unit"] = 100000000;
614}
615
616static void print_sata_version_and_speed(unsigned short word222,
617 unsigned short word076,
618 unsigned short word077)
619{
620 int allspeeds = (!(word076 & 0x0001) ? (word076 & 0x00fe) : 0);
621 int maxspeed = (allspeeds ? find_msb(allspeeds) : 0);
622 int curspeed = (!(word077 & 0x0001) ? ((word077 >> 1) & 0x7) : 0);
623
624 const char * verstr = get_sata_version(word222);
625 const char * maxstr = get_sata_speed(maxspeed);
626 const char * curstr = get_sata_speed(curspeed);
627 jout("SATA Version is: %s%s%s%s%s%s\n",
628 (verstr ? verstr : "Unknown"),
629 (maxstr ? ", " : ""), (maxstr ? maxstr : ""),
630 (curstr ? " (current: " : ""), (curstr ? curstr : ""),
631 (curstr ? ")" : ""));
632 if (verstr)
633 jglb["sata_version"]["string"] = verstr;
634 jglb["sata_version"]["value"] = word222 & 0x0fff;
635 jset_sata_speed("max", allspeeds, maxspeed, maxstr);
636 jset_sata_speed("current", curspeed, curspeed, curstr);
637}
638
639static void print_drive_info(const ata_identify_device * drive,
640 const ata_size_info & sizes, int rpm,
641 const drive_settings * dbentry, const char * dbversion)
642{
643 // format drive information (with byte swapping as needed)
644 char model[40+1], serial[20+1], firmware[8+1];
645 ata_format_id_string(model, drive->model, sizeof(model)-1);
646 ata_format_id_string(serial, drive->serial_no, sizeof(serial)-1);
647 ata_format_id_string(firmware, drive->fw_rev, sizeof(firmware)-1);
648
649 // Print model family if known
650 if (dbentry && *dbentry->modelfamily) {
651 jout("Model Family: %s\n", dbentry->modelfamily);
652 jglb["model_family"] = dbentry->modelfamily;
653 }
654
655 jout("Device Model: %s\n", infofound(model));
656 jglb["model_name"] = model;
657
659 jout("Serial Number: %s\n", infofound(serial));
660 jglb["serial_number"] = serial;
661
662 unsigned oui = 0; uint64_t unique_id = 0;
663 int naa = ata_get_wwn(drive, oui, unique_id);
664 if (naa >= 0) {
665 jout("LU WWN Device Id: %x %06x %09" PRIx64 "\n", naa, oui, unique_id);
666 jglb["wwn"]["naa"] = naa;
667 jglb["wwn"]["oui"] = oui;
668 jglb["wwn"]["id"] = unique_id;
669 }
670 }
671
672 // Additional Product Identifier (OEM Id) string in words 170-173
673 // (e08130r1, added in ACS-2 Revision 1, December 17, 2008)
674 if (0x2020 <= drive->words088_255[170-88] && drive->words088_255[170-88] <= 0x7e7e) {
675 char add[8+1];
676 ata_format_id_string(add, (const unsigned char *)(drive->words088_255+(170-88)), sizeof(add)-1);
677 if (add[0]) {
678 jout("Add. Product Id: %s\n", add);
679 jglb["ata_additional_product_id"] = add;
680 }
681 }
682
683 jout("Firmware Version: %s\n", infofound(firmware));
684 jglb["firmware_version"] = firmware;
685
686 if (sizes.capacity) {
687 // Print capacity
688 char num[64], cap[32];
689 jout("User Capacity: %s bytes [%s]\n",
690 format_with_thousands_sep(num, sizeof(num), sizes.capacity),
691 format_capacity(cap, sizeof(cap), sizes.capacity));
692 jglb["user_capacity"]["blocks"].set_unsafe_uint64(sizes.sectors);
693 jglb["user_capacity"]["bytes"].set_unsafe_uint64(sizes.capacity);
694
695 // Print sector sizes.
696 if (sizes.phy_sector_size == sizes.log_sector_size)
697 jout("Sector Size: %u bytes logical/physical\n", sizes.log_sector_size);
698 else {
699 jout("Sector Sizes: %u bytes logical, %u bytes physical",
700 sizes.log_sector_size, sizes.phy_sector_size);
701 if (sizes.log_sector_offset)
702 pout(" (offset %u bytes)", sizes.log_sector_offset);
703 jout("\n");
704 }
705 jglb["logical_block_size"] = sizes.log_sector_size;
706 jglb["physical_block_size"] = sizes.phy_sector_size;
707 }
708
709 // Print nominal media rotation rate if reported
710 if (rpm) {
711 if (rpm == 1)
712 jout("Rotation Rate: Solid State Device\n");
713 else if (rpm > 1)
714 jout("Rotation Rate: %d rpm\n", rpm);
715 else
716 pout("Rotation Rate: Unknown (0x%04x)\n", -rpm);
717 if (rpm > 0)
718 jglb["rotation_rate"] = (rpm == 1 ? 0 : rpm);
719 }
720
721 // Print form factor if reported
722 unsigned short word168 = drive->words088_255[168-88];
723 if (word168) {
724 const char * form_factor = get_form_factor(word168);
725 if (form_factor)
726 jout("Form Factor: %s\n", form_factor);
727 else
728 jout("Form Factor: Unknown (0x%04x)\n", word168);
729 jglb["form_factor"]["ata_value"] = word168;
730 if (form_factor)
731 jglb["form_factor"]["name"] = form_factor;
732 }
733
734 // Print TRIM support
735 bool trim_sup = !!(drive->words088_255[169-88] & 0x0001);
736 unsigned short word069 = drive->words047_079[69-47];
737 bool trim_det = !!(word069 & 0x4000), trim_zeroed = !!(word069 & 0x0020);
738 if (trim_sup || rpm == 1) // HDD: if supported (SMR), SSD: always
739 jout("TRIM Command: %s%s%s\n",
740 (!trim_sup ? "Unavailable" : "Available"),
741 (!(trim_sup && trim_det) ? "" : ", deterministic"),
742 (!(trim_sup && trim_zeroed) ? "" : ", zeroed") );
743 jglb["trim"]["supported"] = trim_sup;
744 if (trim_sup) {
745 jglb["trim"]["deterministic"] = trim_det;
746 jglb["trim"]["zeroed"] = trim_zeroed;
747 }
748
749 // Print Zoned Device Capabilities if reported
750 // (added in ACS-4, obsoleted in ACS-5)
751 unsigned short zoned_caps = word069 & 0x3;
752 if (zoned_caps) {
753 jout("Zoned Device: %s\n",
754 (zoned_caps == 0x1 ? "Host Aware Zones" :
755 zoned_caps == 0x2 ? "Device managed zones" : "Unknown (0x3)"));
756 if (zoned_caps < 0x3)
757 jglb["zoned_device"]["capabilities"] = (zoned_caps == 0x1 ? "host_aware" : "device_managed");
758 }
759
760 // See if drive is recognized
761 jout("Device is: %s%s%s\n",
762 (dbentry ? "In smartctl database" : "Not in smartctl database"),
763 (*dbversion ? " " : ""), (*dbversion ? dbversion : ""));
764 jglb["in_smartctl_database"] = !!dbentry;
765
766 // Print ATA version
767 std::string ataver;
768 if ( (drive->major_rev_num != 0x0000 && drive->major_rev_num != 0xffff)
769 || (drive->minor_rev_num != 0x0000 && drive->minor_rev_num != 0xffff)) {
770 const char * majorver = get_ata_major_version(drive);
771 const char * minorver = get_ata_minor_version(drive);
772
773 if (majorver && minorver && str_starts_with(minorver, majorver)) {
774 // Major and minor strings match, print minor string only
775 ataver = minorver;
776 }
777 else {
778 if (majorver)
779 ataver = majorver;
780 else
781 ataver = strprintf("Unknown(0x%04x)", drive->major_rev_num);
782
783 if (minorver)
784 ataver += strprintf(", %s", minorver);
785 else if (drive->minor_rev_num != 0x0000 && drive->minor_rev_num != 0xffff)
786 ataver += strprintf(" (unknown minor revision code: 0x%04x)", drive->minor_rev_num);
787 else
788 ataver += " (minor revision not indicated)";
789 }
790 }
791 jout("ATA Version is: %s\n", infofound(ataver.c_str()));
792 if (!ataver.empty()) {
793 jglb["ata_version"]["string"] = ataver;
794 jglb["ata_version"]["major_value"] = drive->major_rev_num;
795 jglb["ata_version"]["minor_value"] = drive->minor_rev_num;
796 }
797
798 // Print Transport specific version
799 unsigned short word222 = drive->words088_255[222-88];
800 if (word222 != 0x0000 && word222 != 0xffff) switch (word222 >> 12) {
801 case 0x0: // PATA
802 {
803 char buf[32] = "";
804 pout("Transport Type: Parallel, %s\n", get_pata_version(word222, buf));
805 }
806 break;
807 case 0x1: // SATA
809 drive->words047_079[76-47],
810 drive->words047_079[77-47]);
811 break;
812 case 0xe: // PCIe (ACS-4)
813 pout("Transport Type: PCIe (0x%03x)\n", word222 & 0x0fff);
814 break;
815 default:
816 pout("Transport Type: Unknown (0x%04x)\n", word222);
817 break;
818 }
819
820 jout_startup_datetime("Local Time is: ");
821
822 // Print warning message, if there is one
823 if (dbentry && *dbentry->warningmsg)
824 pout("\n==> WARNING: %s\n\n", dbentry->warningmsg);
825}
826
827static const char *OfflineDataCollectionStatus(unsigned char status_byte)
828{
829 unsigned char stat=status_byte & 0x7f;
830
831 switch(stat){
832 case 0x00:
833 return "was never started";
834 case 0x02:
835 return "was completed without error";
836 case 0x03:
837 if (status_byte == 0x03)
838 return "is in progress";
839 else
840 return "is in a Reserved state";
841 case 0x04:
842 return "was suspended by an interrupting command from host";
843 case 0x05:
844 return "was aborted by an interrupting command from host";
845 case 0x06:
846 return "was aborted by the device with a fatal error";
847 default:
848 if (stat >= 0x40)
849 return "is in a Vendor Specific state";
850 else
851 return "is in a Reserved state";
852 }
853}
854
855
856// prints verbose value Off-line data collection status byte
858{
859 json::ref jref = jglb["ata_smart_data"]["offline_data_collection"]["status"];
860
861 jout("Offline data collection status: (0x%02x)\t",
862 (int)data->offline_data_collection_status);
863 jref["value"] = data->offline_data_collection_status;
864
865 // Off-line data collection status byte is not a reserved
866 // or vendor specific value
867 jout("Offline data collection activity\n"
868 "\t\t\t\t\t%s.\n", OfflineDataCollectionStatus(data->offline_data_collection_status));
869 jref["string"] = OfflineDataCollectionStatus(data->offline_data_collection_status);
870 switch (data->offline_data_collection_status & 0x7f) {
871 case 0x02: jref["passed"] = true; break;
872 case 0x06: jref["passed"] = false; break;
873 }
874
875 // Report on Automatic Data Collection Status. Only IBM documents
876 // this bit. See SFF 8035i Revision 2 for details.
877 if (data->offline_data_collection_status & 0x80)
878 pout("\t\t\t\t\tAuto Offline Data Collection: Enabled.\n");
879 else
880 pout("\t\t\t\t\tAuto Offline Data Collection: Disabled.\n");
881
882 return;
883}
884
886 firmwarebug_defs firmwarebugs)
887{
888 unsigned char status = data->self_test_exec_status;
889 jout("Self-test execution status: ");
890
891 switch (data->self_test_exec_status >> 4) {
892 case 0:
893 jout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t", status);
894 jout("without error or no self-test has ever \n\t\t\t\t\tbeen run.\n");
895 break;
896 case 1:
897 jout("(%4d)\tThe self-test routine was aborted by\n\t\t\t\t\t", status);
898 jout("the host.\n");
899 break;
900 case 2:
901 jout("(%4d)\tThe self-test routine was interrupted\n\t\t\t\t\t", status);
902 jout("by the host with a hard or soft reset.\n");
903 break;
904 case 3:
905 jout("(%4d)\tA fatal error or unknown test error\n\t\t\t\t\t", status);
906 jout("occurred while the device was executing\n\t\t\t\t\t");
907 jout("its self-test routine and the device \n\t\t\t\t\t");
908 jout("was unable to complete the self-test \n\t\t\t\t\t");
909 jout("routine.\n");
910 break;
911 case 4:
912 jout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t", status);
913 jout("a test element that failed and the test\n\t\t\t\t\t");
914 jout("element that failed is not known.\n");
915 break;
916 case 5:
917 jout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t", status);
918 jout("the electrical element of the test\n\t\t\t\t\t");
919 jout("failed.\n");
920 break;
921 case 6:
922 jout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t", status);
923 jout("the servo (and/or seek) element of the \n\t\t\t\t\t");
924 jout("test failed.\n");
925 break;
926 case 7:
927 jout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t", status);
928 jout("the read element of the test failed.\n");
929 break;
930 case 8:
931 jout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t", status);
932 jout("a test element that failed and the\n\t\t\t\t\t");
933 jout("device is suspected of having handling\n\t\t\t\t\t");
934 jout("damage.\n");
935 break;
936 case 15:
937 if (firmwarebugs.is_set(BUG_SAMSUNG3) && data->self_test_exec_status == 0xf0) {
938 pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t", status);
939 pout("with unknown result or self-test in\n\t\t\t\t\t");
940 pout("progress with less than 10%% remaining.\n");
941 }
942 else {
943 jout("(%4d)\tSelf-test routine in progress...\n\t\t\t\t\t", status);
944 jout("%1d0%% of test remaining.\n", status & 0x0f);
945 }
946 break;
947 default:
948 jout("(%4d)\tReserved.\n", status);
949 break;
950 }
951
952 json::ref jref = jglb["ata_smart_data"]["self_test"]["status"];
953
954 jref["value"] = status;
955 const char * msg;
956 // TODO: Use common function for smartctl/smartd
957 switch (status >> 4) {
958 case 0x0: msg = "completed without error"; break;
959 case 0x1: msg = "was aborted by the host"; break;
960 case 0x2: msg = "was interrupted by the host with a reset"; break;
961 case 0x3: msg = "could not complete due to a fatal or unknown error"; break;
962 case 0x4: msg = "completed with error (unknown test element)"; break;
963 case 0x5: msg = "completed with error (electrical test element)"; break;
964 case 0x6: msg = "completed with error (servo/seek test element)"; break;
965 case 0x7: msg = "completed with error (read test element)"; break;
966 case 0x8: msg = "completed with error (handling damage?)"; break;
967 default: msg = 0;
968 }
969 if (msg) {
970 jref["string"] = msg;
971 switch (status >> 4) {
972 case 0x1: case 0x2: case 0x3: break; // aborted -> unknown
973 default: jref["passed"] = ((status >> 4) == 0x0);
974 }
975 }
976 else if ((status >> 4) == 0xf) {
977 jref["string"] = strprintf("in progress, %u0%% remaining", status & 0xf);
978 jref["remaining_percent"] = (status & 0xf) * 10;
979 }
980}
981
983{
984 jout("Total time to complete Offline \n");
985 jout("data collection: \t\t(%5d) seconds.\n",
986 (int)data->total_time_to_complete_off_line);
987
988 jglb["ata_smart_data"]["offline_data_collection"]["completion_seconds"] =
989 data->total_time_to_complete_off_line;
990}
991
993{
994 json::ref jref = jglb["ata_smart_data"]["capabilities"];
995
996 jout("Offline data collection\n");
997 jout("capabilities: \t\t\t (0x%02x) ",
998 (int)data->offline_data_collection_capability);
999 jref["values"][0] = data->offline_data_collection_capability;
1000
1001 if (data->offline_data_collection_capability == 0x00){
1002 jout("\tOffline data collection not supported.\n");
1003 }
1004 else {
1006 "SMART execute Offline immediate." :
1007 "No SMART execute Offline immediate.");
1008 jref["exec_offline_immediate_supported"] = isSupportExecuteOfflineImmediate(data);
1009
1010 // TODO: Bit 1 is vendor specific
1011 pout( "\t\t\t\t\t%s\n", isSupportAutomaticTimer(data)?
1012 "Auto Offline data collection on/off support.":
1013 "No Auto Offline data collection support.");
1014
1015 jout( "\t\t\t\t\t%s\n", isSupportOfflineAbort(data)?
1016 "Abort Offline collection upon new\n\t\t\t\t\tcommand.":
1017 "Suspend Offline collection upon new\n\t\t\t\t\tcommand.");
1018 jref["offline_is_aborted_upon_new_cmd"] = isSupportOfflineAbort(data);
1019
1020 jout( "\t\t\t\t\t%s\n", isSupportOfflineSurfaceScan(data)?
1021 "Offline surface scan supported.":
1022 "No Offline surface scan supported.");
1023 jref["offline_surface_scan_supported"] = isSupportOfflineSurfaceScan(data);
1024
1025 jout( "\t\t\t\t\t%s\n", isSupportSelfTest(data)?
1026 "Self-test supported.":
1027 "No Self-test supported.");
1028 jref["self_tests_supported"] = isSupportSelfTest(data);
1029
1030 jout( "\t\t\t\t\t%s\n", isSupportConveyanceSelfTest(data)?
1031 "Conveyance Self-test supported.":
1032 "No Conveyance Self-test supported.");
1033 jref["conveyance_self_test_supported"] = isSupportConveyanceSelfTest(data);
1034
1035 jout( "\t\t\t\t\t%s\n", isSupportSelectiveSelfTest(data)?
1036 "Selective Self-test supported.":
1037 "No Selective Self-test supported.");
1038 jref["selective_self_test_supported"] = isSupportSelectiveSelfTest(data);
1039 }
1040}
1041
1043{
1044 json::ref jref = jglb["ata_smart_data"]["capabilities"];
1045
1046 jout("SMART capabilities: ");
1047 jout("(0x%04x)\t", (int)data->smart_capability);
1048 jref["values"][1] = data->smart_capability;
1049
1050 if (data->smart_capability == 0x00)
1051 jout("Automatic saving of SMART data\t\t\t\t\tis not implemented.\n");
1052 else {
1053 jout("%s\n", (data->smart_capability & 0x01)?
1054 "Saves SMART data before entering\n\t\t\t\t\tpower-saving mode.":
1055 "Does not save SMART data before\n\t\t\t\t\tentering power-saving mode.");
1056 jref["attribute_autosave_enabled"] = !!(data->smart_capability & 0x01);
1057
1058 // TODO: Info possibly invalid or misleading
1059 // ATA-3 - ATA-5: Bit shall be set
1060 // ATA-6 - ACS-3: Bit shall be set to indicate support for
1061 // SMART ENABLE/DISABLE ATTRIBUTE AUTOSAVE
1062 if (data->smart_capability & 0x02)
1063 pout("\t\t\t\t\tSupports SMART auto save timer.\n");
1064 }
1065}
1066
1068{
1069 bool capable = isSmartErrorLogCapable(data, identity);
1070 jout("Error logging capability: (0x%02x)\tError logging %ssupported.\n",
1071 data->errorlog_capability, (capable ? "" : "NOT "));
1072 jglb["ata_smart_data"]["capabilities"]["error_logging_supported"] = capable;
1073}
1074
1076{
1077 jout("Short self-test routine \n");
1078 if (isSupportSelfTest(data)) {
1079 jout("recommended polling time: \t (%4d) minutes.\n",
1080 (int)data->short_test_completion_time);
1081 jglb["ata_smart_data"]["self_test"]["polling_minutes"]["short"] =
1082 data->short_test_completion_time;
1083 }
1084 else
1085 jout("recommended polling time: \t Not Supported.\n");
1086}
1087
1089{
1090 jout("Extended self-test routine\n");
1091 if (isSupportSelfTest(data)) {
1092 jout("recommended polling time: \t (%4d) minutes.\n",
1094 jglb["ata_smart_data"]["self_test"]["polling_minutes"]["extended"] =
1096 }
1097 else
1098 jout("recommended polling time: \t Not Supported.\n");
1099}
1100
1102{
1103 jout("Conveyance self-test routine\n");
1105 jout("recommended polling time: \t (%4d) minutes.\n",
1106 (int)data->conveyance_test_completion_time);
1107 jglb["ata_smart_data"]["self_test"]["polling_minutes"]["conveyance"] =
1108 data->conveyance_test_completion_time;
1109 }
1110 else
1111 jout("recommended polling time: \t Not Supported.\n");
1112}
1113
1114// Check SMART attribute table for Threshold failure
1115// onlyfailed=0: are or were any age or prefailure attributes <= threshold
1116// onlyfailed=1: are any prefailure attributes <= threshold now
1118 const ata_smart_thresholds_pvt * thresholds,
1119 const ata_vendor_attr_defs & defs, int onlyfailed)
1120{
1121 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
1122 const ata_smart_attribute & attr = data->vendor_attributes[i];
1123
1124 ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs);
1125
1126 if (!onlyfailed) {
1127 if (state >= ATTRSTATE_FAILED_PAST)
1128 return attr.id;
1129 }
1130 else {
1132 return attr.id;
1133 }
1134 }
1135 return 0;
1136}
1137
1138static void set_json_globals_from_smart_attrib(int id, const char * name,
1139 const ata_vendor_attr_defs & defs,
1140 uint64_t rawval)
1141{
1142 switch (id) {
1143 case 9:
1144 if (!str_starts_with(name, "Power_On_"))
1145 return;
1146 {
1147 int minutes = -1;
1148 switch (defs[id].raw_format) {
1149 case RAWFMT_RAW48: case RAWFMT_RAW64:
1151 case RAWFMT_SEC2HOUR: minutes = (rawval / 60) % 60; rawval /= 60*60; break;
1152 case RAWFMT_MIN2HOUR: minutes = rawval % 60; rawval /= 60; break;
1153 case RAWFMT_HALFMIN2HOUR: minutes = (rawval / 2) % 60; rawval /= 2*60; break;
1154 case RAWFMT_DEFAULT: // No database entry:
1155 rawval &= 0xffffffffULL; // ignore milliseconds from RAWFMT_MSEC24_HOUR32
1156 break;
1158 minutes = (int)(rawval >> 32) / (1000*60);
1159 if (minutes >= 60)
1160 minutes = -1;
1161 rawval &= 0xffffffffULL;
1162 break;
1163 default: return;
1164 }
1165 if (rawval > 0x00ffffffULL)
1166 return; // assume bogus value
1167 jglb["power_on_time"]["hours"] = rawval;
1168 if (minutes >= 0)
1169 jglb["power_on_time"]["minutes"] = minutes;
1170 }
1171 break;
1172 case 12:
1173 if (strcmp(name, "Power_Cycle_Count"))
1174 return;
1175 switch (defs[id].raw_format) {
1176 case RAWFMT_DEFAULT: case RAWFMT_RAW48: case RAWFMT_RAW64:
1178 default: return;
1179 }
1180 if (rawval > 0x00ffffffULL)
1181 return; // assume bogus value
1182 jglb["power_cycle_count"] = rawval;
1183 break;
1184 //case 194:
1185 // Temperature set separately from ata_return_temperature_value() below
1186 }
1187}
1188
1189// onlyfailed=0 : print all attribute values
1190// onlyfailed=1: just ones that are currently failed and have prefailure bit set
1191// onlyfailed=2: ones that are failed, or have failed with or without prefailure bit set
1193 const ata_smart_thresholds_pvt * thresholds,
1194 const ata_vendor_attr_defs & defs, int rpm,
1195 int onlyfailed, unsigned char format)
1196{
1197 bool brief = !!(format & ata_print_options::FMT_BRIEF);
1198 bool hexid = !!(format & ata_print_options::FMT_HEX_ID);
1199 bool hexval = !!(format & ata_print_options::FMT_HEX_VAL);
1200 bool needheader = true;
1201
1202 // step through all vendor attributes
1203 for (int i = 0, ji = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
1204 const ata_smart_attribute & attr = data->vendor_attributes[i];
1205
1206 // Check attribute and threshold
1207 unsigned char threshold = 0;
1208 ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs, &threshold);
1209 if (state == ATTRSTATE_NON_EXISTING)
1210 continue;
1211
1212 // These break out of the loop if we are only printing certain entries...
1213 if (onlyfailed == 1 && !(ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) && state == ATTRSTATE_FAILED_NOW))
1214 continue;
1215
1216 if (onlyfailed == 2 && state < ATTRSTATE_FAILED_PAST)
1217 continue;
1218
1219 // print header only if needed
1220 if (needheader) {
1221 if (!onlyfailed) {
1222 jout("SMART Attributes Data Structure revision number: %d\n",(int)data->revnumber);
1223 jglb["ata_smart_attributes"]["revision"] = data->revnumber;
1224 jout("Vendor Specific SMART Attributes with Thresholds:\n");
1225 }
1226 if (!brief)
1227 jout("ID#%s ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE\n",
1228 (!hexid ? "" : " "));
1229 else
1230 jout("ID#%s ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE\n",
1231 (!hexid ? "" : " "));
1232 needheader = false;
1233 }
1234
1235 // Format value, worst, threshold
1236 std::string valstr, worstr, threstr;
1237 if (state > ATTRSTATE_NO_NORMVAL)
1238 valstr = (!hexval ? strprintf("%.3d", attr.current)
1239 : strprintf("0x%02x", attr.current));
1240 else
1241 valstr = (!hexval ? "---" : "----");
1242 if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL))
1243 worstr = (!hexval ? strprintf("%.3d", attr.worst)
1244 : strprintf("0x%02x", attr.worst));
1245 else
1246 worstr = (!hexval ? "---" : "----");
1247 if (state > ATTRSTATE_NO_THRESHOLD)
1248 threstr = (!hexval ? strprintf("%.3d", threshold)
1249 : strprintf("0x%02x", threshold));
1250 else
1251 threstr = (!hexval ? "---" : "----");
1252
1253 // Print line for each valid attribute
1254 std::string idstr = (!hexid ? strprintf("%3d", attr.id)
1255 : strprintf("0x%02x", attr.id));
1256 std::string attrname = ata_get_smart_attr_name(attr.id, defs, rpm);
1257 std::string rawstr = ata_format_attr_raw_value(attr, defs);
1258
1259 char flagstr[] = {
1260 (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? 'P' : '-'),
1261 (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? 'O' : '-'),
1262 (ATTRIBUTE_FLAGS_PERFORMANCE(attr.flags) ? 'S' : '-'),
1263 (ATTRIBUTE_FLAGS_ERRORRATE(attr.flags) ? 'R' : '-'),
1264 (ATTRIBUTE_FLAGS_EVENTCOUNT(attr.flags) ? 'C' : '-'),
1265 (ATTRIBUTE_FLAGS_SELFPRESERVING(attr.flags) ? 'K' : '-'),
1266 (ATTRIBUTE_FLAGS_OTHER(attr.flags) ? '+' : ' '),
1267 0
1268 };
1269
1270 if (!brief)
1271 jout("%s %-24s0x%04x %-4s %-4s %-4s %-10s%-9s%-12s%s\n",
1272 idstr.c_str(), attrname.c_str(), attr.flags,
1273 valstr.c_str(), worstr.c_str(), threstr.c_str(),
1274 (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? "Pre-fail" : "Old_age"),
1275 (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? "Always" : "Offline"),
1276 (state == ATTRSTATE_FAILED_NOW ? "FAILING_NOW" :
1277 state == ATTRSTATE_FAILED_PAST ? "In_the_past"
1278 : " -" ) ,
1279 rawstr.c_str());
1280 else
1281 jout("%s %-24s%s %-4s %-4s %-4s %-5s%s\n",
1282 idstr.c_str(), attrname.c_str(), flagstr,
1283 valstr.c_str(), worstr.c_str(), threstr.c_str(),
1284 (state == ATTRSTATE_FAILED_NOW ? "NOW" :
1285 state == ATTRSTATE_FAILED_PAST ? "Past"
1286 : "-" ),
1287 rawstr.c_str());
1288
1289 if (!jglb.is_enabled())
1290 continue;
1291
1292 json::ref jref = jglb["ata_smart_attributes"]["table"][ji++];
1293 jref["id"] = attr.id;
1294 jref["name"] = attrname;
1295 if (state > ATTRSTATE_NO_NORMVAL)
1296 jref["value"] = attr.current;
1297 if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL))
1298 jref["worst"] = attr.worst;
1299 if (state > ATTRSTATE_NO_THRESHOLD) {
1300 jref["thresh"] = threshold;
1301 jref["when_failed"] = (state == ATTRSTATE_FAILED_NOW ? "now" :
1302 state == ATTRSTATE_FAILED_PAST ? "past"
1303 : "" );
1304 }
1305
1306 json::ref jreff = jref["flags"];
1307 jreff["value"] = attr.flags;
1308 jreff["string"] = flagstr;
1309 jreff["prefailure"] = !!ATTRIBUTE_FLAGS_PREFAILURE(attr.flags);
1310 jreff["updated_online"] = !!ATTRIBUTE_FLAGS_ONLINE(attr.flags);
1311 jreff["performance"] = !!ATTRIBUTE_FLAGS_PERFORMANCE(attr.flags);
1312 jreff["error_rate"] = !!ATTRIBUTE_FLAGS_ERRORRATE(attr.flags);
1313 jreff["event_count"] = !!ATTRIBUTE_FLAGS_EVENTCOUNT(attr.flags);
1314 jreff["auto_keep"] = !!ATTRIBUTE_FLAGS_SELFPRESERVING(attr.flags);
1315 if (ATTRIBUTE_FLAGS_OTHER(attr.flags))
1316 jreff["other"] = ATTRIBUTE_FLAGS_OTHER(attr.flags);
1317
1318 uint64_t rawval = ata_get_attr_raw_value(attr, defs);
1319 jref["raw"]["value"] = rawval;
1320 jref["raw"]["string"] = rawstr;
1321
1322 set_json_globals_from_smart_attrib(attr.id, attrname.c_str(), defs, rawval);
1323 }
1324
1325 if (!needheader) {
1326 if (!onlyfailed && brief) {
1327 int n = (!hexid ? 28 : 29);
1328 jout("%*s||||||_ K auto-keep\n"
1329 "%*s|||||__ C event count\n"
1330 "%*s||||___ R error rate\n"
1331 "%*s|||____ S speed/performance\n"
1332 "%*s||_____ O updated online\n"
1333 "%*s|______ P prefailure warning\n",
1334 n, "", n, "", n, "", n, "", n, "", n, "");
1335 }
1336 pout("\n");
1337 }
1338
1339 if (!jglb.is_enabled())
1340 return;
1341
1342 // Protocol independent temperature
1343 unsigned char t = ata_return_temperature_value(data, defs);
1344 if (t)
1345 jglb["temperature"]["current"] = t;
1346}
1347
1348// Print SMART related SCT capabilities
1350{
1351 unsigned short sctcaps = drive->words088_255[206-88];
1352 if (!(sctcaps & 0x01))
1353 return;
1354 json::ref jref = jglb["ata_sct_capabilities"];
1355 jout("SCT capabilities: \t (0x%04x)\tSCT Status supported.\n", sctcaps);
1356 jref["value"] = sctcaps;
1357 if (sctcaps & 0x08)
1358 jout("\t\t\t\t\tSCT Error Recovery Control supported.\n");
1359 jref["error_recovery_control_supported"] = !!(sctcaps & 0x08);
1360 if (sctcaps & 0x10)
1361 jout("\t\t\t\t\tSCT Feature Control supported.\n");
1362 jref["feature_control_supported"] = !!(sctcaps & 0x10);
1363 if (sctcaps & 0x20)
1364 jout("\t\t\t\t\tSCT Data Table supported.\n");
1365 jref["data_table_supported"] = !!(sctcaps & 0x20);
1366}
1367
1368
1370 firmwarebug_defs firmwarebugs)
1371{
1372 jout("General SMART Values:\n");
1373
1375
1376 if (isSupportSelfTest(data)){
1377 PrintSmartSelfExecStatus(data, firmwarebugs);
1378 }
1379
1383
1385
1386 jout( "\t\t\t\t\t%s\n", isGeneralPurposeLoggingCapable(drive)?
1387 "General Purpose Logging supported.":
1388 "No General Purpose Logging support.");
1389 jglb["ata_smart_data"]["capabilities"]["gp_logging_supported"] =
1391
1392 if (isSupportSelfTest(data)){
1395 }
1398
1399 ataPrintSCTCapability(drive);
1400
1401 jout("\n");
1402}
1403
1404// Get # sectors of a log addr, 0 if log does not exist.
1405static unsigned GetNumLogSectors(const ata_smart_log_directory * logdir, unsigned logaddr, bool gpl)
1406{
1407 if (!logdir)
1408 return 0;
1409 if (logaddr > 0xff)
1410 return 0;
1411 if (logaddr == 0)
1412 return 1;
1413 unsigned n = logdir->entry[logaddr-1].numsectors;
1414 if (gpl)
1415 // GP logs may have >255 sectors
1416 n |= logdir->entry[logaddr-1].reserved << 8;
1417 return n;
1418}
1419
1420// Get name of log.
1421static const char * GetLogName(unsigned logaddr)
1422{
1423 // Table A.2 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
1424 // Table 112 of Serial ATA Revision 3.2, August 7, 2013
1425 // Table A.2 of T13/2161-D (ACS-3) Revision 5, October 28, 2013
1426 // Table 213 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
1427 // Table 213 of T13/BSR INCITS 558 (ACS-5) Revision 10, March 3, 2021
1428 switch (logaddr) {
1429 case 0x00: return "Log Directory";
1430 case 0x01: return "Summary SMART error log";
1431 case 0x02: return "Comprehensive SMART error log";
1432 case 0x03: return "Ext. Comprehensive SMART error log";
1433 case 0x04: return "Device Statistics log";
1434 case 0x05: return "Reserved for CFA"; // ACS-2
1435 case 0x06: return "SMART self-test log"; // OBS-ACS-5
1436 case 0x07: return "Extended self-test log"; // OBS-ACS-5
1437 case 0x08: return "Power Conditions log"; // ACS-2
1438 case 0x09: return "Selective self-test log";
1439 case 0x0a: return "Device Statistics Notification"; // ACS-3
1440 case 0x0b: return "Reserved for CFA"; // ACS-3
1441 case 0x0c: return "Pending Defects log"; // ACS-4
1442 case 0x0d: return "LPS Mis-alignment log"; // ACS-2
1443 case 0x0e: return "Reserved for ZAC-2"; // ACS-4
1444 case 0x0f: return "Sense Data for Successful NCQ Cmds log"; // ACS-4
1445 case 0x10: return "NCQ Command Error log";
1446 case 0x11: return "SATA Phy Event Counters log";
1447 //case 0x12: return "SATA NCQ Queue Management log"; // SATA 3.0/3.1, ACS-3
1448 case 0x12: return "SATA NCQ Non-Data log"; // SATA 3.2, ACS-4
1449 case 0x13: return "SATA NCQ Send and Receive log"; // SATA 3.1, ACS-3
1450 case 0x14: return "Hybrid Information log"; // SATA 3.2, ACS-4
1451 case 0x15: return "Rebuild Assist log"; // SATA 3.2, ACS-4
1452 case 0x16: return "Out Of Band Management Control log"; // ACS-5
1453 case 0x17: return "Reserved for Serial ATA";
1454 case 0x18: return "Command Duration Limits log"; // ACS-5
1455 case 0x19: return "LBA Status log"; // ACS-3
1456
1457 case 0x20: return "Streaming performance log [OBS-8]";
1458 case 0x21: return "Write stream error log";
1459 case 0x22: return "Read stream error log";
1460 case 0x23: return "Delayed sector log [OBS-8]";
1461 case 0x24: return "Current Device Internal Status Data log"; // ACS-3
1462 case 0x25: return "Saved Device Internal Status Data log"; // ACS-3
1463
1464 case 0x2f: return "Set Sector Configuration"; // ACS-4
1465 case 0x30: return "IDENTIFY DEVICE data log"; // ACS-3
1466
1467 case 0x42: return "Mutate Configurations log"; // ACS-5
1468
1469 case 0x47: return "Concurrent Positioning Ranges log"; // ACS-5
1470
1471 case 0x53: return "Sense Data log"; // ACS-5
1472
1473 case 0xe0: return "SCT Command/Status";
1474 case 0xe1: return "SCT Data Transfer";
1475 default:
1476 if (0xa0 <= logaddr && logaddr <= 0xdf)
1477 return "Device vendor specific log";
1478 if (0x80 <= logaddr && logaddr <= 0x9f)
1479 return "Host vendor specific log";
1480 return "Reserved";
1481 }
1482 /*NOTREACHED*/
1483}
1484
1485// Get log access permissions
1486static const char * get_log_rw(unsigned logaddr)
1487{
1488 if ( ( logaddr <= 0x08)
1489 || (0x0c <= logaddr && logaddr <= 0x0d)
1490 || (0x0f <= logaddr && logaddr <= 0x14)
1491 || (0x19 == logaddr)
1492 || (0x20 <= logaddr && logaddr <= 0x25)
1493 || (0x30 == logaddr)
1494 || (0x42 == logaddr)
1495 || (0x47 == logaddr)
1496 || (0x53 == logaddr))
1497 return "R/O";
1498
1499 if ( ( logaddr <= 0x0a)
1500 || (0x15 <= logaddr && logaddr <= 0x16)
1501 || (0x18 == logaddr)
1502 || (0x80 <= logaddr && logaddr <= 0x9f)
1503 || (0xe0 <= logaddr && logaddr <= 0xe1))
1504 return "R/W";
1505
1506 if (0xa0 <= logaddr && logaddr <= 0xdf)
1507 return "VS"; // Vendor specific
1508
1509 return "-"; // Unknown/Reserved
1510}
1511
1512// Init a fake log directory, assume that standard logs are supported
1514 const ata_print_options & options)
1515{
1516 memset(logdir, 0, sizeof(*logdir));
1517 logdir->logversion = 255;
1518 logdir->entry[0x01-1].numsectors = 1;
1519 logdir->entry[0x03-1].numsectors = (options.smart_ext_error_log + (4-1)) / 4;
1520 logdir->entry[0x04-1].numsectors = 8;
1521 logdir->entry[0x06-1].numsectors = 1;
1522 logdir->entry[0x07-1].numsectors = (options.smart_ext_selftest_log + (19-1)) / 19;
1523 logdir->entry[0x09-1].numsectors = 1;
1524 logdir->entry[0x11-1].numsectors = 1;
1525 return logdir;
1526}
1527
1528// Print SMART and/or GP Log Directory
1530 const ata_smart_log_directory * smartlogdir)
1531{
1532 json::ref jref = jglb["ata_log_directory"];
1533 if (gplogdir) {
1534 jout("General Purpose Log Directory Version %u\n", gplogdir->logversion);
1535 jref["gp_dir_version"] = gplogdir->logversion;
1536 }
1537 if (smartlogdir) {
1538 jout("SMART %sLog Directory Version %u%s\n",
1539 (gplogdir ? " " : ""), smartlogdir->logversion,
1540 (smartlogdir->logversion==1 ? " [multi-sector log support]" : ""));
1541 jref["smart_dir_version"] = smartlogdir->logversion;
1542 jref["smart_dir_multi_sector"] = (smartlogdir->logversion == 1);
1543 }
1544
1545 jout("Address Access R/W Size Description\n");
1546
1547 for (unsigned i = 0, ji = 0; i <= 0xff; i++) {
1548 // Get number of sectors
1549 unsigned smart_numsect = GetNumLogSectors(smartlogdir, i, false);
1550 unsigned gp_numsect = GetNumLogSectors(gplogdir , i, true );
1551
1552 if (!(smart_numsect || gp_numsect))
1553 continue; // Log does not exist
1554
1555 const char * acc; unsigned size;
1556 if (smart_numsect == gp_numsect) {
1557 acc = "GPL,SL"; size = gp_numsect;
1558 }
1559 else if (!smart_numsect) {
1560 acc = "GPL"; size = gp_numsect;
1561 }
1562 else if (!gp_numsect) {
1563 acc = " SL"; size = smart_numsect;
1564 }
1565 else {
1566 acc = 0; size = 0;
1567 }
1568
1569 unsigned i2 = i;
1570 if (acc && ((0x80 <= i && i < 0x9f) || (0xa0 <= i && i < 0xdf))) {
1571 // Find range of Host/Device vendor specific logs with same size
1572 unsigned imax = (i < 0x9f ? 0x9f : 0xdf);
1573 for (unsigned j = i+1; j <= imax; j++) {
1574 unsigned sn = GetNumLogSectors(smartlogdir, j, false);
1575 unsigned gn = GetNumLogSectors(gplogdir , j, true );
1576
1577 if (!(sn == smart_numsect && gn == gp_numsect))
1578 break;
1579 i2 = j;
1580 }
1581 }
1582
1583 const char * name = GetLogName(i);
1584 const char * rw = get_log_rw(i);
1585
1586 if (i2 > i)
1587 jout("0x%02x-0x%02x %-6s %-3s %5u %s\n", i, i2, acc, rw, size, name);
1588 else if (acc)
1589 jout( "0x%02x %-6s %-3s %5u %s\n", i, acc, rw, size, name);
1590 else {
1591 // GPL and SL support different sizes
1592 jout( "0x%02x %-6s %-3s %5u %s\n", i, "GPL", rw, gp_numsect, name);
1593 jout( "0x%02x %-6s %-3s %5u %s\n", i, "SL", rw, smart_numsect, name);
1594 }
1595
1596 for (;;) {
1597 json::ref jrefi = jref["table"][ji++];
1598 jrefi["address"] = i;
1599 jrefi["name"] = name;
1600 if (rw[0] == 'R' && rw[1] && rw[2]) {
1601 jrefi["read"] = true;
1602 jrefi["write"] = (rw[2] == 'W');
1603 }
1604 if (gp_numsect)
1605 jrefi["gp_sectors"] = gp_numsect;
1606 if (smart_numsect)
1607 jrefi["smart_sectors"] = smart_numsect;
1608 if (i >= i2)
1609 break;
1610 i++;
1611 }
1612 }
1613 jout("\n");
1614}
1615
1616// Print hexdump of log pages.
1617// Format is compatible with 'xxd -r'.
1618static void PrintLogPages(const char * type, const unsigned char * data,
1619 unsigned char logaddr, unsigned page,
1620 unsigned num_pages, unsigned max_pages)
1621{
1622 pout("%s Log 0x%02x [%s], Page %u-%u (of %u)\n",
1623 type, logaddr, GetLogName(logaddr), page, page+num_pages-1, max_pages);
1624 for (unsigned i = 0; i < num_pages * 512; i += 16) {
1625 const unsigned char * p = data+i;
1626 pout("%07x: %02x %02x %02x %02x %02x %02x %02x %02x "
1627 "%02x %02x %02x %02x %02x %02x %02x %02x ",
1628 (page * 512) + i,
1629 p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
1630 p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15]);
1631#define P(n) (' ' <= p[n] && p[n] <= '~' ? (int)p[n] : '.')
1632 pout("|%c%c%c%c%c%c%c%c"
1633 "%c%c%c%c%c%c%c%c|\n",
1634 P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
1635 P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15));
1636#undef P
1637 if ((i & 0x1ff) == 0x1f0)
1638 pout("\n");
1639 }
1640}
1641
1642///////////////////////////////////////////////////////////////////////
1643// Device statistics (Log 0x04)
1644
1645// Section A.5 of T13/2161-D (ACS-3) Revision 5, October 28, 2013
1646// Section 9.5 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
1647
1649{
1650 short size; // #bytes of value, -1 for signed char
1651 const char * name;
1652};
1653
1655 { 2, "List of supported log pages" },
1656 { 0, 0 }
1657};
1658
1660 { 2, "General Statistics" },
1661 { 4, "Lifetime Power-On Resets" },
1662 { 4, "Power-on Hours" },
1663 { 6, "Logical Sectors Written" },
1664 { 6, "Number of Write Commands" },
1665 { 6, "Logical Sectors Read" },
1666 { 6, "Number of Read Commands" },
1667 { 6, "Date and Time TimeStamp" }, // ACS-3
1668 { 4, "Pending Error Count" }, // ACS-4
1669 { 2, "Workload Utilization" }, // ACS-4
1670 { 6, "Utilization Usage Rate" }, // ACS-4 (TODO: 47:40: Validity, 39:36 Basis, 7:0 Usage rate)
1671 { 7, "Resource Availability" }, // ACS-4 (TODO: 55:16 Resources, 15:0 Fraction)
1672 { 1, "Random Write Resources Used" }, // ACS-4
1673 { 0, 0 }
1674};
1675
1677 { 2, "Free-Fall Statistics" },
1678 { 4, "Number of Free-Fall Events Detected" },
1679 { 4, "Overlimit Shock Events" },
1680 { 0, 0 }
1681};
1682
1684 { 2, "Rotating Media Statistics" },
1685 { 4, "Spindle Motor Power-on Hours" },
1686 { 4, "Head Flying Hours" },
1687 { 4, "Head Load Events" },
1688 { 4, "Number of Reallocated Logical Sectors" },
1689 { 4, "Read Recovery Attempts" },
1690 { 4, "Number of Mechanical Start Failures" },
1691 { 4, "Number of Realloc. Candidate Logical Sectors" }, // ACS-3
1692 { 4, "Number of High Priority Unload Events" }, // ACS-3
1693 { 0, 0 }
1694};
1695
1697 { 2, "General Errors Statistics" },
1698 { 4, "Number of Reported Uncorrectable Errors" },
1699//{ 4, "Number of Resets Between Command Acceptance and Command Completion" },
1700 { 4, "Resets Between Cmd Acceptance and Completion" },
1701 { 4, "Physical Element Status Changed" }, // ACS-4
1702 { 0, 0 }
1703};
1704
1706 { 2, "Temperature Statistics" },
1707 { -1, "Current Temperature" },
1708 { -1, "Average Short Term Temperature" },
1709 { -1, "Average Long Term Temperature" },
1710 { -1, "Highest Temperature" },
1711 { -1, "Lowest Temperature" },
1712 { -1, "Highest Average Short Term Temperature" },
1713 { -1, "Lowest Average Short Term Temperature" },
1714 { -1, "Highest Average Long Term Temperature" },
1715 { -1, "Lowest Average Long Term Temperature" },
1716 { 4, "Time in Over-Temperature" },
1717 { -1, "Specified Maximum Operating Temperature" },
1718 { 4, "Time in Under-Temperature" },
1719 { -1, "Specified Minimum Operating Temperature" },
1720 { 0, 0 }
1721};
1722
1724 { 2, "Transport Statistics" },
1725 { 4, "Number of Hardware Resets" },
1726 { 4, "Number of ASR Events" },
1727 { 4, "Number of Interface CRC Errors" },
1728 { 0, 0 }
1729};
1730
1732 { 2, "Solid State Device Statistics" },
1733 { 1, "Percentage Used Endurance Indicator" },
1734 { 0, 0 }
1735};
1736
1746 // TODO: 0x08 Zoned Device Statistics (T13/f16136r7, January 2017)
1747 // TODO: 0x09 Command Duration Limits Statistics (ACS-5 Revision 10, March 2021)
1748};
1749
1750const int num_devstat_infos = sizeof(devstat_infos)/sizeof(devstat_infos[0]);
1751
1752static const char * get_device_statistics_page_name(int page)
1753{
1754 if (page < num_devstat_infos)
1755 return devstat_infos[page][0].name;
1756 if (page == 0xff)
1757 return "Vendor Specific Statistics"; // ACS-4
1758 return "Unknown Statistics";
1759}
1760
1761static void set_json_globals_from_device_statistics(int page, int offset, int64_t val)
1762{
1763 switch (page) {
1764 case 1:
1765 switch (offset) {
1766 case 0x008: jglb["power_cycle_count"] = val; break; // ~= Lifetime Power-On Resets
1767 case 0x010: jglb["power_on_time"]["hours"]= val; break;
1768 }
1769 break;
1770 case 5:
1771 switch (offset) {
1772 case 0x008: jglb["temperature"]["current"] = val; break;
1773 case 0x020: jglb["temperature"]["lifetime_max"] = val; break;
1774 case 0x028: jglb["temperature"]["lifetime_min"] = val; break;
1775 case 0x050: jglb["temperature"]["lifetime_over_limit_minutes"] = val; break;
1776 case 0x058: jglb["temperature"]["op_limit_max"] = val; break;
1777 case 0x060: jglb["temperature"]["lifetime_under_limit_minutes"] = val; break;
1778 case 0x068: jglb["temperature"]["op_limit_min"] = val; break;
1779 }
1780 break;
1781 }
1782}
1783
1784static void print_device_statistics_page(const json::ref & jref, const unsigned char * data, int page)
1785{
1786 const devstat_entry_info * info = (page < num_devstat_infos ? devstat_infos[page] : 0);
1787 const char * name = get_device_statistics_page_name(page);
1788
1789 // Check page number in header
1790 static const char line[] = " ===== = = === == ";
1791 if (!data[2]) {
1792 pout("0x%02x%s%s (empty) ==\n", page, line, name);
1793 return;
1794 }
1795 if (data[2] != page) {
1796 pout("0x%02x%s%s (invalid page 0x%02x in header) ==\n", page, line, name, data[2]);
1797 return;
1798 }
1799
1800 int rev = data[0] | (data[1] << 8);
1801 jout("0x%02x%s%s (rev %d) ==\n", page, line, name, rev);
1802 jref["number"] = page;
1803 jref["name"] = name;
1804 jref["revision"] = rev;
1805
1806 // Print entries
1807 int ji = 0;
1808 for (int i = 1, offset = 8; offset < 512-7; i++, offset+=8) {
1809 // Check for last known entry
1810 if (info && !info[i].size)
1811 info = 0;
1812
1813 // Skip unsupported entries
1814 unsigned char flags = data[offset+7];
1815 if (!(flags & 0x80))
1816 continue;
1817
1818 // Stop if unknown entries contain garbage data due to buggy firmware
1819 if (!info && (data[offset+5] || data[offset+6])) {
1820 pout("0x%02x 0x%03x - - [Trailing garbage ignored]\n", page, offset);
1821 break;
1822 }
1823
1824 // Get value name
1825 const char * valname = (info ? info[i].name :
1826 (page == 0xff) ? "Vendor Specific" // ACS-4
1827 : "Unknown" );
1828
1829 // Get value size, default to max if unknown
1830 int size = (info ? info[i].size : 7);
1831
1832 // Get flags (supported flag already checked above)
1833 bool valid = !!(flags & 0x40);
1834 bool normalized = !!(flags & 0x20);
1835 bool supports_dsn = !!(flags & 0x10); // ACS-3
1836 bool monitored_condition_met = !!(flags & 0x08); // ACS-3
1837 unsigned char reserved_flags = (flags & 0x07);
1838
1839 // Format value
1840 int64_t val = 0;
1841 char valstr[32];
1842 if (valid) {
1843 // Get value
1844 if (size < 0) {
1845 val = (signed char)data[offset];
1846 }
1847 else {
1848 for (int j = 0; j < size; j++)
1849 val |= (int64_t)data[offset+j] << (j*8);
1850 }
1851 snprintf(valstr, sizeof(valstr), "%" PRId64, val);
1852 }
1853 else {
1854 // Value not known (yet)
1855 valstr[0] = '-'; valstr[1] = 0;
1856 }
1857
1858 char flagstr[] = {
1859 (valid ? 'V' : '-'), // JSON only
1860 (normalized ? 'N' : '-'),
1861 (supports_dsn ? 'D' : '-'),
1862 (monitored_condition_met ? 'C' : '-'),
1863 (reserved_flags ? '+' : ' '),
1864 0
1865 };
1866
1867 jout("0x%02x 0x%03x %d %15s %s %s\n",
1868 page, offset, abs(size), valstr, flagstr+1, valname);
1869
1870 if (!jglb.is_enabled())
1871 continue;
1872
1873 json::ref jrefi = jref["table"][ji++];
1874 jrefi["offset"] = offset;
1875 jrefi["name"] = valname;
1876 jrefi["size"] = abs(size);
1877 if (valid)
1878 jrefi["value"] = val; // TODO: May be unsafe JSON int if size > 6
1879
1880 json::ref jreff = jrefi["flags"];
1881 jreff["value"] = flags;
1882 jreff["string"] = flagstr;
1883 jreff["valid"] = valid;
1884 jreff["normalized"] = normalized;
1885 jreff["supports_dsn"] = supports_dsn;
1886 jreff["monitored_condition_met"] = monitored_condition_met;
1887 if (reserved_flags)
1888 jreff["other"] = reserved_flags;
1889
1890 if (valid)
1891 set_json_globals_from_device_statistics(page, offset, val);
1892 }
1893}
1894
1895static bool print_device_statistics(ata_device * device, unsigned nsectors,
1896 const std::vector<int> & single_pages, bool all_pages, bool ssd_page,
1897 bool use_gplog)
1898{
1899 // Read list of supported pages from page 0
1900 unsigned char page_0[512] = {0, };
1901 int rc;
1902
1903 if (use_gplog)
1904 rc = ataReadLogExt(device, 0x04, 0, 0, page_0, 1);
1905 else
1906 rc = ataReadSmartLog(device, 0x04, page_0, 1);
1907 if (!rc) {
1908 jerr("Read Device Statistics page 0x00 failed\n\n");
1909 return false;
1910 }
1911
1912 unsigned char nentries = page_0[8];
1913 if (!(page_0[2] == 0 && nentries > 0)) {
1914 jerr("Device Statistics page 0x00 is invalid (page=0x%02x, nentries=%d)\n\n", page_0[2], nentries);
1915 return false;
1916 }
1917
1918 // Prepare list of pages to print
1919 std::vector<int> pages;
1920 unsigned i;
1921 if (all_pages) {
1922 // Add all supported pages
1923 for (i = 0; i < nentries; i++) {
1924 int page = page_0[8+1+i];
1925 if (page)
1926 pages.push_back(page);
1927 }
1928 ssd_page = false;
1929 }
1930 // Add manually specified pages
1931 bool print_page_0 = false;
1932 for (i = 0; i < single_pages.size() || ssd_page; i++) {
1933 int page = (i < single_pages.size() ? single_pages[i] : 0x07);
1934 if (!page)
1935 print_page_0 = true;
1936 else if (page >= (int)nsectors)
1937 pout("Device Statistics Log has only 0x%02x pages\n", nsectors);
1938 else
1939 pages.push_back(page);
1940 if (page == 0x07)
1941 ssd_page = false;
1942 }
1943
1944 json::ref jref = jglb["ata_device_statistics"];
1945
1946 // Print list of supported pages if requested
1947 if (print_page_0) {
1948 pout("Device Statistics (%s Log 0x04) supported pages\n",
1949 use_gplog ? "GP" : "SMART");
1950 jout("Page Description\n");
1951 for (i = 0; i < nentries; i++) {
1952 int page = page_0[8+1+i];
1953 const char * name = get_device_statistics_page_name(page);
1954 jout("0x%02x %s\n", page, name);
1955 jref["supported_pages"][i]["number"] = page;
1956 jref["supported_pages"][i]["name"] = name;
1957 }
1958 jout("\n");
1959 }
1960
1961 // Read & print pages
1962 if (!pages.empty()) {
1963 pout("Device Statistics (%s Log 0x04)\n",
1964 use_gplog ? "GP" : "SMART");
1965 jout("Page Offset Size Value Flags Description\n");
1966 int max_page = 0;
1967
1968 if (!use_gplog)
1969 for (i = 0; i < pages.size(); i++) {
1970 int page = pages[i];
1971 if (max_page < page && page < 0xff)
1972 max_page = page;
1973 }
1974
1975 raw_buffer pages_buf((max_page+1) * 512);
1976
1977 if (!use_gplog && !ataReadSmartLog(device, 0x04, pages_buf.data(), max_page+1)) {
1978 jerr("Read Device Statistics pages 0x00-0x%02x failed\n\n", max_page);
1979 return false;
1980 }
1981
1982 int ji = 0;
1983 for (i = 0; i < pages.size(); i++) {
1984 int page = pages[i];
1985 if (use_gplog) {
1986 if (!ataReadLogExt(device, 0x04, 0, page, pages_buf.data(), 1)) {
1987 jerr("Read Device Statistics page 0x%02x failed\n\n", page);
1988 return false;
1989 }
1990 }
1991 else if (page > max_page)
1992 continue;
1993
1994 int offset = (use_gplog ? 0 : page * 512);
1995 print_device_statistics_page(jref["pages"][ji++], pages_buf.data() + offset, page);
1996 }
1997
1998 jout("%32s|||_ C monitored condition met\n", "");
1999 jout("%32s||__ D supports DSN\n", "");
2000 jout("%32s|___ N normalized value\n\n", "");
2001 }
2002
2003 return true;
2004}
2005
2006
2007///////////////////////////////////////////////////////////////////////
2008// Pending Defects log (Log 0x0c)
2009
2010// Section 9.26 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
2011
2012static bool print_pending_defects_log(ata_device * device, unsigned nsectors,
2013 unsigned max_entries)
2014{
2015 // Read #entries from page 0
2016 unsigned char page_buf[512] = {0, };
2017 if (!ataReadLogExt(device, 0x0c, 0, 0, page_buf, 1)) {
2018 pout("Read Pending Defects log page 0x00 failed\n\n");
2019 return false;
2020 }
2021
2022 jout("Pending Defects log (GP Log 0x0c)\n");
2023 unsigned nentries = sg_get_unaligned_le32(page_buf);
2024 json::ref jref = jglb["ata_pending_defects_log"];
2025 jref["size"] = nsectors * 32 - 1;
2026 jref["count"] = nentries;
2027 if (!nentries) {
2028 jout("No Defects Logged\n\n");
2029 return true;
2030 }
2031
2032 // Print entries
2033 jout("Index LBA Hours\n");
2034 for (unsigned i = 0, pi = 1, page = 0; i < nentries && i < max_entries; i++, pi++) {
2035 // Read new page if required
2036 if (pi >= 32) {
2037 if (++page >= nsectors) {
2038 pout("Pending Defects count %u exceeds log size (#pages=%u)\n\n",
2039 nentries, nsectors);
2040 return false;
2041 }
2042 if (!ataReadLogExt(device, 0x0c, 0, page, page_buf, 1)) {
2043 pout("Read Pending Defects log page 0x%02x failed\n\n", page);
2044 return false;
2045 }
2046 pi = 0;
2047 }
2048
2049 const unsigned char * entry = page_buf + 16 * pi;
2050 unsigned hours = sg_get_unaligned_le32(entry);
2051 char hourstr[32];
2052 if (hours != 0xffffffffU)
2053 snprintf(hourstr, sizeof(hourstr), "%u", hours);
2054 else
2055 hourstr[0] = '-', hourstr[1] = 0;
2056 uint64_t lba = sg_get_unaligned_le64(entry + 8);
2057 jout("%5u %18" PRIu64 " %8s\n", i, lba, hourstr);
2058
2059 json::ref jrefi = jref["table"][i];
2060 jrefi["lba"].set_unsafe_uint64(lba);
2061 if (hours != 0xffffffffU)
2062 jrefi["power_on_hours"] = hours;
2063 }
2064
2065 if (nentries > max_entries)
2066 pout("... (%u entries not shown)\n", nentries - max_entries);
2067 jout("\n");
2068 return true;
2069}
2070
2071
2072///////////////////////////////////////////////////////////////////////
2073
2074// Print log 0x11
2075static void PrintSataPhyEventCounters(const unsigned char * data, bool reset)
2076{
2077 if (checksum(data))
2078 checksumwarning("SATA Phy Event Counters");
2079 jout("SATA Phy Event Counters (GP Log 0x11)\n");
2080 if (data[0] || data[1] || data[2] || data[3])
2081 pout("[Reserved: 0x%02x 0x%02x 0x%02x 0x%02x]\n",
2082 data[0], data[1], data[2], data[3]);
2083 jout("ID Size Value Description\n");
2084
2085 for (unsigned i = 4, ji = 0; ; ) {
2086 // Get counter id and size (bits 14:12)
2087 unsigned id = data[i] | (data[i+1] << 8);
2088 unsigned size = ((id >> 12) & 0x7) << 1;
2089 id &= 0x8fff;
2090
2091 // End of counter table ?
2092 if (!id)
2093 break;
2094 i += 2;
2095
2096 if (!(2 <= size && size <= 8 && i + size < 512)) {
2097 pout("0x%04x %u: Invalid entry\n", id, size);
2098 break;
2099 }
2100
2101 // Get value
2102 uint64_t val = 0, max_val = 0;
2103 for (unsigned j = 0; j < size; j+=2) {
2104 val |= (uint64_t)(data[i+j] | (data[i+j+1] << 8)) << (j*8);
2105 max_val |= (uint64_t)0xffffU << (j*8);
2106 }
2107 i += size;
2108
2109 // Get name
2110 const char * name;
2111 switch (id) {
2112 case 0x001: name = "Command failed due to ICRC error"; break; // Mandatory
2113 case 0x002: name = "R_ERR response for data FIS"; break;
2114 case 0x003: name = "R_ERR response for device-to-host data FIS"; break;
2115 case 0x004: name = "R_ERR response for host-to-device data FIS"; break;
2116 case 0x005: name = "R_ERR response for non-data FIS"; break;
2117 case 0x006: name = "R_ERR response for device-to-host non-data FIS"; break;
2118 case 0x007: name = "R_ERR response for host-to-device non-data FIS"; break;
2119 case 0x008: name = "Device-to-host non-data FIS retries"; break;
2120 case 0x009: name = "Transition from drive PhyRdy to drive PhyNRdy"; break;
2121 case 0x00A: name = "Device-to-host register FISes sent due to a COMRESET"; break; // Mandatory
2122 case 0x00B: name = "CRC errors within host-to-device FIS"; break;
2123 case 0x00D: name = "Non-CRC errors within host-to-device FIS"; break;
2124 case 0x00F: name = "R_ERR response for host-to-device data FIS, CRC"; break;
2125 case 0x010: name = "R_ERR response for host-to-device data FIS, non-CRC"; break;
2126 case 0x012: name = "R_ERR response for host-to-device non-data FIS, CRC"; break;
2127 case 0x013: name = "R_ERR response for host-to-device non-data FIS, non-CRC"; break;
2128 default: name = ((id & 0x8000) ? "Vendor specific" : "Unknown"); break;
2129 }
2130
2131 // Counters stop at max value, add '+' in this case
2132 jout("0x%04x %u %12" PRIu64 "%c %s\n", id, size, val,
2133 (val == max_val ? '+' : ' '), name);
2134
2135 json::ref jref = jglb["sata_phy_event_counters"]["table"][ji++];
2136 jref["id"] = id;
2137 jref["name"] = name;
2138 jref["size"] = size;
2139 jref["value"] = val;
2140 jref["overflow"] = (val == max_val);
2141 }
2142 if (reset)
2143 jout("All counters reset\n");
2144 jout("\n");
2145 jglb["sata_phy_event_counters"]["reset"] = reset;
2146}
2147
2148// Format milliseconds from error log entry as "DAYS+H:M:S.MSEC"
2149static std::string format_milliseconds(unsigned msec)
2150{
2151 unsigned days = msec / 86400000U;
2152 msec -= days * 86400000U;
2153 unsigned hours = msec / 3600000U;
2154 msec -= hours * 3600000U;
2155 unsigned min = msec / 60000U;
2156 msec -= min * 60000U;
2157 unsigned sec = msec / 1000U;
2158 msec -= sec * 1000U;
2159
2160 std::string str;
2161 if (days)
2162 str = strprintf("%2ud+", days);
2163 str += strprintf("%02u:%02u:%02u.%03u", hours, min, sec, msec);
2164 return str;
2165}
2166
2167// Get description for 'state' value from SMART Error Logs
2168static const char * get_error_log_state_desc(unsigned state)
2169{
2170 state &= 0x0f;
2171 switch (state){
2172 case 0x0: return "in an unknown state";
2173 case 0x1: return "sleeping";
2174 case 0x2: return "in standby mode";
2175 case 0x3: return "active or idle";
2176 case 0x4: return "doing SMART Offline or Self-test";
2177 default:
2178 return (state < 0xb ? "in a reserved state"
2179 : "in a vendor specific state");
2180 }
2181}
2182
2183// returns number of errors
2185 firmwarebug_defs firmwarebugs)
2186{
2187 json::ref jref = jglb["ata_smart_error_log"]["summary"];
2188 jout("SMART Error Log Version: %d\n", (int)data->revnumber);
2189 jref["revision"] = data->revnumber;
2190
2191 // if no errors logged, return
2192 if (!data->error_log_pointer){
2193 jout("No Errors Logged\n\n");
2194 jref["count"] = 0;
2195 return 0;
2196 }
2197 print_on();
2198 // If log pointer out of range, return
2199 if (data->error_log_pointer>5){
2200 pout("Invalid Error Log index = 0x%02x (valid range is from 1 to 5)\n",
2201 data->error_log_pointer);
2202 pout("ATA Error Count: %d (possibly also invalid)\n\n", data->ata_error_count);
2203 return 0;
2204 }
2205
2206 // Some internal consistency checking of the data structures
2207 if ((data->ata_error_count-data->error_log_pointer) % 5 && !firmwarebugs.is_set(BUG_SAMSUNG2)) {
2208 pout("Warning: ATA error count %d inconsistent with error log pointer %d\n\n",
2209 data->ata_error_count,data->error_log_pointer);
2210 }
2211
2212 // starting printing error log info
2213 if (data->ata_error_count<=5)
2214 jout( "ATA Error Count: %d\n", (int)data->ata_error_count);
2215 else
2216 jout( "ATA Error Count: %d (device log contains only the most recent five errors)\n",
2217 (int)data->ata_error_count);
2218 jref["count"] = data->ata_error_count;
2219 jref["logged_count"] = (data->ata_error_count <= 5 ? data->ata_error_count : 5);
2220
2221 print_off();
2222 jout("\tCR = Command Register [HEX]\n"
2223 "\tFR = Features Register [HEX]\n"
2224 "\tSC = Sector Count Register [HEX]\n"
2225 "\tSN = Sector Number Register [HEX]\n"
2226 "\tCL = Cylinder Low Register [HEX]\n"
2227 "\tCH = Cylinder High Register [HEX]\n"
2228 "\tDH = Device/Head Register [HEX]\n"
2229 "\tDC = Device Command Register [HEX]\n"
2230 "\tER = Error register [HEX]\n"
2231 "\tST = Status register [HEX]\n"
2232 "Powered_Up_Time is measured from power on, and printed as\n"
2233 "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
2234 "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
2235
2236 // now step through the five error log data structures (table 39 of spec)
2237 for (int k = 4, ji = 0; k >= 0; k--) {
2238
2239 // The error log data structure entries are a circular buffer
2240 int i = (data->error_log_pointer + k) % 5;
2241 const ata_smart_errorlog_struct * elog = data->errorlog_struct+i;
2242 const ata_smart_errorlog_error_struct * summary = &(elog->error_struct);
2243
2244 // Spec says: unused error log structures shall be zero filled
2245 if (nonempty(elog, sizeof(*elog))){
2246 // Table 57 of T13/1532D Volume 1 Revision 3
2247 const char *msgstate = get_error_log_state_desc(summary->state);
2248 int days = (int)summary->timestamp/24;
2249
2250 // See table 42 of ATA5 spec
2251 print_on();
2252 jout("Error %d occurred at disk power-on lifetime: %d hours (%d days + %d hours)\n",
2253 (int)(data->ata_error_count+k-4), (int)summary->timestamp, days, (int)(summary->timestamp-24*days));
2254 print_off();
2255
2256 json::ref jrefi = jref["table"][ji++];
2257 jrefi["error_number"] = data->ata_error_count + k - 4;
2258 jrefi["lifetime_hours"] = summary->timestamp;
2259
2260 jout(" When the command that caused the error occurred, the device was %s.\n\n", msgstate);
2261 jout(" After command completion occurred, registers were:\n"
2262 " ER ST SC SN CL CH DH\n"
2263 " -- -- -- -- -- -- --\n"
2264 " %02x %02x %02x %02x %02x %02x %02x",
2265 (int)summary->error_register,
2266 (int)summary->status,
2267 (int)summary->sector_count,
2268 (int)summary->sector_number,
2269 (int)summary->cylinder_low,
2270 (int)summary->cylinder_high,
2271 (int)summary->drive_head);
2272
2273 {
2274 json::ref jrefir = jrefi["completion_registers"];
2275 jrefir["error"] = summary->error_register;
2276 jrefir["status"] = summary->status;
2277 jrefir["count"] = summary->sector_count;
2278 jrefir["lba"] = (summary->sector_number )
2279 | (summary->cylinder_low << 8)
2280 | (summary->cylinder_high << 16);
2281 jrefir["device"] = summary->drive_head;
2282 }
2283
2284 // Add a description of the contents of the status and error registers
2285 // if possible
2286 std::string st_er_desc = format_st_er_desc(elog);
2287 if (!st_er_desc.empty()) {
2288 jout(" %s", st_er_desc.c_str());
2289 jrefi["error_description"] = st_er_desc;
2290 }
2291 jout("\n\n");
2292 jout(" Commands leading to the command that caused the error were:\n"
2293 " CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name\n"
2294 " -- -- -- -- -- -- -- -- ---------------- --------------------\n");
2295 for (int j = 4, jj = 0; j >= 0; j--) {
2296 const ata_smart_errorlog_command_struct * thiscommand = elog->commands+j;
2297
2298 // Spec says: unused data command structures shall be zero filled
2299 if (nonempty(thiscommand, sizeof(*thiscommand))) {
2300 const char * atacmd = look_up_ata_command(thiscommand->commandreg, thiscommand->featuresreg);
2301 jout(" %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
2302 (int)thiscommand->commandreg,
2303 (int)thiscommand->featuresreg,
2304 (int)thiscommand->sector_count,
2305 (int)thiscommand->sector_number,
2306 (int)thiscommand->cylinder_low,
2307 (int)thiscommand->cylinder_high,
2308 (int)thiscommand->drive_head,
2309 (int)thiscommand->devicecontrolreg,
2310 format_milliseconds(thiscommand->timestamp).c_str(),
2311 atacmd);
2312
2313 json::ref jrefic = jrefi["previous_commands"][jj++];
2314 json::ref jreficr = jrefic["registers"];
2315 jreficr["command"] = thiscommand->commandreg;
2316 jreficr["features"] = thiscommand->featuresreg,
2317 jreficr["count"] = thiscommand->sector_count;
2318 jreficr["lba"] = (thiscommand->sector_number )
2319 | (thiscommand->cylinder_low << 8)
2320 | (thiscommand->cylinder_high << 16);
2321 jreficr["device"] = thiscommand->drive_head;
2322 jreficr["device_control"] = thiscommand->devicecontrolreg;
2323 jrefic["powerup_milliseconds"] = thiscommand->timestamp;
2324 jrefic["command_name"] = atacmd;
2325 }
2326 }
2327 jout("\n");
2328 }
2329 }
2330 print_on();
2332 pout("\n");
2333 print_off();
2334 return data->ata_error_count;
2335}
2336
2337// Print SMART Extended Comprehensive Error Log (GP Log 0x03)
2339 const firmwarebug_defs & firmwarebugs,
2340 const ata_smart_exterrlog * log,
2341 unsigned nsectors, unsigned max_errors)
2342{
2343 json::ref jref = jglb["ata_smart_error_log"]["extended"];
2344 jout("SMART Extended Comprehensive Error Log Version: %u (%u sectors)\n",
2345 log->version, nsectors);
2346 jref["revision"] = log->version;
2347 jref["sectors"] = nsectors;
2348
2349 if (!log->device_error_count) {
2350 jout("No Errors Logged\n\n");
2351 jref["count"] = 0;
2352 return 0;
2353 }
2354 print_on();
2355
2356 // Check index
2357 unsigned nentries = nsectors * 4;
2358 unsigned erridx = log->error_log_index;
2359 if (!(1 <= erridx && erridx <= nentries)){
2360 // Some Samsung disks (at least SP1614C/SW100-25, HD300LJ/ZT100-12) use the
2361 // former index from Summary Error Log (byte 1, now reserved) and set byte 2-3
2362 // to 0.
2363 if (!(erridx == 0 && 1 <= log->reserved1 && log->reserved1 <= nentries)) {
2364 pout("Invalid Error Log index = 0x%04x (reserved = 0x%02x)\n", erridx, log->reserved1);
2365 pout("Device Error Count: %d (possibly also invalid)\n\n", log->device_error_count);
2366 return 0;
2367 }
2368 pout("Invalid Error Log index = 0x%04x, trying reserved byte (0x%02x) instead\n", erridx, log->reserved1);
2369 erridx = log->reserved1;
2370 }
2371
2372 // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
2373 // it is 1-based in practice.
2374 erridx--;
2375
2376 // Calculate #errors to print
2377 unsigned errcnt = log->device_error_count;
2378
2379 if (errcnt <= nentries)
2380 jout("Device Error Count: %u\n", log->device_error_count);
2381 else {
2382 errcnt = nentries;
2383 jout("Device Error Count: %u (device log contains only the most recent %u errors)\n",
2384 log->device_error_count, errcnt);
2385 }
2386 jref["count"] = log->device_error_count;
2387 jref["logged_count"] = errcnt;
2388
2389 if (max_errors < errcnt)
2390 errcnt = max_errors;
2391
2392 print_off();
2393 jout("\tCR = Command Register\n"
2394 "\tFEATR = Features Register\n"
2395 "\tCOUNT = Count (was: Sector Count) Register\n"
2396 "\tLBA_48 = Upper bytes of LBA High/Mid/Low Registers ] ATA-8\n"
2397 "\tLH = LBA High (was: Cylinder High) Register ] LBA\n"
2398 "\tLM = LBA Mid (was: Cylinder Low) Register ] Register\n"
2399 "\tLL = LBA Low (was: Sector Number) Register ]\n"
2400 "\tDV = Device (was: Device/Head) Register\n"
2401 "\tDC = Device Control Register\n"
2402 "\tER = Error register\n"
2403 "\tST = Status register\n"
2404 "Powered_Up_Time is measured from power on, and printed as\n"
2405 "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
2406 "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
2407
2408 // Recently read log page
2409 ata_smart_exterrlog log_buf;
2410 unsigned log_buf_page = ~0;
2411
2412 // Iterate through circular buffer in reverse direction
2413 for (unsigned i = 0, errnum = log->device_error_count;
2414 i < errcnt; i++, errnum--, erridx = (erridx > 0 ? erridx - 1 : nentries - 1)) {
2415
2416 // Read log page if needed
2417 const ata_smart_exterrlog * log_p;
2418 unsigned page = erridx / 4;
2419 if (page == 0)
2420 log_p = log;
2421 else {
2422 if (page != log_buf_page) {
2423 memset(&log_buf, 0, sizeof(log_buf));
2424 if (!ataReadExtErrorLog(device, &log_buf, page, 1, firmwarebugs))
2425 break;
2426 log_buf_page = page;
2427 }
2428 log_p = &log_buf;
2429 }
2430
2431 const ata_smart_exterrlog_error_log & entry = log_p->error_logs[erridx % 4];
2432
2433 json::ref jrefi = jref["table"][i];
2434 jrefi["error_number"] = errnum;
2435 jrefi["log_index"] = erridx;
2436
2437 // Skip unused entries
2438 if (!nonempty(&entry, sizeof(entry))) {
2439 jout("Error %u [%u] log entry is empty\n", errnum, erridx);
2440 continue;
2441 }
2442
2443 // Print error information
2444 print_on();
2445 const ata_smart_exterrlog_error & err = entry.error;
2446 jout("Error %u [%u] occurred at disk power-on lifetime: %u hours (%u days + %u hours)\n",
2447 errnum, erridx, err.timestamp, err.timestamp / 24, err.timestamp % 24);
2448 print_off();
2449 jrefi["lifetime_hours"] = err.timestamp;
2450
2451 const char * msgstate = get_error_log_state_desc(err.state);
2452 jout(" When the command that caused the error occurred, the device was %s.\n\n", msgstate);
2453 jrefi["device_state"]["value"] = err.state;
2454 jrefi["device_state"]["string"] = msgstate;
2455
2456 // Print registers
2457 jout(" After command completion occurred, registers were:\n"
2458 " ER -- ST COUNT LBA_48 LH LM LL DV DC\n"
2459 " -- -- -- == -- == == == -- -- -- -- --\n"
2460 " %02x -- %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
2461 err.error_register,
2462 err.status_register,
2464 err.count_register,
2469 err.lba_mid_register,
2470 err.lba_low_register,
2471 err.device_register,
2473
2474 {
2475 json::ref jrefir = jrefi["completion_registers"];
2476 jrefir["error"] = err.error_register;
2477 jrefir["status"] = err.status_register,
2478 jrefir["count"] = (err.count_register_hi << 8) | err.count_register;
2479 jrefir["lba"] = ((uint64_t)err.lba_high_register_hi << 40)
2480 | ((uint64_t)err.lba_mid_register_hi << 32)
2481 | ((uint64_t)err.lba_low_register_hi << 24)
2482 | ((unsigned)err.lba_high_register << 16)
2483 | ((unsigned)err.lba_mid_register << 8)
2484 | ((unsigned)err.lba_low_register );
2485 jrefir["device"] = err.device_register;
2486 jrefir["device_control"] = err.device_control_register;
2487 }
2488
2489 // Add a description of the contents of the status and error registers
2490 // if possible
2491 std::string st_er_desc = format_st_er_desc(&entry);
2492 if (!st_er_desc.empty()) {
2493 jout(" %s", st_er_desc.c_str());
2494 jrefi["error_description"] = st_er_desc;
2495 }
2496 jout("\n\n");
2497
2498 // Print command history
2499 jout(" Commands leading to the command that caused the error were:\n"
2500 " CR FEATR COUNT LBA_48 LH LM LL DV DC Powered_Up_Time Command/Feature_Name\n"
2501 " -- == -- == -- == == == -- -- -- -- -- --------------- --------------------\n");
2502 for (int ci = 4, cji = 0; ci >= 0; ci--) {
2503 const ata_smart_exterrlog_command & cmd = entry.commands[ci];
2504
2505 // Skip unused entries
2506 if (!nonempty(&cmd, sizeof(cmd)))
2507 continue;
2508
2509 // Print registers, timestamp and ATA command name
2510 const char * atacmd = look_up_ata_command(cmd.command_register, cmd.features_register);
2511 jout(" %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
2512 cmd.command_register,
2513 cmd.features_register_hi,
2514 cmd.features_register,
2515 cmd.count_register_hi,
2516 cmd.count_register,
2517 cmd.lba_high_register_hi,
2518 cmd.lba_mid_register_hi,
2519 cmd.lba_low_register_hi,
2520 cmd.lba_high_register,
2521 cmd.lba_mid_register,
2522 cmd.lba_low_register,
2523 cmd.device_register,
2524 cmd.device_control_register,
2525 format_milliseconds(cmd.timestamp).c_str(),
2526 atacmd);
2527
2528 json::ref jrefic = jrefi["previous_commands"][cji++];
2529 json::ref jreficr = jrefic["registers"];
2530 jreficr["command"] = cmd.command_register;
2531 jreficr["features"] = (cmd.features_register_hi << 8) | cmd.features_register;
2532 jreficr["count"] = (cmd.count_register_hi << 8) | cmd.count_register;
2533 jreficr["lba"] = ((uint64_t)cmd.lba_high_register_hi << 40)
2534 | ((uint64_t)cmd.lba_mid_register_hi << 32)
2535 | ((uint64_t)cmd.lba_low_register_hi << 24)
2536 | ((unsigned)cmd.lba_high_register << 16)
2537 | ((unsigned)cmd.lba_mid_register << 8)
2538 | ((unsigned)cmd.lba_low_register );
2539 jreficr["device"] = cmd.device_register;
2540 jreficr["device_control"] = cmd.device_control_register;
2541 jrefic["powerup_milliseconds"] = cmd.timestamp;
2542 jrefic["command_name"] = atacmd;
2543 }
2544 jout("\n");
2545 }
2546
2547 print_on();
2549 pout("\n");
2550 print_off();
2551 return log->device_error_count;
2552}
2553
2554// Print one self-test log entry.
2555// Returns:
2556// -1: self-test failed
2557// 1: extended self-test completed without error
2558// 0: otherwise
2560 unsigned testnum, unsigned char test_type,
2561 unsigned char test_status,
2562 unsigned short timestamp,
2563 uint64_t failing_lba,
2564 bool print_error_only, bool & print_header)
2565{
2566 // Check status and type for return value
2567 int retval = 0;
2568 switch (test_status >> 4) {
2569 case 0x0:
2570 if ((test_type & 0x7f) == 0x02)
2571 retval = 1; // extended self-test completed without error
2572 break;
2573 case 0x3: case 0x4:
2574 case 0x5: case 0x6:
2575 case 0x7: case 0x8:
2576 retval = -1; // self-test failed
2577 break;
2578 }
2579
2580 if (retval >= 0 && print_error_only)
2581 return retval;
2582
2583 std::string msgtest;
2584 switch (test_type) {
2585 case 0x00: msgtest = "Offline"; break;
2586 case 0x01: msgtest = "Short offline"; break;
2587 case 0x02: msgtest = "Extended offline"; break;
2588 case 0x03: msgtest = "Conveyance offline"; break;
2589 case 0x04: msgtest = "Selective offline"; break;
2590 case 0x7f: msgtest = "Abort offline test"; break;
2591 case 0x81: msgtest = "Short captive"; break;
2592 case 0x82: msgtest = "Extended captive"; break;
2593 case 0x83: msgtest = "Conveyance captive"; break;
2594 case 0x84: msgtest = "Selective captive"; break;
2595 default:
2596 if ((0x40 <= test_type && test_type <= 0x7e) || 0x90 <= test_type)
2597 msgtest = strprintf("Vendor (0x%02x)", test_type);
2598 else
2599 msgtest = strprintf("Reserved (0x%02x)", test_type);
2600 }
2601
2602 std::string msgstat;
2603 switch (test_status >> 4) {
2604 case 0x0: msgstat = "Completed without error"; break;
2605 case 0x1: msgstat = "Aborted by host"; break;
2606 case 0x2: msgstat = "Interrupted (host reset)"; break;
2607 case 0x3: msgstat = "Fatal or unknown error"; break;
2608 case 0x4: msgstat = "Completed: unknown failure"; break;
2609 case 0x5: msgstat = "Completed: electrical failure"; break;
2610 case 0x6: msgstat = "Completed: servo/seek failure"; break;
2611 case 0x7: msgstat = "Completed: read failure"; break;
2612 case 0x8: msgstat = "Completed: handling damage??"; break;
2613 case 0xf: msgstat = "Self-test routine in progress"; break;
2614 default: msgstat = strprintf("Unknown status (0x%x)", test_status >> 4);
2615 }
2616
2617 // Print header once
2618 if (print_header) {
2619 print_header = false;
2620 jout("Num Test_Description Status Remaining LifeTime(hours) LBA_of_first_error\n");
2621 }
2622
2623 char msglba[32];
2624 if (retval < 0 && failing_lba < 0xffffffffffffULL)
2625 snprintf(msglba, sizeof(msglba), "%" PRIu64, failing_lba);
2626 else {
2627 msglba[0] = '-'; msglba[1] = 0;
2628 }
2629
2630 jout("#%2u %-19s %-29s %1d0%% %8u %s\n", testnum,
2631 msgtest.c_str(), msgstat.c_str(), test_status & 0x0f, timestamp, msglba);
2632
2633 jref["type"]["value"] = test_type;
2634 jref["type"]["string"] = msgtest;
2635
2636 jref["status"]["value"] = test_status;
2637 jref["status"]["string"] = msgstat;
2638 if (test_status & 0x0f)
2639 jref["status"]["remaining_percent"] = (test_status & 0x0f) * 10;
2640 switch (test_status >> 4) {
2641 case 0x1: case 0x2: case 0x3: break; // aborted -> unknown
2642 default: jref["status"]["passed"] = (retval >= 0);
2643 }
2644
2645 jref["lifetime_hours"] = timestamp;
2646
2647 if (retval < 0 && failing_lba < 0xffffffffffffULL)
2648 jref["lba"] = failing_lba;
2649
2650 return retval;
2651}
2652
2653// Print SMART Self-test log, return error count
2654static int ataPrintSmartSelfTestlog(const ata_smart_selftestlog * log, bool allentries,
2655 firmwarebug_defs firmwarebugs)
2656{
2657 json::ref jref = jglb["ata_smart_self_test_log"]["standard"];
2658
2659 if (allentries)
2660 jout("SMART Self-test log structure revision number %d\n", log->revnumber);
2661 jref["revision"] = log->revnumber;
2662 if (log->revnumber != 0x0001 && allentries && !firmwarebugs.is_set(BUG_SAMSUNG))
2663 pout("Warning: ATA Specification requires self-test log structure revision number = 1\n");
2664 if (!log->mostrecenttest){
2665 if (allentries)
2666 jout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n");
2667 jref["count"] = 0;
2668 return 0;
2669 }
2670
2671 bool noheaderprinted = true;
2672 int errcnt = 0, igncnt = 0;
2673 int testnum = 1, ext_ok_testnum = -1;
2674
2675 // Iterate through circular buffer in reverse direction
2676 for (int i = 20, ji = 0; i >= 0; i--) {
2677 int j = (i + log->mostrecenttest) % 21;
2679
2680 // Skip unused entries
2681 if (!nonempty(&entry, sizeof(entry)))
2682 continue;
2683
2684 // Get LBA if valid
2685 uint64_t lba48 = (entry.lbafirstfailure < 0xffffffff ?
2686 entry.lbafirstfailure : 0xffffffffffffULL);
2687
2688 // Print entry
2689 int state = ataPrintSmartSelfTestEntry(jref["table"][ji++],
2690 testnum, entry.selftestnumber, entry.selfteststatus,
2691 entry.timestamp, lba48, !allentries, noheaderprinted);
2692
2693 if (state < 0) {
2694 // Self-test showed an error
2695 if (ext_ok_testnum < 0)
2696 errcnt++;
2697 else
2698 // Newer successful extended self-test exits
2699 igncnt++;
2700 }
2701 else if (state > 0 && ext_ok_testnum < 0) {
2702 // Latest successful extended self-test
2703 ext_ok_testnum = testnum;
2704 }
2705 testnum++;
2706 }
2707
2708 if (igncnt)
2709 jout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
2710 igncnt, igncnt+errcnt, ext_ok_testnum);
2711 jref["count"] = testnum - 1;
2712 jref["error_count_total"] = igncnt + errcnt;
2713 jref["error_count_outdated"] = igncnt;
2714
2715 if (!allentries && !noheaderprinted)
2716 jout("\n");
2717
2718 return errcnt;
2719}
2720
2721// Print SMART Extended Self-test Log (GP Log 0x07)
2723 unsigned nsectors, unsigned max_entries)
2724{
2725 json::ref jref = jglb["ata_smart_self_test_log"]["extended"];
2726
2727 jout("SMART Extended Self-test Log Version: %u (%u sectors)\n",
2728 log->version, nsectors);
2729 jref["revision"] = log->version;
2730 jref["sectors"] = nsectors;
2731
2732 if (!log->log_desc_index){
2733 jout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n\n");
2734 jref["count"] = 0;
2735 return 0;
2736 }
2737
2738 // Check index
2739 unsigned nentries = nsectors * 19;
2740 unsigned logidx = log->log_desc_index;
2741 if (logidx > nentries) {
2742 pout("Invalid Self-test Log index = 0x%04x (reserved = 0x%02x)\n", logidx, log->reserved1);
2743 return 0;
2744 }
2745
2746 // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
2747 // it is 1-based in practice.
2748 logidx--;
2749
2750 bool print_header = true;
2751 int errcnt = 0, igncnt = 0;
2752 int ext_ok_testnum = -1;
2753 unsigned testnum = 1;
2754
2755 // Iterate through circular buffer in reverse direction
2756 for (unsigned i = 0, ji = 0; i < nentries && testnum <= max_entries;
2757 i++, logidx = (logidx > 0 ? logidx - 1 : nentries - 1)) {
2758
2759 const ata_smart_extselftestlog_desc & entry = log[logidx / 19].log_descs[logidx % 19];
2760
2761 // Skip unused entries
2762 if (!nonempty(&entry, sizeof(entry)))
2763 continue;
2764
2765 // Get LBA
2766 const unsigned char * b = entry.failing_lba;
2767 uint64_t lba48 = b[0]
2768 | ( b[1] << 8)
2769 | ( b[2] << 16)
2770 | ((uint64_t)b[3] << 24)
2771 | ((uint64_t)b[4] << 32)
2772 | ((uint64_t)b[5] << 40);
2773
2774 // Print entry
2775 int state = ataPrintSmartSelfTestEntry(jref["table"][ji++],
2776 testnum, entry.self_test_type,
2777 entry.self_test_status, entry.timestamp, lba48,
2778 false /*!print_error_only*/, print_header);
2779
2780 if (state < 0) {
2781 // Self-test showed an error
2782 if (ext_ok_testnum < 0)
2783 errcnt++;
2784 else
2785 // Newer successful extended self-test exits
2786 igncnt++;
2787 }
2788 else if (state > 0 && ext_ok_testnum < 0) {
2789 // Latest successful extended self-test
2790 ext_ok_testnum = testnum;
2791 }
2792 testnum++;
2793 }
2794
2795 if (igncnt)
2796 jout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
2797 igncnt, igncnt+errcnt, ext_ok_testnum);
2798 jref["count"] = testnum - 1;
2799 jref["error_count_total"] = igncnt + errcnt;
2800 jref["error_count_outdated"] = igncnt;
2801
2802 jout("\n");
2803 return errcnt;
2804}
2805
2807{
2808 json::ref jref = jglb["ata_smart_selective_self_test_log"];
2809
2810 // print data structure revision number
2811 jout("SMART Selective self-test log data structure revision number %d\n", log->logversion);
2812 jref["revision"] = log->logversion;
2813 if (1 != log->logversion)
2814 pout("Note: revision number not 1 implies that no selective self-test has ever been run\n");
2815
2816 const char *msg;
2817 switch((sv->self_test_exec_status)>>4){
2818 case 0:msg="Completed";
2819 break;
2820 case 1:msg="Aborted_by_host";
2821 break;
2822 case 2:msg="Interrupted";
2823 break;
2824 case 3:msg="Fatal_error";
2825 break;
2826 case 4:msg="Completed_unknown_failure";
2827 break;
2828 case 5:msg="Completed_electrical_failure";
2829 break;
2830 case 6:msg="Completed_servo/seek_failure";
2831 break;
2832 case 7:msg="Completed_read_failure";
2833 break;
2834 case 8:msg="Completed_handling_damage??";
2835 break;
2836 case 15:msg="Self_test_in_progress";
2837 break;
2838 default:msg="Unknown_status ";
2839 break;
2840 }
2841
2842 // find the number of columns needed for printing. If in use, the
2843 // start/end of span being read-scanned...
2844 uint64_t maxl = 0, maxr = 0;
2845 uint64_t current = log->currentlba;
2846 uint64_t currentend = current + 0xffff;
2847 if (log->currentspan>5) {
2848 maxl=current;
2849 maxr=currentend;
2850 }
2851 for (int i = 0; i < 5; i++) {
2852 uint64_t start=log->span[i].start;
2853 uint64_t end =log->span[i].end;
2854 // ... plus max start/end of each of the five test spans.
2855 if (start>maxl)
2856 maxl=start;
2857 if (end > maxr)
2858 maxr=end;
2859 }
2860
2861 // we need at least 7 characters wide fields to accommodate the
2862 // labels
2863 int field1,field2;
2864 char tmp[64];
2865 if ((field1=snprintf(tmp,64, "%" PRIu64, maxl))<7)
2866 field1=7;
2867 if ((field2=snprintf(tmp,64, "%" PRIu64, maxr))<7)
2868 field2=7;
2869
2870 // now print the five test spans
2871 jout(" SPAN %*s %*s CURRENT_TEST_STATUS\n", field1, "MIN_LBA", field2, "MAX_LBA");
2872
2873 for (int i = 0; i < 5; i++) {
2874 uint64_t start=log->span[i].start;
2875 uint64_t end=log->span[i].end;
2876 bool active = (i + 1 == log->currentspan);
2877
2878 if (active)
2879 // this span is currently under test
2880 jout(" %d %*" PRIu64 " %*" PRIu64 " %s [%01d0%% left] (%" PRIu64 "-%" PRIu64 ")\n",
2881 i + 1, field1, start, field2, end, msg,
2882 (sv->self_test_exec_status & 0xf), current, currentend);
2883 else
2884 // this span is not currently under test
2885 jout(" %d %*" PRIu64 " %*" PRIu64 " Not_testing\n",
2886 i + 1, field1, start, field2, end);
2887
2888 json::ref jrefi = jref["table"][i];
2889 jrefi["lba_min"] = start;
2890 jrefi["lba_max"] = end;
2891 jrefi["status"]["value"] = sv->self_test_exec_status;
2892 jrefi["status"]["string"] = (active ? msg : "Not_testing");
2893 if (active) {
2894 jrefi["status"]["remaining_percent"] = sv->self_test_exec_status & 0xf;
2895 jrefi["current_lba_min"] = current;
2896 jrefi["current_lba_max"] = currentend;
2897 }
2898 }
2899
2900 // if we are currently read-scanning, print LBAs and the status of
2901 // the read scan
2902 if (log->currentspan > 5) {
2904 jout("%5d %*" PRIu64 " %*" PRIu64 " Read_scanning %s\n",
2905 log->currentspan, field1, current, field2, currentend, ost);
2906 json::ref jrefc = jref["current_read_scan"];
2907 jrefc["lba_min"] = current;
2908 jrefc["lba_max"] = currentend;
2909 jrefc["status"]["value"] = sv->offline_data_collection_status;
2910 jrefc["status"]["string"] = ost;
2911 }
2912
2913 /* Print selective self-test flags. Possible flag combinations are
2914 (numbering bits from 0-15):
2915 Bit-1 Bit-3 Bit-4
2916 Scan Pending Active
2917 0 * * Don't scan
2918 1 0 0 Will carry out scan after selective test
2919 1 1 0 Waiting to carry out scan after powerup
2920 1 0 1 Currently scanning
2921 1 1 1 Currently scanning
2922 */
2923
2924 jout("Selective self-test flags (0x%x):\n", (unsigned)log->flags);
2925 json::ref jreff = jref["flags"];
2926 jreff["value"] = log->flags;
2927 jreff["remainder_scan_enabled"] = !!(log->flags & SELECTIVE_FLAG_DOSCAN);
2928 if (log->flags & SELECTIVE_FLAG_DOSCAN) {
2929 if (log->flags & SELECTIVE_FLAG_ACTIVE)
2930 jout(" Currently read-scanning the remainder of the disk.\n");
2931 else if (log->flags & SELECTIVE_FLAG_PENDING)
2932 jout(" Read-scan of remainder of disk interrupted; will resume %d min after power-up.\n",
2933 log->pendingtime);
2934 else
2935 jout(" After scanning selected spans, read-scan remainder of disk.\n");
2936 jreff["remainder_scan_active"] = !!(log->flags & SELECTIVE_FLAG_ACTIVE);
2937 jreff["power_up_scan_pending"] = !!(log->flags & SELECTIVE_FLAG_PENDING);
2938 }
2939 else
2940 jout(" After scanning selected spans, do NOT read-scan remainder of disk.\n");
2941
2942 // print pending time
2943 jout("If Selective self-test is pending on power-up, resume after %d minute delay.\n",
2944 log->pendingtime);
2945 jref["power_up_scan_resume_minutes"] = log->pendingtime;
2946}
2947
2948// Format SCT Temperature value
2949static const char * sct_ptemp(signed char x, char (& buf)[20])
2950{
2951 if (x == -128 /*0x80 = unknown*/)
2952 return " ?";
2953 snprintf(buf, sizeof(buf), "%2d", x);
2954 return buf;
2955}
2956
2957static void sct_jtemp2(const json::ref & jref, const char * name, signed char x)
2958{
2959 if (x == -128 /*0x80 = unknown*/)
2960 return;
2961 jglb["temperature"][name] = x;
2962 jref["temperature"][name] = x;
2963}
2964
2965static const char * sct_pbar(int x, char (& buf)[64])
2966{
2967 if (x <= 19)
2968 x = 0;
2969 else
2970 x -= 19;
2971 bool ov = false;
2972 if (x > 40) {
2973 x = 40; ov = true;
2974 }
2975 if (x > 0) {
2976 memset(buf, '*', x);
2977 if (ov)
2978 buf[x-1] = '+';
2979 buf[x] = 0;
2980 }
2981 else {
2982 buf[0] = '-'; buf[1] = 0;
2983 }
2984 return buf;
2985}
2986
2987static const char * sct_device_state_msg(unsigned char state)
2988{
2989 switch (state) {
2990 case 0: return "Active";
2991 case 1: return "Stand-by";
2992 case 2: return "Sleep";
2993 case 3: return "DST executing in background";
2994 case 4: return "SMART Off-line Data Collection executing in background";
2995 case 5: return "SCT command executing in background";
2996 default:return "Unknown";
2997 }
2998}
2999
3000// Print SCT Status
3002{
3003 json::ref jref = jglb["ata_sct_status"];
3004
3005 jout("SCT Status Version: %u\n", sts->format_version);
3006 jref["format_version"] = sts->format_version;
3007 jout("SCT Version (vendor specific): %u (0x%04x)\n", sts->sct_version, sts->sct_version);
3008 jref["sct_version"] = sts->sct_version;
3009 // SCT Support Level (1) from original SCT draft was later declared obsolete in ATA-8 ACS.
3010 // Drives typically return 0 or 1. Print only if unknown value is returned.
3011 if (sts->sct_spec > 1)
3012 pout("SCT Support Level: %u\n", sts->sct_spec);
3013 const char * statestr = sct_device_state_msg(sts->device_state);
3014 jout("Device State: %s (%u)\n", statestr, sts->device_state);
3015 jref["device_state"]["value"] = sts->device_state;
3016 jref["device_state"]["string"] = statestr;
3017
3018 // If "Reserved" fields not set, assume "old" format version 2:
3019 // Table 11 of T13/1701DT-N (SMART Command Transport) Revision 5, February 2005
3020 // Table 54 of T13/1699-D (ATA8-ACS) Revision 3e, July 2006
3021 // ... else assume "new" format version 2 or version 3:
3022 // T13/e06152r0-3 (Additional SCT Temperature Statistics), August - October 2006
3023 // Table 60 of T13/1699-D (ATA8-ACS) Revision 3f, December 2006 (format version 2)
3024 // Table 80 of T13/1699-D (ATA8-ACS) Revision 6a, September 2008 (format version 3)
3025 // Table 194 of T13/BSR INCITS 529 (ACS-4) Revision 20, October 26, 2017
3026 // (max_op_limit, smart_status, min_erc_time)
3027 bool old_format_2 = ( !sts->min_temp && !sts->life_min_temp
3028 && !sts->under_limit_count && !sts->over_limit_count);
3029
3030 char buf1[20], buf2[20];
3031 jout("Current Temperature: %s Celsius\n",
3032 sct_ptemp(sts->hda_temp, buf1));
3033 sct_jtemp2(jref, "current", sts->hda_temp);
3034 jout("Power Cycle Min/Max Temperature: %s/%s Celsius\n",
3035 (!old_format_2 ? sct_ptemp(sts->min_temp, buf1) : "--"),
3036 sct_ptemp(sts->max_temp, buf2));
3037 if (!old_format_2)
3038 sct_jtemp2(jref, "power_cycle_min", sts->min_temp);
3039 sct_jtemp2(jref, "power_cycle_max", sts->max_temp);
3040 jout("Lifetime Min/Max Temperature: %s/%s Celsius\n",
3041 (!old_format_2 ? sct_ptemp(sts->life_min_temp, buf1) : "--"),
3042 sct_ptemp(sts->life_max_temp, buf2));
3043 if (!old_format_2)
3044 sct_jtemp2(jref, "lifetime_min", sts->life_min_temp);
3045 sct_jtemp2(jref, "lifetime_max", sts->life_max_temp);
3046 if (old_format_2)
3047 return 0;
3048
3049 if (sts->max_op_limit > 0) { // e06152r0-2: "Average Temperature"
3050 jout("Specified Max Operating Temperature: %3d Celsius\n", sts->max_op_limit);
3051 sct_jtemp2(jref, "op_limit_max", sts->max_op_limit);
3052 }
3053 jout("Under/Over Temperature Limit Count: %2u/%u\n",
3055 jref["temperature"]["under_limit_count"] = sts->under_limit_count;
3056 jref["temperature"]["over_limit_count"] = sts->over_limit_count;
3057
3058 if (sts->smart_status) { // ACS-4
3059 int passed = (sts->smart_status == 0x2cf4 ? 0 :
3060 sts->smart_status == 0xc24f ? 1 : -1);
3061 jout("SMART Status: 0x%04x (%s)\n", sts->smart_status,
3062 (passed == 0 ? "FAILED" : passed > 0 ? "PASSED" : "Reserved"));
3063 if (passed >= 0) {
3064 jref["smart_status"]["passed"] = !!passed;
3065 jglb["smart_status"]["passed"] = !!passed;
3066 }
3067 else
3068 jref["smart_status"]["reserved_value"] = sts->smart_status;
3069 }
3070
3071 if (sts->min_erc_time) // ACS-4
3072 pout("Minimum supported ERC Time Limit: %d (%0.1f seconds)\n",
3073 sts->min_erc_time, sts->min_erc_time/10.0);
3074
3075 if (nonempty(sts->vendor_specific, sizeof(sts->vendor_specific))) {
3076 jout("Vendor specific:\n");
3077 for (unsigned i = 0; i < sizeof(sts->vendor_specific); i++) {
3078 jout("%02x%c", sts->vendor_specific[i], ((i & 0xf) != 0xf ? ' ' : '\n'));
3079 jref["vendor_specific"][i] = sts->vendor_specific[i];
3080 }
3081 }
3082 return 0;
3083}
3084
3085// Print SCT Temperature History Table
3087{
3088 json::ref jref = jglb["ata_sct_temperature_history"];
3089
3090 char buf1[20], buf2[20], buf3[64];
3091 jout("SCT Temperature History Version: %u%s\n", tmh->format_version,
3092 (tmh->format_version != 2 ? " (Unknown, should be 2)" : ""));
3093 jref["version"] = tmh->format_version;
3094 jout("Temperature Sampling Period: %u minute%s\n",
3095 tmh->sampling_period, (tmh->sampling_period==1?"":"s"));
3096 jref["sampling_period_minutes"] = tmh->sampling_period;
3097 jout("Temperature Logging Interval: %u minute%s\n",
3098 tmh->interval, (tmh->interval==1?"":"s"));
3099 jref["logging_interval_minutes"] = tmh->interval;
3100
3101 jout("Min/Max recommended Temperature: %s/%s Celsius\n",
3102 sct_ptemp(tmh->min_op_limit, buf1), sct_ptemp(tmh->max_op_limit, buf2));
3103 sct_jtemp2(jref, "op_limit_min", tmh->min_op_limit);
3104 sct_jtemp2(jref, "op_limit_max", tmh->max_op_limit);
3105 jout("Min/Max Temperature Limit: %s/%s Celsius\n",
3106 sct_ptemp(tmh->under_limit, buf1), sct_ptemp(tmh->over_limit, buf2));
3107 sct_jtemp2(jref, "limit_min", tmh->under_limit);
3108 sct_jtemp2(jref, "limit_max", tmh->over_limit);
3109 jout("Temperature History Size (Index): %u (%u)\n", tmh->cb_size, tmh->cb_index);
3110 jref["size"] = tmh->cb_size;
3111 jref["index"] = tmh->cb_index;
3112
3113 if (!(0 < tmh->cb_size && tmh->cb_size <= sizeof(tmh->cb) && tmh->cb_index < tmh->cb_size)) {
3114 if (!tmh->cb_size)
3115 pout("Temperature History is empty\n");
3116 else
3117 pout("Invalid Temperature History Size or Index\n");
3118 return 0;
3119 }
3120
3121 // Print table
3122 jout("\nIndex Estimated Time Temperature Celsius\n");
3123 unsigned n = 0, i = (tmh->cb_index+1) % tmh->cb_size;
3124 unsigned interval = (tmh->interval > 0 ? tmh->interval : 1);
3125 time_t t = time(0) - (time_t)(tmh->cb_size-1) * interval * 60;
3126 t -= t % (interval * 60);
3127 while (n < tmh->cb_size) {
3128 // Find range of identical temperatures
3129 unsigned n1 = n, n2 = n+1, i2 = (i+1) % tmh->cb_size;
3130 while (n2 < tmh->cb_size && tmh->cb[i2] == tmh->cb[i]) {
3131 n2++; i2 = (i2+1) % tmh->cb_size;
3132 }
3133 // Print range
3134 while (n < n2) {
3135 if (n == n1 || n == n2-1 || n2 <= n1+3) {
3136 // TODO: Don't print times < boot time
3137 char date[32] = "";
3138 struct tm tmbuf;
3139 strftime(date, sizeof(date), "%Y-%m-%d %H:%M", time_to_tm_local(&tmbuf, t));
3140 jout(" %3u %s %s %s\n", i, date,
3141 sct_ptemp(tmh->cb[i], buf1), sct_pbar(tmh->cb[i], buf3));
3142 }
3143 else if (n == n1+1) {
3144 jout(" ... ..(%3u skipped). .. %s\n",
3145 n2-n1-2, sct_pbar(tmh->cb[i], buf3));
3146 }
3147 if (tmh->cb[i] != -128)
3148 jref["table"][n] = tmh->cb[i];
3149 t += interval * 60; i = (i+1) % tmh->cb_size; n++;
3150 }
3151 }
3152 //assert(n == tmh->cb_size && i == (tmh->cb_index+1) % tmh->cb_size);
3153
3154 return 0;
3155}
3156
3157// Print SCT Error Recovery Control timers
3158static void ataPrintSCTErrorRecoveryControl(bool set, unsigned short read_timer, unsigned short write_timer, bool power_on, bool mfg_default = false)
3159{
3160 const char* power_on_str = (power_on ? "Power-on " : "");
3161 json::ref jref = jglb["ata_sct_erc"];
3162 jout("SCT Error Recovery Control%s:%s\n", (set ? " set to" : ""), (mfg_default ? " default values." : ""));
3163
3164 if (!mfg_default) {
3165 jref["read"]["enabled"] = !!read_timer;
3166 if (!read_timer)
3167 jout(" %sRead: Disabled\n", power_on_str);
3168 else {
3169 jout(" %sRead: %6d (%0.1f seconds)\n", power_on_str, read_timer, read_timer/10.0);
3170 jref["read"]["deciseconds"] = read_timer;
3171 }
3172
3173 jref["write"]["enabled"] = !!write_timer;
3174 if (!write_timer)
3175 jout(" %sWrite: Disabled\n", power_on_str);
3176 else {
3177 jout(" %sWrite: %6d (%0.1f seconds)\n", power_on_str, write_timer, write_timer/10.0);
3178 jref["write"]["deciseconds"] = write_timer;
3179 }
3180 }
3181}
3182
3183static void print_aam_level(const char * msg, int level, int recommended = -1)
3184{
3185 // Table 56 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008
3186 // Obsolete since T13/2015-D (ACS-2) Revision 4a, December 9, 2010
3187 const char * s;
3188 if (level == 0)
3189 s = "vendor specific";
3190 else if (level < 128)
3191 s = "unknown/retired";
3192 else if (level == 128)
3193 s = "quiet";
3194 else if (level < 254)
3195 s = "intermediate";
3196 else if (level == 254)
3197 s = "maximum performance";
3198 else
3199 s = "reserved";
3200
3201 if (recommended >= 0)
3202 jout("%s%d (%s), recommended: %d\n", msg, level, s, recommended);
3203 else
3204 jout("%s%d (%s)\n", msg, level, s);
3205
3206 json::ref jref = jglb["ata_aam"];
3207 jref["enabled"] = true;
3208 jref["level"] = level;
3209 jref["string"] = s;
3210 if (recommended >= 0)
3211 jref["recommended_level"] = recommended;
3212}
3213
3214static void print_apm_level(const char * msg, int level)
3215{
3216 // Table 120 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
3217 const char * s;
3218 if (!(1 <= level && level <= 254))
3219 s = "reserved";
3220 else if (level == 1)
3221 s = "minimum power consumption with standby";
3222 else if (level < 128)
3223 s = "intermediate level with standby";
3224 else if (level == 128)
3225 s = "minimum power consumption without standby";
3226 else if (level < 254)
3227 s = "intermediate level without standby";
3228 else
3229 s = "maximum performance";
3230
3231 jout("%s%d (%s)\n", msg, level, s);
3232
3233 json::ref jref = jglb["ata_apm"];
3234 jref["enabled"] = true;
3235 jref["level"] = level;
3236 jref["string"] = s;
3237 if (1 <= level && level <= 254) {
3238 jref["max_performance"] = (level == 254);
3239 jref["min_power"] = (level == 1 || level == 128);
3240 jref["with_standby"] = (level < 128);
3241 }
3242}
3243
3244static void print_ata_security_status(const char * msg, unsigned short state, unsigned short master_password_id)
3245{
3246 // Table 6 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
3247 if (!(state & 0x0001)) {
3248 pout("%sUnavailable\n", msg);
3249 return;
3250 }
3251
3252 const char * s1, * s2 = "", * s3 = "", * s4 = "";
3253 bool enabled = false, locked = false;
3254 if (!(state & 0x0002)) {
3255 s1 = "Disabled, ";
3256 if (!(state & 0x0008))
3257 s2 = "NOT FROZEN [SEC1]";
3258 else
3259 s2 = "frozen [SEC2]";
3260 }
3261 else {
3262 enabled = true;
3263 s1 = "ENABLED, PW level ";
3264 if (!(state & 0x0100))
3265 s2 = "HIGH";
3266 else
3267 s2 = "MAX";
3268
3269 if (!(state & 0x0004)) {
3270 s3 = ", not locked, ";
3271 if (!(state & 0x0008))
3272 s4 = "not frozen [SEC5]";
3273 else
3274 s4 = "frozen [SEC6]";
3275 }
3276 else {
3277 locked = true;
3278 s3 = ", **LOCKED** [SEC4]";
3279 if (state & 0x0010)
3280 s4 = ", PW ATTEMPTS EXCEEDED";
3281 }
3282 }
3283
3284 // Print Master Password ID if set to non-default value
3285 // (0x0000, 0xffff: unsupported, 0xfffe: default)
3286 char s5[32] = "";
3287 if (0x0000 < master_password_id && master_password_id < 0xfffe)
3288 snprintf(s5, sizeof(s5), ", Master PW ID: 0x%04x", master_password_id);
3289
3290 jout("%s%s%s%s%s%s\n", msg, s1, s2, s3, s4, s5);
3291
3292 json::ref jref = jglb["ata_security"];
3293 jref["state"] = state;
3294 jref["string"] = strprintf("%s%s%s%s", s1, s2, s3, s4);
3295 jref["enabled"] = enabled;
3296 if (!enabled || !locked)
3297 jref["frozen"] = !!(state & 0x0008);
3298 if (enabled) {
3299 jref["pw_level_max"] = !!(state & 0x0100);
3300 jref["locked"] = locked;
3301 if (locked)
3302 jref["pw_attempts_exceeded"] = !!(state & 0x0010);
3303 }
3304 jref["master_password_id"] = master_password_id;
3305}
3306
3307static void print_standby_timer(const char * msg, int timer, const ata_identify_device & drive)
3308{
3309 const char * s1 = 0;
3310 int hours = 0, minutes = 0 , seconds = 0;
3311
3312 // Table 63 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
3313 if (timer == 0)
3314 s1 = "disabled";
3315 else if (timer <= 240)
3316 seconds = timer * 5, minutes = seconds / 60, seconds %= 60;
3317 else if (timer <= 251)
3318 minutes = (timer - 240) * 30, hours = minutes / 60, minutes %= 60;
3319 else if (timer == 252)
3320 minutes = 21;
3321 else if (timer == 253)
3322 s1 = "between 8 hours and 12 hours";
3323 else if (timer == 255)
3324 minutes = 21, seconds = 15;
3325 else
3326 s1 = "reserved";
3327
3328 const char * s2 = "", * s3 = "";
3329 if (!(drive.words047_079[49-47] & 0x2000))
3330 s2 = " or vendor-specific";
3331 if (timer > 0 && (drive.words047_079[50-47] & 0xc001) == 0x4001)
3332 s3 = ", a vendor-specific minimum applies";
3333
3334 if (s1)
3335 pout("%s%d (%s%s%s)\n", msg, timer, s1, s2, s3);
3336 else
3337 pout("%s%d (%02d:%02d:%02d%s%s)\n", msg, timer, hours, minutes, seconds, s2, s3);
3338}
3339
3340
3341int ataPrintMain (ata_device * device, const ata_print_options & options)
3342{
3343 // If requested, check power mode first
3344 const char * powername = 0;
3345 bool powerchg = false;
3346 if (options.powermode) {
3347 unsigned char powerlimit = 0xff;
3348 int powermode = ataCheckPowerMode(device);
3349 // TODO: Move to new function used by smartctl and smartd.
3350 switch (powermode) {
3351 case -1:
3352 if (device->is_syscall_unsup()) {
3353 if (options.powerexit_unsup >= 0) {
3354 jinf("CHECK POWER MODE not implemented, exit(%d)\n", options.powerexit_unsup);
3355 return options.powerexit_unsup;
3356 }
3357 jinf("CHECK POWER MODE not implemented, ignoring -n option\n"); break;
3358 }
3359 powername = "SLEEP"; powerlimit = 2;
3360 break;
3361 // Table 215 of T13/2015-D (ACS-2) Revision 7, June 22, 2011
3362 // Table 293 of T13/BSR INCITS 529 (ACS-4) Revision 12, February 18, 2016
3363 case 0x00: // PM2:Standby, EPC unavailable or Standby_z power condition
3364 powername = "STANDBY"; powerlimit = 3; break;
3365 case 0x01: // PM2:Standby, Standby_y power condition
3366 powername = "STANDBY_Y"; powerlimit = 3; break;
3367 case 0x80: // PM1:Idle, EPC unavailable
3368 powername = "IDLE"; powerlimit = 4; break;
3369 case 0x81: // PM1:Idle, Idle_a power condition
3370 powername = "IDLE_A"; powerlimit = 4; break;
3371 case 0x82: // PM1:Idle, Idle_b power condition
3372 powername = "IDLE_B"; powerlimit = 4; break;
3373 case 0x83: // PM1:Idle, Idle_c power condition
3374 powername = "IDLE_C"; powerlimit = 4; break;
3375 // 0x40/41 were declared obsolete in ACS-3 Revision 1
3376 case 0x40: // PM0:Active, NV Cache power mode enabled, spun down
3377 powername = "ACTIVE_NV_DOWN"; break;
3378 case 0x41: // PM0:Active, NV Cache power mode enabled, spun up
3379 powername = "ACTIVE_NV_UP" ; break;
3380 case 0xff: // PM0:Active or PM1:Idle
3381 powername = "ACTIVE or IDLE"; break;
3382
3383 default:
3384 if (options.powerexit_unsup >= 0) {
3385 jinf("CHECK POWER MODE returned unknown value 0x%02x, exit(%d)\n", powermode,
3386 options.powerexit_unsup);
3387 return options.powerexit_unsup;
3388 }
3389 jinf("CHECK POWER MODE returned unknown value 0x%02x, ignoring -n option\n", powermode);
3390 break;
3391 }
3392 if (powername) {
3393 if (options.powermode >= powerlimit) {
3394 jinf("Device is in %s mode, exit(%d)\n", powername, options.powerexit);
3395 return options.powerexit;
3396 }
3397 powerchg = (powermode != 0xff); // SMART tests will spin up drives
3398 }
3399 }
3400
3401 // SMART values needed ?
3402 bool need_smart_val = (
3403 options.smart_check_status
3404 || options.smart_general_values
3405 || options.smart_vendor_attrib
3406 || options.smart_error_log
3407 || options.smart_selftest_log
3409 || options.smart_ext_error_log
3410 || options.smart_ext_selftest_log
3411 || options.smart_auto_offl_enable
3412 || options.smart_auto_offl_disable
3413 || options.smart_selftest_type != -1
3414 );
3415
3416 // SMART must be enabled ?
3417 bool need_smart_enabled = (
3418 need_smart_val
3419 || options.smart_auto_save_enable
3420 || options.smart_auto_save_disable
3421 );
3422
3423 // SMART feature set needed ?
3424 bool need_smart_support = (
3425 need_smart_enabled
3426 || options.smart_enable
3427 || options.smart_disable
3428 );
3429
3430 // SMART and GP log directories needed ?
3431 bool need_smart_logdir = (
3432 options.smart_logdir
3433 || options.devstat_all_pages // devstat fallback to smartlog if needed
3434 || options.devstat_ssd_page
3435 || !options.devstat_pages.empty()
3436 );
3437
3438 bool need_gp_logdir = (
3439 options.gp_logdir
3440 || options.smart_ext_error_log
3441 || options.smart_ext_selftest_log
3442 || options.devstat_all_pages
3443 || options.devstat_ssd_page
3444 || !options.devstat_pages.empty()
3445 || options.pending_defects_log
3446 || options.farm_log
3447 );
3448
3449 unsigned i;
3450 for (i = 0; i < options.log_requests.size(); i++) {
3451 if (options.log_requests[i].gpl)
3452 need_gp_logdir = true;
3453 else
3454 need_smart_logdir = true;
3455 }
3456
3457 // SCT commands needed ?
3458 bool need_sct_support = (
3459 options.sct_temp_sts
3460 || options.sct_temp_hist
3461 || options.sct_temp_int
3462 || options.sct_erc_get
3463 || options.sct_erc_set
3464 || options.sct_wcache_reorder_get
3465 || options.sct_wcache_reorder_set
3466 || options.sct_wcache_sct_get
3467 || options.sct_wcache_sct_set
3468 );
3469
3470 // Exit if no further options specified
3471 if (!( options.drive_info || options.show_presets
3472 || need_smart_support || need_smart_logdir
3473 || need_gp_logdir || need_sct_support
3474 || options.farm_log
3475 || options.sataphy
3476 || options.identify_word_level >= 0
3477 || options.get_set_used )) {
3478 if (powername)
3479 pout("Device is in %s mode\n", powername);
3480 else
3481 pout("ATA device successfully opened\n\n"
3482 "Use 'smartctl -a' (or '-x') to print SMART (and more) information\n\n");
3483 return 0;
3484 }
3485
3486 // Start by getting Drive ID information. We need this, to know if SMART is supported.
3487 int returnval = 0;
3488 ata_identify_device drive; memset(&drive, 0, sizeof(drive));
3489 unsigned char raw_drive[sizeof(drive)]; memset(&raw_drive, 0, sizeof(raw_drive));
3490
3491 device->clear_err();
3492 int retid = ata_read_identity(device, &drive, options.fix_swapped_id, raw_drive);
3493 if (retid < 0) {
3494 pout("Read Device Identity failed: %s\n\n",
3495 (device->get_errno() ? device->get_errmsg() : "Unknown error"));
3496 pout("If this is a USB connected device, look at the various "
3497 "--device=TYPE variants\n");
3498 failuretest(MANDATORY_CMD, returnval|=FAILID);
3499 }
3500 else if (!nonempty(&drive, sizeof(drive))) {
3501 pout("Read Device Identity failed: empty IDENTIFY data\n\n");
3502 failuretest(MANDATORY_CMD, returnval|=FAILID);
3503 }
3504
3505 // If requested, show which presets would be used for this drive and exit.
3506 if (options.show_presets) {
3507 show_presets(&drive);
3508 return 0;
3509 }
3510
3511 // Use preset vendor attribute options unless user has requested otherwise.
3512 ata_vendor_attr_defs attribute_defs = options.attribute_defs;
3513 firmwarebug_defs firmwarebugs = options.firmwarebugs;
3514 std::string dbversion;
3515 const drive_settings * dbentry = 0;
3516 if (!options.ignore_presets) {
3517 dbentry = lookup_drive_apply_presets(&drive, attribute_defs,
3518 firmwarebugs, dbversion);
3519 if (!dbversion.empty())
3520 jglb["smartctl"]["drive_database_version"]["string"] = dbversion;
3521 }
3522
3523 // Get capacity, sector sizes and rotation rate
3524 ata_size_info sizes;
3525 ata_get_size_info(&drive, sizes);
3526 int rpm = ata_get_rotation_rate(&drive);
3527
3528 // Print ATA IDENTIFY info if requested
3529 if (options.identify_word_level >= 0) {
3530 pout("=== ATA IDENTIFY DATA ===\n");
3531 // Pass raw data without endianness adjustments
3532 ata_print_identify_data(raw_drive, (options.identify_word_level > 0), options.identify_bit_level);
3533 }
3534
3535 // Print most drive identity information if requested
3536 if (options.drive_info) {
3537 pout("=== START OF INFORMATION SECTION ===\n");
3538 print_drive_info(&drive, sizes, rpm, dbentry, dbversion.c_str());
3539 }
3540
3541 // Check and print SMART support and state
3542 int smart_supported = -1, smart_enabled = -1;
3543 if (need_smart_support || options.drive_info) {
3544
3545 // Packet device ?
3546 if (retid > 0) {
3547 pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n",
3548 packetdevicetype(retid-1));
3549 }
3550 else {
3551 // Disk device: SMART supported and enabled ?
3552 smart_supported = ataSmartSupport(&drive);
3553 smart_enabled = ataIsSmartEnabled(&drive);
3554
3555 if (smart_supported < 0)
3556 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
3557 if (smart_supported && smart_enabled < 0) {
3558 pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
3559 if (need_smart_support) {
3560 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
3561 // check SMART support by trying a command
3562 pout(" Checking to be sure by trying SMART RETURN STATUS command.\n");
3563 if (ataDoesSmartWork(device))
3564 smart_supported = smart_enabled = 1;
3565 }
3566 }
3567 else if (smart_supported < 0 && (smart_enabled > 0 || dbentry))
3568 // Assume supported if enabled or in drive database
3569 smart_supported = 1;
3570
3571 if (smart_supported < 0)
3572 pout("SMART support is: Unknown - Try option -s with argument 'on' to enable it.");
3573 else if (!smart_supported)
3574 jout("SMART support is: Unavailable - device lacks SMART capability.\n");
3575 else {
3576 if (options.drive_info)
3577 jout("SMART support is: Available - device has SMART capability.\n");
3578 if (smart_enabled >= 0) {
3579 if (device->ata_identify_is_cached()) {
3580 if (options.drive_info)
3581 pout(" %sabled status cached by OS, trying SMART RETURN STATUS cmd.\n",
3582 (smart_enabled?"En":"Dis"));
3583 smart_enabled = ataDoesSmartWork(device);
3584 }
3585 if (options.drive_info)
3586 jout("SMART support is: %s\n",
3587 (smart_enabled ? "Enabled" : "Disabled"));
3588 }
3589 }
3590 }
3591
3592 if (options.drive_info || smart_supported <= 0) {
3593 jglb["smart_support"]["available"] = (smart_supported > 0);
3594 if (smart_supported > 0)
3595 jglb["smart_support"]["enabled"] = (smart_enabled > 0);
3596 }
3597 }
3598
3599 // Print AAM status
3600 if (options.get_aam) {
3601 if ((drive.command_set_2 & 0xc200) != 0x4200) // word083
3602 pout("AAM feature is: Unavailable\n");
3603 else if (!(drive.word086 & 0x0200)) {
3604 jout("AAM feature is: Disabled\n");
3605 jglb["ata_aam"]["enabled"] = false;
3606 }
3607 else
3608 print_aam_level("AAM level is: ", drive.words088_255[94-88] & 0xff,
3609 drive.words088_255[94-88] >> 8);
3610 }
3611
3612 // Print APM status
3613 if (options.get_apm) {
3614 if ((drive.command_set_2 & 0xc008) != 0x4008) // word083
3615 pout("APM feature is: Unavailable\n");
3616 else if (!(drive.word086 & 0x0008)) {
3617 jout("APM feature is: Disabled\n");
3618 jglb["ata_apm"]["enabled"] = false;
3619 }
3620 else
3621 print_apm_level("APM level is: ", drive.words088_255[91-88] & 0xff);
3622 }
3623
3624 // Print read look-ahead status
3625 if (options.get_lookahead) {
3626 if ( (drive.command_set_2 & 0xc000) != 0x4000 // word083
3627 || !(drive.command_set_1 & 0x0040) ) // word082
3628 pout("Rd look-ahead is: Unavailable\n");
3629 else {
3630 bool enabled = !!(drive.cfs_enable_1 & 0x0040); // word085
3631 jout("Rd look-ahead is: %sabled\n", (enabled ? "En" : "Dis"));
3632 jglb["read_lookahead"]["enabled"] = enabled;
3633 }
3634 }
3635
3636 // Print write cache status
3637 if (options.get_wcache) {
3638 if ( (drive.command_set_2 & 0xc000) != 0x4000 // word083
3639 || !(drive.command_set_1 & 0x0020) ) // word082
3640 pout("Write cache is: Unavailable\n");
3641 else {
3642 bool enabled = !!(drive.cfs_enable_1 & 0x0020); // word085
3643 jout("Write cache is: %sabled\n", (enabled ? "En" : "Dis"));
3644 jglb["write_cache"]["enabled"] = enabled;
3645 }
3646 }
3647
3648 // Print DSN status
3649 unsigned short word120 = drive.words088_255[120-88];
3650 unsigned short word119 = drive.words088_255[119-88];
3651 if (options.get_dsn) {
3652 if (!(drive.word086 & 0x8000) // word086
3653 || ((word119 & 0xc200) != 0x4200) // word119
3654 || ((word120 & 0xc000) != 0x4000)) // word120
3655 pout("DSN feature is: Unavailable\n");
3656 else {
3657 bool enabled = !!(word120 & 0x200);
3658 jout("DSN feature is: %sabled\n", (enabled ? "En" : "Dis"));
3659 jglb["ata_dsn"]["enabled"] = enabled;
3660 }
3661 }
3662
3663 // Check for ATA Security LOCK
3664 unsigned short word128 = drive.words088_255[128-88];
3665 bool locked = ((word128 & 0x0007) == 0x0007); // LOCKED|ENABLED|SUPPORTED
3666
3667 // Print ATA Security status
3668 if (options.get_security)
3669 print_ata_security_status("ATA Security is: ", word128, drive.words088_255[92-88]);
3670
3671 // Print write cache reordering status
3672 if (options.sct_wcache_reorder_get) {
3673 if (!isSCTFeatureControlCapable(&drive))
3674 pout("Wt Cache Reorder: Unavailable\n");
3675 else if (locked)
3676 pout("Wt Cache Reorder: Unknown (SCT not supported if ATA Security is LOCKED)\n");
3677 else {
3678 int wcache_reorder = ataGetSetSCTWriteCacheReordering(device,
3679 false /*enable*/, false /*persistent*/, false /*set*/);
3680
3681 if (-1 <= wcache_reorder && wcache_reorder <= 2)
3682 pout("Wt Cache Reorder: %s\n",
3683 (wcache_reorder == -1 ? "Unknown (SCT Feature Control command failed)" :
3684 wcache_reorder == 0 ? "Unknown" : // not defined in standard but returned on some drives if not set
3685 wcache_reorder == 1 ? "Enabled" : "Disabled"));
3686 else
3687 pout("Wt Cache Reorder: Unknown (0x%02x)\n", wcache_reorder);
3688 }
3689 }
3690
3691 const char * sct_write_cache_state_desc[4] = {
3692 "Unknown", // 0: not defined in standard but returned on some drives if not set
3693 "Controlled by ATA", // 1: controlled ATA Set Features command
3694 "Force Enabled", // 2
3695 "Force Disabled" // 3
3696 };
3697
3698 // Print SCT feature control of write cache
3699 if (options.sct_wcache_sct_get) {
3700 if (!isSCTFeatureControlCapable(&drive))
3701 pout("SCT Write Cache Control: Unavailable\n");
3702 else if (locked)
3703 pout("SCT Write Cache Control: Unknown (SCT not supported if ATA Security is LOCKED)\n");
3704 else {
3705 int state = ataGetSetSCTWriteCache(device, 1, false /*persistent*/, false /*set*/);
3706 if (-1 <= state && state <= 3)
3707 pout("SCT Write Cache Control: %s\n",
3708 (state == -1 ? "Unknown (SCT Feature Control command failed)" :
3709 sct_write_cache_state_desc[state]));
3710 else
3711 pout("SCT Write Cache Control: Unknown (0x%02x)\n", state);
3712 }
3713 }
3714
3715
3716 // Print remaining drive info
3717 if (options.drive_info) {
3718 // Print the (now possibly changed) power mode if available
3719 if (powername)
3720 pout("Power mode %s %s\n", (powerchg?"was:":"is: "), powername);
3721 pout("\n");
3722 }
3723
3724 // Exit if SMART is not supported but must be available to proceed
3725 if (smart_supported <= 0 && need_smart_support)
3726 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
3727
3728 // START OF THE ENABLE/DISABLE SECTION OF THE CODE
3729 if ( options.smart_disable || options.smart_enable
3732 || options.set_aam || options.set_apm || options.set_lookahead
3733 || options.set_wcache || options.set_security_freeze || options.set_standby
3734 || options.sct_wcache_reorder_set || options.sct_wcache_sct_set || options.set_dsn)
3735 pout("=== START OF ENABLE/DISABLE COMMANDS SECTION ===\n");
3736
3737 // Enable/Disable AAM
3738 if (options.set_aam) {
3739 if (options.set_aam > 0) {
3740 if (!ata_set_features(device, ATA_ENABLE_AAM, options.set_aam-1)) {
3741 pout("AAM enable failed: %s\n", device->get_errmsg());
3742 returnval |= FAILSMART;
3743 }
3744 else
3745 print_aam_level("AAM set to level ", options.set_aam-1);
3746 }
3747 else {
3748 if (!ata_set_features(device, ATA_DISABLE_AAM)) {
3749 pout("AAM disable failed: %s\n", device->get_errmsg());
3750 returnval |= FAILSMART;
3751 }
3752 else
3753 pout("AAM disabled\n");
3754 }
3755 }
3756
3757 // Enable/Disable APM
3758 if (options.set_apm) {
3759 if (options.set_apm > 0) {
3760 if (!ata_set_features(device, ATA_ENABLE_APM, options.set_apm-1)) {
3761 pout("APM enable failed: %s\n", device->get_errmsg());
3762 returnval |= FAILSMART;
3763 }
3764 else
3765 print_apm_level("APM set to level ", options.set_apm-1);
3766 }
3767 else {
3768 if (!ata_set_features(device, ATA_DISABLE_APM)) {
3769 pout("APM disable failed: %s\n", device->get_errmsg());
3770 returnval |= FAILSMART;
3771 }
3772 else
3773 pout("APM disabled\n");
3774 }
3775 }
3776
3777 // Enable/Disable read look-ahead
3778 if (options.set_lookahead) {
3779 bool enable = (options.set_lookahead > 0);
3781 pout("Read look-ahead %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
3782 returnval |= FAILSMART;
3783 }
3784 else
3785 pout("Read look-ahead %sabled\n", (enable ? "en" : "dis"));
3786 }
3787
3788 // Enable/Disable write cache
3789 if (options.set_wcache) {
3790 bool enable = (options.set_wcache > 0);
3792 pout("Write cache %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
3793 returnval |= FAILSMART;
3794 }
3795 else
3796 pout("Write cache %sabled\n", (enable ? "en" : "dis"));
3797 }
3798
3799 // Enable/Disable DSN
3800 if (options.set_dsn) {
3801 bool enable = (options.set_dsn > 0);
3802 if (!ata_set_features(device, ATA_ENABLE_DISABLE_DSN, (enable ? 0x1 : 0x2))) {
3803 pout("DSN %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
3804 returnval |= FAILSMART;
3805 }
3806 else
3807 pout("DSN %sabled\n", (enable ? "en" : "dis"));
3808 }
3809
3810 // Enable/Disable write cache reordering
3811 if (options.sct_wcache_reorder_set) {
3812 bool enable = (options.sct_wcache_reorder_set > 0);
3813 if (!isSCTFeatureControlCapable(&drive))
3814 pout("Write cache reordering %sable failed: SCT Feature Control command not supported\n",
3815 (enable ? "en" : "dis"));
3816 else if (locked)
3817 pout("Write cache reordering %sable failed: SCT not supported if ATA Security is LOCKED\n",
3818 (enable ? "en" : "dis"));
3819 else if (ataGetSetSCTWriteCacheReordering(device,
3820 enable, options.sct_wcache_reorder_set_pers, true /*set*/) < 0) {
3821 pout("Write cache reordering %sable failed: %s\n", (enable ? "en" : "dis"), device->get_errmsg());
3822 returnval |= FAILSMART;
3823 }
3824 else
3825 pout("Write cache reordering %sabled (%s)\n", (enable ? "en" : "dis"),
3826 (options.sct_wcache_reorder_set_pers ? "persistent" : "volatile"));
3827 }
3828
3829 // Enable/Disable write cache in SCT
3830 if (options.sct_wcache_sct_set) {
3831 if (!isSCTFeatureControlCapable(&drive))
3832 pout("SCT Feature Control of write cache failed: SCT Feature Control command not supported\n");
3833 else if (locked)
3834 pout("SCT Feature Control of write cache failed: SCT not supported if ATA Security is LOCKED\n");
3835 else if (ataGetSetSCTWriteCache(device,
3836 options.sct_wcache_sct_set, options.sct_wcache_sct_set_pers, true /*set*/) < 0) {
3837 pout("SCT Feature Control of write cache failed: %s\n", device->get_errmsg());
3838 returnval |= FAILSMART;
3839 }
3840 else
3841 pout("Write cache SCT Feature Control is set to: %s (%s)\n",
3842 sct_write_cache_state_desc[options.sct_wcache_sct_set],
3843 (options.sct_wcache_sct_set_pers ? "persistent" : "volatile"));
3844 }
3845
3846 // Freeze ATA security
3847 if (options.set_security_freeze) {
3849 pout("ATA SECURITY FREEZE LOCK failed: %s\n", device->get_errmsg());
3850 returnval |= FAILSMART;
3851 }
3852 else
3853 pout("ATA Security set to frozen mode\n");
3854 }
3855
3856 // Set standby timer unless immediate standby is also requested
3857 if (options.set_standby && !options.set_standby_now) {
3858 if (!ata_nodata_command(device, ATA_IDLE, options.set_standby-1)) {
3859 pout("ATA IDLE command failed: %s\n", device->get_errmsg());
3860 returnval |= FAILSMART;
3861 }
3862 else
3863 print_standby_timer("Standby timer set to ", options.set_standby-1, drive);
3864 }
3865
3866 // Enable/Disable SMART commands
3867 if (options.smart_enable) {
3868 if (ataEnableSmart(device)) {
3869 pout("SMART Enable failed: %s\n\n", device->get_errmsg());
3870 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
3871 }
3872 else {
3873 pout("SMART Enabled.\n");
3874 smart_enabled = 1;
3875 }
3876 }
3877
3878 // Turn off SMART on device
3879 if (options.smart_disable) {
3880 if (ataDisableSmart(device)) {
3881 pout("SMART Disable failed: %s\n\n", device->get_errmsg());
3883 }
3884 }
3885
3886 // Exit if SMART is disabled but must be enabled to proceed
3887 if (options.smart_disable || (smart_enabled <= 0 && need_smart_enabled && !is_permissive())) {
3888 pout("SMART Disabled. Use option -s with argument 'on' to enable it.\n");
3889 if (!options.smart_disable)
3890 pout("(override with '-T permissive' option)\n");
3891 return returnval;
3892 }
3893
3894 // Enable/Disable Auto-save attributes
3895 if (options.smart_auto_save_enable) {
3896 if (ataEnableAutoSave(device)){
3897 pout("SMART Enable Attribute Autosave failed: %s\n\n", device->get_errmsg());
3898 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
3899 }
3900 else
3901 pout("SMART Attribute Autosave Enabled.\n");
3902 }
3903
3904 if (options.smart_auto_save_disable) {
3905 if (ataDisableAutoSave(device)){
3906 pout("SMART Disable Attribute Autosave failed: %s\n\n", device->get_errmsg());
3907 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
3908 }
3909 else
3910 pout("SMART Attribute Autosave Disabled.\n");
3911 }
3912
3913 // Read SMART values and thresholds if necessary
3914 ata_smart_values smartval; memset(&smartval, 0, sizeof(smartval));
3915 ata_smart_thresholds_pvt smartthres; memset(&smartthres, 0, sizeof(smartthres));
3916 bool smart_val_ok = false, smart_thres_ok = false;
3917
3918 if (need_smart_val) {
3919 if (ataReadSmartValues(device, &smartval)) {
3920 pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
3921 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3922 }
3923 else {
3924 smart_val_ok = true;
3925
3926 if (options.smart_check_status || options.smart_vendor_attrib) {
3927 if (ataReadSmartThresholds(device, &smartthres)){
3928 pout("Read SMART Thresholds failed: %s\n\n", device->get_errmsg());
3929 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3930 }
3931 else
3932 smart_thres_ok = true;
3933 }
3934 }
3935 }
3936
3937 // Enable/Disable Off-line testing
3938 bool needupdate = false;
3939 if (options.smart_auto_offl_enable) {
3940 if (!isSupportAutomaticTimer(&smartval)){
3941 pout("SMART Automatic Timers not supported\n\n");
3942 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3943 }
3944 needupdate = smart_val_ok;
3945 if (ataEnableAutoOffline(device)){
3946 pout("SMART Enable Automatic Offline failed: %s\n\n", device->get_errmsg());
3947 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3948 }
3949 else
3950 pout("SMART Automatic Offline Testing Enabled every four hours.\n");
3951 }
3952
3953 if (options.smart_auto_offl_disable) {
3954 if (!isSupportAutomaticTimer(&smartval)){
3955 pout("SMART Automatic Timers not supported\n\n");
3956 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3957 }
3958 needupdate = smart_val_ok;
3959 if (ataDisableAutoOffline(device)){
3960 pout("SMART Disable Automatic Offline failed: %s\n\n", device->get_errmsg());
3961 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3962 }
3963 else
3964 pout("SMART Automatic Offline Testing Disabled.\n");
3965 }
3966
3967 if (needupdate && ataReadSmartValues(device, &smartval)){
3968 pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
3969 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
3970 smart_val_ok = false;
3971 }
3972
3973 // all this for a newline!
3974 if ( options.smart_disable || options.smart_enable
3977 || options.set_aam || options.set_apm || options.set_lookahead
3978 || options.set_wcache || options.set_security_freeze || options.set_standby
3979 || options.sct_wcache_reorder_set || options.set_dsn)
3980 pout("\n");
3981
3982 // START OF READ-ONLY OPTIONS APART FROM -V and -i
3983 if ( options.smart_check_status || options.smart_general_values
3984 || options.smart_vendor_attrib || options.smart_error_log
3986 || options.smart_ext_error_log || options.smart_ext_selftest_log
3987 || options.sct_temp_sts || options.sct_temp_hist )
3988 pout("=== START OF READ SMART DATA SECTION ===\n");
3989
3990 // Check SMART status
3991 if (options.smart_check_status) {
3992
3993 switch (ataSmartStatus2(device)) {
3994
3995 case 0:
3996 // The case where the disk health is OK
3997 jout("SMART overall-health self-assessment test result: PASSED\n");
3998 jglb["smart_status"]["passed"] = true;
3999 if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
4000 if (options.smart_vendor_attrib)
4001 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
4002 else {
4003 print_on();
4004 pout("Please note the following marginal Attributes:\n");
4005 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 2, options.output_format);
4006 }
4007 returnval|=FAILAGE;
4008 }
4009 else
4010 pout("\n");
4011 break;
4012
4013 case 1:
4014 // The case where the disk health is NOT OK
4015 print_on();
4016 jout("SMART overall-health self-assessment test result: FAILED!\n"
4017 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
4018 jglb["smart_status"]["passed"] = false;
4019 print_off();
4020 if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
4021 returnval|=FAILATTR;
4022 if (options.smart_vendor_attrib)
4023 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
4024 else {
4025 print_on();
4026 pout("Failed Attributes:\n");
4027 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 1, options.output_format);
4028 }
4029 }
4030 else
4031 pout("No failed Attributes found.\n\n");
4032 returnval|=FAILSTATUS;
4033 print_off();
4034 break;
4035
4036 case -1:
4037 default:
4038 // Something went wrong with the SMART STATUS command.
4039 // The ATA SMART RETURN STATUS command provides the result in the ATA output
4040 // registers. Buggy ATA/SATA drivers and SAT Layers often do not properly
4041 // return the registers values.
4042 pout("SMART Status %s: %s\n",
4043 (device->is_syscall_unsup() ? "not supported" : "command failed"),
4044 device->get_errmsg());
4045 failuretest(OPTIONAL_CMD, returnval | FAILSMART);
4046 if (!(device->is_syscall_unsup() && smart_val_ok && smart_thres_ok))
4047 returnval |= FAILSMART; // Unknown error or attribute check not possible
4048
4049 if (!(smart_val_ok && smart_thres_ok)) {
4050 print_on();
4051 pout("SMART overall-health self-assessment test result: UNKNOWN!\n"
4052 "SMART Status, Attributes and Thresholds cannot be read.\n\n");
4053 }
4054 else if (find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
4055 print_on();
4056 jout("SMART overall-health self-assessment test result: FAILED!\n"
4057 "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
4058 jwrn("Warning: This result is based on an Attribute check.\n");
4059 jglb["smart_status"]["passed"] = false;
4060 print_off();
4061 returnval|=FAILATTR;
4062 returnval|=FAILSTATUS;
4063 if (options.smart_vendor_attrib)
4064 pout("See vendor-specific Attribute list for failed Attributes.\n\n");
4065 else {
4066 print_on();
4067 pout("Failed Attributes:\n");
4068 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 1, options.output_format);
4069 }
4070 }
4071 else {
4072 jout("SMART overall-health self-assessment test result: PASSED\n");
4073 jwrn("Warning: This result is based on an Attribute check.\n");
4074 jglb["smart_status"]["passed"] = true;
4075 if (find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
4076 if (options.smart_vendor_attrib)
4077 pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
4078 else {
4079 print_on();
4080 pout("Please note the following marginal Attributes:\n");
4081 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm, 2, options.output_format);
4082 }
4083 returnval|=FAILAGE;
4084 }
4085 else
4086 pout("\n");
4087 }
4088 print_off();
4089 break;
4090 } // end of switch statement
4091
4092 print_off();
4093 } // end of checking SMART Status
4094
4095 // Print general SMART values
4096 if (smart_val_ok && options.smart_general_values)
4097 PrintGeneralSmartValues(&smartval, &drive, firmwarebugs);
4098
4099 // Print vendor-specific attributes
4100 if (smart_val_ok && options.smart_vendor_attrib) {
4101 print_on();
4102 PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, rpm,
4103 (printing_is_switchable ? 2 : 0), options.output_format);
4104 print_off();
4105 }
4106
4107 // If GP Log is supported use smart log directory for
4108 // error and selftest log support check.
4109 bool gp_log_supported = isGeneralPurposeLoggingCapable(&drive);
4110 if ( gp_log_supported
4111 && ( options.smart_error_log || options.smart_selftest_log
4112 || options.retry_error_log || options.retry_selftest_log))
4113 need_smart_logdir = true;
4114
4115 ata_smart_log_directory smartlogdir_buf, gplogdir_buf;
4116 const ata_smart_log_directory * smartlogdir = 0, * gplogdir = 0;
4117
4118 // Read SMART Log directory
4119 if (need_smart_logdir) {
4120 if (firmwarebugs.is_set(BUG_NOLOGDIR))
4121 smartlogdir = fake_logdir(&smartlogdir_buf, options);
4122 else if (ataReadLogDirectory(device, &smartlogdir_buf, false)) {
4123 pout("Read SMART Log Directory failed: %s\n\n", device->get_errmsg());
4124 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4125 }
4126 else
4127 smartlogdir = &smartlogdir_buf;
4128 }
4129
4130 // Read GP Log directory
4131 if (need_gp_logdir) {
4132 if (firmwarebugs.is_set(BUG_NOLOGDIR))
4133 gplogdir = fake_logdir(&gplogdir_buf, options);
4134 else if (!gp_log_supported && !is_permissive()) {
4135 if (options.gp_logdir)
4136 pout("General Purpose Log Directory not supported\n\n");
4137 }
4138 else if (ataReadLogDirectory(device, &gplogdir_buf, true)) {
4139 pout("Read GP Log Directory failed\n\n");
4140 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4141 }
4142 else
4143 gplogdir = &gplogdir_buf;
4144 }
4145
4146 // Print log directories
4147 if ((options.gp_logdir && gplogdir) || (options.smart_logdir && smartlogdir)) {
4148 if (firmwarebugs.is_set(BUG_NOLOGDIR))
4149 pout("Log Directories not read due to '-F nologdir' option\n\n");
4150 else
4151 PrintLogDirectories(gplogdir, smartlogdir);
4152 }
4153
4154 // Print log pages
4155 for (i = 0; i < options.log_requests.size(); i++) {
4156 const ata_log_request & req = options.log_requests[i];
4157
4158 const char * type;
4159 unsigned max_nsectors;
4160 if (req.gpl) {
4161 type = "General Purpose";
4162 max_nsectors = GetNumLogSectors(gplogdir, req.logaddr, true);
4163 }
4164 else {
4165 type = "SMART";
4166 max_nsectors = GetNumLogSectors(smartlogdir, req.logaddr, false);
4167 }
4168
4169 if (!max_nsectors) {
4170 if (!is_permissive()) {
4171 pout("%s Log 0x%02x does not exist (override with '-T permissive' option)\n", type, req.logaddr);
4172 continue;
4173 }
4174 max_nsectors = req.page+1;
4175 }
4176 if (max_nsectors <= req.page) {
4177 pout("%s Log 0x%02x has only %u sectors, output skipped\n", type, req.logaddr, max_nsectors);
4178 continue;
4179 }
4180
4181 unsigned ns = req.nsectors;
4182 if (ns > max_nsectors - req.page) {
4183 if (req.nsectors != ~0U) // "FIRST-max"
4184 pout("%s Log 0x%02x has only %u sectors, output truncated\n", type, req.logaddr, max_nsectors);
4185 ns = max_nsectors - req.page;
4186 }
4187
4188 // SMART log don't support sector offset, start with first sector
4189 unsigned offs = (req.gpl ? 0 : req.page);
4190
4191 raw_buffer log_buf((offs + ns) * 512);
4192 bool ok;
4193 if (req.gpl)
4194 ok = ataReadLogExt(device, req.logaddr, 0x00, req.page, log_buf.data(), ns);
4195 else
4196 ok = ataReadSmartLog(device, req.logaddr, log_buf.data(), offs + ns);
4197 if (!ok)
4198 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4199 else
4200 PrintLogPages(type, log_buf.data() + offs*512, req.logaddr, req.page, ns, max_nsectors);
4201 }
4202
4203 // Print SMART Extendend Comprehensive Error Log
4204 bool do_smart_error_log = options.smart_error_log;
4205 if (options.smart_ext_error_log) {
4206 bool ok = false;
4207 unsigned nsectors = GetNumLogSectors(gplogdir, 0x03, true);
4208 if (!nsectors)
4209 pout("SMART Extended Comprehensive Error Log (GP Log 0x03) not supported\n\n");
4210 else {
4211 // Read only first sector to get error count and index
4212 // Print function will read more sectors as needed
4213 ata_smart_exterrlog log_03; memset(&log_03, 0, sizeof(log_03));
4214 if (!ataReadExtErrorLog(device, &log_03, 0, 1, firmwarebugs)) {
4215 pout("Read SMART Extended Comprehensive Error Log failed\n\n");
4216 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4217 }
4218 else {
4219 if (PrintSmartExtErrorLog(device, firmwarebugs, &log_03, nsectors, options.smart_ext_error_log))
4220 returnval |= FAILERR;
4221 ok = true;
4222 }
4223 }
4224
4225 if (!ok) {
4226 if (options.retry_error_log)
4227 do_smart_error_log = true;
4228 else if (!do_smart_error_log)
4229 pout("Try '-l [xerror,]error' to read traditional SMART Error Log\n");
4230 }
4231 }
4232
4233 // Print SMART error log
4234 if (do_smart_error_log) {
4235 if (!( GetNumLogSectors(smartlogdir, 0x01, false)
4236 || ( !(smartlogdir && gp_log_supported)
4237 && isSmartErrorLogCapable(&smartval, &drive))
4238 || is_permissive() )) {
4239 pout("SMART Error Log not supported\n\n");
4240 }
4241 else {
4242 ata_smart_errorlog smarterror; memset(&smarterror, 0, sizeof(smarterror));
4243 if (ataReadErrorLog(device, &smarterror, firmwarebugs)) {
4244 pout("Read SMART Error Log failed: %s\n\n", device->get_errmsg());
4245 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4246 }
4247 else {
4248 // quiet mode is turned on inside PrintSmartErrorLog()
4249 if (PrintSmartErrorlog(&smarterror, firmwarebugs))
4250 returnval|=FAILERR;
4251 print_off();
4252 }
4253 }
4254 }
4255
4256 // Print SMART Extendend Self-test Log
4257 bool do_smart_selftest_log = options.smart_selftest_log;
4258 if (options.smart_ext_selftest_log) {
4259 bool ok = false;
4260 unsigned nsectors = GetNumLogSectors(gplogdir, 0x07, true);
4261 if (!nsectors)
4262 pout("SMART Extended Self-test Log (GP Log 0x07) not supported\n\n");
4263 else if (nsectors >= 256)
4264 pout("SMART Extended Self-test Log size %u not supported\n\n", nsectors);
4265 else {
4266 raw_buffer log_07_buf(nsectors * 512);
4267 ata_smart_extselftestlog * log_07 = reinterpret_cast<ata_smart_extselftestlog *>(log_07_buf.data());
4268 if (!ataReadExtSelfTestLog(device, log_07, nsectors)) {
4269 pout("Read SMART Extended Self-test Log failed\n\n");
4270 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4271 }
4272 else {
4273 if (PrintSmartExtSelfTestLog(log_07, nsectors, options.smart_ext_selftest_log))
4274 returnval |= FAILLOG;
4275 ok = true;
4276 }
4277 }
4278
4279 if (!ok) {
4280 if (options.retry_selftest_log)
4281 do_smart_selftest_log = true;
4282 else if (!do_smart_selftest_log)
4283 pout("Try '-l [xselftest,]selftest' to read traditional SMART Self Test Log\n");
4284 }
4285 }
4286
4287 // Print SMART self-test log
4288 if (do_smart_selftest_log) {
4289 if (!( GetNumLogSectors(smartlogdir, 0x06, false)
4290 || ( !(smartlogdir && gp_log_supported)
4291 && isSmartTestLogCapable(&smartval, &drive))
4292 || is_permissive() )) {
4293 pout("SMART Self-test Log not supported\n\n");
4294 }
4295 else {
4296 ata_smart_selftestlog smartselftest; memset(&smartselftest, 0, sizeof(smartselftest));
4297 if (ataReadSelfTestLog(device, &smartselftest, firmwarebugs)) {
4298 pout("Read SMART Self-test Log failed: %s\n\n", device->get_errmsg());
4299 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4300 }
4301 else {
4302 print_on();
4303 if (ataPrintSmartSelfTestlog(&smartselftest, !printing_is_switchable, firmwarebugs))
4304 returnval |= FAILLOG;
4305 print_off();
4306 pout("\n");
4307 }
4308 }
4309 }
4310
4311 // Print SMART selective self-test log
4312 if (options.smart_selective_selftest_log) {
4314
4315 if (!isSupportSelectiveSelfTest(&smartval))
4316 pout("Selective Self-tests/Logging not supported\n\n");
4317 else if(ataReadSelectiveSelfTestLog(device, &log)) {
4318 pout("Read SMART Selective Self-test Log failed: %s\n\n", device->get_errmsg());
4319 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4320 }
4321 else {
4322 print_on();
4323 // If any errors were found, they are logged in the SMART Self-test log.
4324 // So there is no need to print the Selective Self Test log in silent
4325 // mode.
4327 ataPrintSelectiveSelfTestLog(&log, &smartval);
4328 print_off();
4329 pout("\n");
4330 }
4331 }
4332
4333 // Check if SCT commands available
4334 bool sct_ok = isSCTCapable(&drive);
4335 if ( options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int
4336 || options.sct_erc_get || options.sct_erc_set ) {
4337 if (!sct_ok)
4338 pout("SCT Commands not supported\n\n");
4339 else if (locked) {
4340 pout("SCT Commands not supported if ATA Security is LOCKED\n\n");
4341 sct_ok = false;
4342 }
4343 }
4344
4345 // Print SCT status and temperature history table
4346 if (sct_ok && (options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int)) {
4347 for (;;) {
4348 bool sct_temp_hist_ok = isSCTDataTableCapable(&drive);
4350
4351 if (options.sct_temp_sts || (options.sct_temp_hist && sct_temp_hist_ok)) {
4352 // Read SCT status
4353 if (ataReadSCTStatus(device, &sts)) {
4354 pout("\n");
4355 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4356 break;
4357 }
4358 if (options.sct_temp_sts) {
4359 ataPrintSCTStatus(&sts);
4360 pout("\n");
4361 }
4362 }
4363
4364 if (!sct_temp_hist_ok && (options.sct_temp_hist || options.sct_temp_int)) {
4365 pout("SCT Data Table command not supported\n\n");
4366 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4367 break;
4368 }
4369
4370 if (options.sct_temp_hist) {
4371 // Read SCT temperature history,
4372 // requires initial SCT status from above
4374 if (ataReadSCTTempHist(device, &tmh, &sts)) {
4375 pout("Read SCT Temperature History failed\n\n");
4376 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4377 break;
4378 }
4379 ataPrintSCTTempHist(&tmh);
4380 pout("\n");
4381 }
4382
4383 if (options.sct_temp_int) {
4384 // Set new temperature logging interval
4385 if (!isSCTFeatureControlCapable(&drive)) {
4386 pout("SCT Feature Control command not supported\n\n");
4387 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4388 break;
4389 }
4390 if (ataSetSCTTempInterval(device, options.sct_temp_int, options.sct_temp_int_pers)) {
4391 pout("Write Temperature Logging Interval failed\n\n");
4392 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4393 break;
4394 }
4395 pout("Temperature Logging Interval set to %u minute%s (%s)\n",
4396 options.sct_temp_int, (options.sct_temp_int == 1 ? "" : "s"),
4397 (options.sct_temp_int_pers ? "persistent" : "volatile"));
4398 }
4399 break;
4400 }
4401 }
4402
4403 // SCT Error Recovery Control
4404 if (sct_ok && (options.sct_erc_get || options.sct_erc_set)) {
4405 if (!isSCTErrorRecoveryControlCapable(&drive)) {
4406 pout("SCT Error Recovery Control command not supported\n\n");
4407 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4408 }
4409 else {
4410 int sct_erc_get = options.sct_erc_get;
4411 if (options.sct_erc_set) {
4412 // Set SCT Error Recovery Control
4413 bool set_power_on = (options.sct_erc_set == 2), mfg_default = (options.sct_erc_set == 3);
4414 if ( ataSetSCTErrorRecoveryControltime(device, 1, options.sct_erc_readtime, set_power_on, mfg_default)
4415 || ataSetSCTErrorRecoveryControltime(device, 2, options.sct_erc_writetime, set_power_on, mfg_default)) {
4416 pout("SCT (Set) Error Recovery Control command failed\n");
4417 if (!( (options.sct_erc_readtime == 70 && options.sct_erc_writetime == 70)
4418 || (options.sct_erc_readtime == 0 && options.sct_erc_writetime == 0)))
4419 pout("Retry with: 'scterc,70,70' to enable ERC or 'scterc,0,0' to disable\n");
4420 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4421 sct_erc_get = 0;
4422 }
4423 else if (!sct_erc_get)
4425 options.sct_erc_writetime, set_power_on, mfg_default);
4426 }
4427
4428 if (sct_erc_get) {
4429 // Print SCT Error Recovery Control
4430 bool get_power_on = (sct_erc_get == 2);
4431 unsigned short read_timer, write_timer;
4432 if ( ataGetSCTErrorRecoveryControltime(device, 1, read_timer, get_power_on)
4433 || ataGetSCTErrorRecoveryControltime(device, 2, write_timer, get_power_on)) {
4434 pout("SCT (Get) Error Recovery Control command failed\n");
4435 if (options.sct_erc_set == sct_erc_get) {
4436 pout("The previous SCT (Set) Error Recovery Control command succeeded\n");
4438 options.sct_erc_writetime, get_power_on);
4439 }
4440 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4441 }
4442 else
4443 ataPrintSCTErrorRecoveryControl(false, read_timer, write_timer, get_power_on);
4444 }
4445 pout("\n");
4446 }
4447 }
4448
4449 // Print Device Statistics
4450 if (options.devstat_all_pages || options.devstat_ssd_page || !options.devstat_pages.empty()) {
4451 bool use_gplog = true;
4452 unsigned nsectors = 0;
4453 if (gplogdir)
4454 nsectors = GetNumLogSectors(gplogdir, 0x04, true);
4455 else if (smartlogdir){ // for systems without ATA_READ_LOG_EXT
4456 nsectors = GetNumLogSectors(smartlogdir, 0x04, false);
4457 use_gplog = false;
4458 }
4459 if (!nsectors)
4460 pout("Device Statistics (GP/SMART Log 0x04) not supported\n\n");
4461 else if (!print_device_statistics(device, nsectors, options.devstat_pages,
4462 options.devstat_all_pages, options.devstat_ssd_page, use_gplog))
4463 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4464 }
4465
4466 // Print Pending Defects log
4467 if (options.pending_defects_log) {
4468 unsigned nsectors = GetNumLogSectors(gplogdir, 0x0c, true);
4469 if (!nsectors)
4470 pout("Pending Defects log (GP Log 0x0c) not supported\n\n");
4471 else if (!print_pending_defects_log(device, nsectors, options.pending_defects_log))
4472 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4473 }
4474
4475 // Print SATA Phy Event Counters
4476 if (options.sataphy) {
4477 unsigned nsectors = GetNumLogSectors(gplogdir, 0x11, true);
4478 // Packet interface devices do not provide a log directory, check support bit
4479 if (!nsectors && (drive.words047_079[76-47] & 0x0401) == 0x0400)
4480 nsectors = 1;
4481 if (!nsectors)
4482 pout("SATA Phy Event Counters (GP Log 0x11) not supported\n\n");
4483 else if (nsectors != 1)
4484 pout("SATA Phy Event Counters with %u sectors not supported\n\n", nsectors);
4485 else {
4486 unsigned char log_11[512] = {0, };
4487 unsigned char features = (options.sataphy_reset ? 0x01 : 0x00);
4488 if (!ataReadLogExt(device, 0x11, features, 0, log_11, 1)) {
4489 pout("Read SATA Phy Event Counters failed\n\n");
4490 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4491 }
4492 else
4494 }
4495 }
4496 // Print ATA FARM log for Seagate ATA drive
4497 if (options.farm_log || options.farm_log_suggest) {
4498 bool farm_supported = true;
4499 // Check if drive is a Seagate drive
4500 if (ataIsSeagate(drive, dbentry)) {
4501 unsigned nsectors = GetNumLogSectors(gplogdir, 0xA6, true);
4502 // Check if the Seagate drive is one that supports FARM
4503 if (!nsectors) {
4504 if (options.farm_log) {
4505 jout("\nFARM log (GP Log 0xA6) not supported\n\n");
4506 }
4507 farm_supported = false;
4508 } else {
4509 // If -x/-xall or -a/-all is run without explicit -l farm, suggests FARM log
4510 if (options.farm_log_suggest && !options.farm_log) {
4511 jout("Seagate FARM log supported [try: -l farm]\n\n");
4512 // Otherwise, actually pull the FARM log
4513 } else {
4514 ataFarmLog farmLog;
4515 if (!ataReadFarmLog(device, farmLog, nsectors)) {
4516 jout("\nRead FARM log (GP Log 0xA6) failed\n\n");
4517 farm_supported = false;
4518 } else {
4519 ataPrintFarmLog(farmLog);
4520 }
4521 }
4522 }
4523 } else {
4524 if (options.farm_log) {
4525 jout("FARM log (GP Log 0xA6) not supported for non-Seagate drives\n\n");
4526 }
4527 farm_supported = false;
4528 }
4529 jglb["seagate_farm_log"]["supported"] = farm_supported;
4530 }
4531 // Set to standby (spindown) mode and set standby timer if not done above
4532 // (Above commands may spinup drive)
4533 if (options.set_standby_now) {
4534 if (options.set_standby) {
4535 if (!ata_nodata_command(device, ATA_STANDBY, options.set_standby-1)) {
4536 pout("ATA STANDBY command failed: %s\n", device->get_errmsg());
4537 returnval |= FAILSMART;
4538 }
4539 else {
4540 print_standby_timer("Standby timer set to ", options.set_standby-1, drive);
4541 pout("Device placed in STANDBY mode\n");
4542 }
4543 }
4544 else {
4546 pout("ATA STANDBY IMMEDIATE command failed: %s\n", device->get_errmsg());
4547 returnval |= FAILSMART;
4548 }
4549 else
4550 pout("Device placed in STANDBY mode\n");
4551 }
4552 }
4553
4554 // START OF THE TESTING SECTION OF THE CODE. IF NO TESTING, RETURN
4555 if (!smart_val_ok || options.smart_selftest_type == -1)
4556 return returnval;
4557
4558 pout("=== START OF OFFLINE IMMEDIATE AND SELF-TEST SECTION ===\n");
4559 // if doing a self-test, be sure it's supported by the hardware
4560 switch (options.smart_selftest_type) {
4561 case OFFLINE_FULL_SCAN:
4562 if (!isSupportExecuteOfflineImmediate(&smartval)){
4563 pout("Execute Offline Immediate function not supported\n\n");
4564 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4565 }
4566 break;
4567 case ABORT_SELF_TEST:
4568 case SHORT_SELF_TEST:
4569 case EXTEND_SELF_TEST:
4572 if (!isSupportSelfTest(&smartval)){
4573 pout("Self-test functions not supported\n\n");
4574 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4575 }
4576 break;
4579 if (!isSupportConveyanceSelfTest(&smartval)){
4580 pout("Conveyance Self-test functions not supported\n\n");
4581 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4582 }
4583 break;
4586 if (!isSupportSelectiveSelfTest(&smartval)){
4587 pout("Selective Self-test functions not supported\n\n");
4588 failuretest(MANDATORY_CMD, returnval|=FAILSMART);
4589 }
4590 break;
4591 default:
4592 break; // Vendor specific type
4593 }
4594
4595 // Now do the test. Note ataSmartTest prints its own error/success
4596 // messages
4597 if (ataSmartTest(device, options.smart_selftest_type, options.smart_selftest_force,
4598 options.smart_selective_args, &smartval, sizes.sectors ))
4599 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4600 else {
4601 // Tell user how long test will take to complete. This is tricky
4602 // because in the case of an Offline Full Scan, the completion
4603 // timer is volatile, and needs to be read AFTER the command is
4604 // given. If this will interrupt the Offline Full Scan, we don't
4605 // do it, just warn user.
4606 if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
4607 if (isSupportOfflineAbort(&smartval))
4608 pout("Note: giving further SMART commands will abort Offline testing\n");
4609 else if (ataReadSmartValues(device, &smartval)){
4610 pout("Read SMART Data failed: %s\n\n", device->get_errmsg());
4611 failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
4612 }
4613 }
4614
4615 // Now say how long the test will take to complete
4616 int timewait = TestTime(&smartval, options.smart_selftest_type);
4617 if (timewait) {
4618 time_t t=time(NULL);
4619 if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
4620 t+=timewait;
4621 pout("Please wait %d seconds for test to complete.\n", (int)timewait);
4622 } else {
4623 t+=timewait*60;
4624 pout("Please wait %d minutes for test to complete.\n", (int)timewait);
4625 }
4626 char comptime[DATEANDEPOCHLEN];
4627 dateandtimezoneepoch(comptime, t);
4628 pout("Test will complete after %s\n", comptime);
4629
4634 pout("Use smartctl -X to abort test.\n");
4635 }
4636 }
4637
4638 return returnval;
4639}
const char * look_up_ata_command(unsigned char c_code, unsigned char f_reg)
bool ata_nodata_command(ata_device *device, unsigned char command, int sector_count)
Definition: atacmds.cpp:787
int ataDisableAutoOffline(ata_device *device)
Definition: atacmds.cpp:1581
unsigned char ata_return_temperature_value(const ata_smart_values *data, const ata_vendor_attr_defs &defs)
Definition: atacmds.cpp:2159
bool isSmartErrorLogCapable(const ata_smart_values *data, const ata_identify_device *identity)
Definition: atacmds.cpp:1731
int ataGetSCTErrorRecoveryControltime(ata_device *device, unsigned type, unsigned short &time_limit, bool power_on)
Definition: atacmds.cpp:2510
bool ataReadSmartLog(ata_device *device, unsigned char logaddr, void *data, unsigned nsectors)
Definition: atacmds.cpp:1143
int ata_get_wwn(const ata_identify_device *id, unsigned &oui, uint64_t &unique_id)
Definition: atacmds.cpp:900
int ataSmartTest(ata_device *device, int testtype, bool force, const ata_selective_selftest_args &selargs, const ata_smart_values *sv, uint64_t num_sectors)
Definition: atacmds.cpp:1611
int ataEnableAutoOffline(ata_device *device)
Definition: atacmds.cpp:1570
int ataSmartStatus2(ata_device *device)
Definition: atacmds.cpp:1604
int ataSmartSupport(const ata_identify_device *drive)
Definition: atacmds.cpp:936
int ataDisableAutoSave(ata_device *device)
Definition: atacmds.cpp:1558
int ata_get_rotation_rate(const ata_identify_device *id)
Definition: atacmds.cpp:920
bool ataReadLogExt(ata_device *device, unsigned char logaddr, unsigned char features, unsigned page, void *data, unsigned nsectors)
Definition: atacmds.cpp:1111
int ataEnableAutoSave(ata_device *device)
Definition: atacmds.cpp:1551
int ataReadSelfTestLog(ata_device *device, ata_smart_selftestlog *data, firmwarebug_defs firmwarebugs)
Definition: atacmds.cpp:1013
std::string ata_format_attr_raw_value(const ata_smart_attribute &attr, const ata_vendor_attr_defs &defs)
Definition: atacmds.cpp:1920
int ataReadSCTTempHist(ata_device *device, ata_sct_temperature_history_table *tmh, ata_sct_status_response *sts)
Definition: atacmds.cpp:2220
int ataReadErrorLog(ata_device *device, ata_smart_errorlog *data, firmwarebug_defs firmwarebugs)
Definition: atacmds.cpp:1424
void ata_get_size_info(const ata_identify_device *id, ata_size_info &sizes)
Definition: atacmds.cpp:658
int ata_read_identity(ata_device *device, ata_identify_device *buf, bool fix_swapped_id, unsigned char *raw_buf)
Definition: atacmds.cpp:817
int TestTime(const ata_smart_values *data, int testtype)
Definition: atacmds.cpp:1700
int ataEnableSmart(ata_device *device)
Definition: atacmds.cpp:1536
bool isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
Definition: atacmds.cpp:1769
int ataCheckPowerMode(ata_device *device)
Definition: atacmds.cpp:777
int ataGetSetSCTWriteCacheReordering(ata_device *device, bool enable, bool persistent, bool set)
Definition: atacmds.cpp:2349
unsigned char checksum(const void *data)
Definition: atacmds.cpp:716
bool ataReadExtSelfTestLog(ata_device *device, ata_smart_extselftestlog *log, unsigned nsectors)
Definition: atacmds.cpp:1061
int ataReadSelectiveSelfTestLog(ata_device *device, struct ata_selective_self_test_log *data)
Definition: atacmds.cpp:1184
bool isSmartTestLogCapable(const ata_smart_values *data, const ata_identify_device *identity)
Definition: atacmds.cpp:1750
int ataReadSmartValues(ata_device *device, struct ata_smart_values *data)
Definition: atacmds.cpp:967
int ataSetSCTErrorRecoveryControltime(ata_device *device, unsigned type, unsigned short time_limit, bool power_on, bool mfg_default)
Definition: atacmds.cpp:2516
int ataDoesSmartWork(ata_device *device)
Definition: atacmds.cpp:1593
uint64_t ata_get_attr_raw_value(const ata_smart_attribute &attr, const ata_vendor_attr_defs &defs)
Definition: atacmds.cpp:1846
bool dont_print_serial_number
Definition: atacmds.cpp:37
int ataReadSCTStatus(ata_device *device, ata_sct_status_response *sts)
Definition: atacmds.cpp:2188
bool ataReadExtErrorLog(ata_device *device, ata_smart_exterrlog *log, unsigned page, unsigned nsectors, firmwarebug_defs firmwarebugs)
Definition: atacmds.cpp:1491
int ataDisableSmart(ata_device *device)
Definition: atacmds.cpp:1543
int ataSetSCTTempInterval(ata_device *device, unsigned interval, bool persistent)
Definition: atacmds.cpp:2363
std::string ata_get_smart_attr_name(unsigned char id, const ata_vendor_attr_defs &defs, int rpm)
Definition: atacmds.cpp:2127
int ataGetSetSCTWriteCache(ata_device *device, unsigned short state, bool persistent, bool set)
Definition: atacmds.cpp:2356
int ataReadSmartThresholds(ata_device *device, struct ata_smart_thresholds_pvt *data)
Definition: atacmds.cpp:1518
int ataIsSmartEnabled(const ata_identify_device *drive)
Definition: atacmds.cpp:951
void ata_format_id_string(char *out, const unsigned char *in, int n)
Definition: atacmds.cpp:762
int ataReadLogDirectory(ata_device *device, ata_smart_log_directory *data, bool gpl)
Definition: atacmds.cpp:1164
bool ata_set_features(ata_device *device, unsigned char features, int sector_count)
Definition: atacmds.cpp:799
ata_attr_state ata_get_attr_state(const ata_smart_attribute &attr, int attridx, const ata_smart_threshold_entry *thresholds, const ata_vendor_attr_defs &defs, unsigned char *threshval)
Definition: atacmds.cpp:1796
#define ATA_ENABLE_READ_LOOK_AHEAD
Definition: atacmds.h:72
#define ATTRIBUTE_FLAGS_OTHER(x)
Definition: atacmds.h:192
#define SELECTIVE_FLAG_PENDING
Definition: atacmds.h:500
#define ATA_DISABLE_WRITE_CACHE
Definition: atacmds.h:67
#define ATTRIBUTE_FLAGS_SELFPRESERVING(x)
Definition: atacmds.h:189
bool isSupportSelfTest(const ata_smart_values *data)
Definition: atacmds.h:877
#define ATA_STANDBY
Definition: atacmds.h:61
#define SELECTIVE_SELF_TEST
Definition: atacmds.h:101
bool isSCTErrorRecoveryControlCapable(const ata_identify_device *drive)
Definition: atacmds.h:889
#define ATA_ENABLE_APM
Definition: atacmds.h:70
#define ATA_STANDBY_IMMEDIATE
Definition: atacmds.h:62
bool isSupportOfflineSurfaceScan(const ata_smart_values *data)
Definition: atacmds.h:874
#define ATA_DISABLE_AAM
Definition: atacmds.h:65
#define OFFLINE_FULL_SCAN
Definition: atacmds.h:97
#define SHORT_SELF_TEST
Definition: atacmds.h:98
#define SELECTIVE_FLAG_DOSCAN
Definition: atacmds.h:499
bool isSupportConveyanceSelfTest(const ata_smart_values *data)
Definition: atacmds.h:880
#define ATA_ENABLE_DISABLE_DSN
Definition: atacmds.h:73
#define ATA_IDLE
Definition: atacmds.h:55
void checksumwarning(const char *string)
Definition: smartctl.cpp:1482
@ RAWFMT_MIN2HOUR
Definition: atacmds.h:665
@ RAWFMT_RAW16_OPT_RAW16
Definition: atacmds.h:659
@ RAWFMT_RAW24_OPT_RAW8
Definition: atacmds.h:661
@ RAWFMT_MSEC24_HOUR32
Definition: atacmds.h:667
@ RAWFMT_RAW64
Definition: atacmds.h:657
@ RAWFMT_RAW48
Definition: atacmds.h:653
@ RAWFMT_DEFAULT
Definition: atacmds.h:650
@ RAWFMT_HALFMIN2HOUR
Definition: atacmds.h:666
@ RAWFMT_SEC2HOUR
Definition: atacmds.h:664
#define ATTRIBUTE_FLAGS_EVENTCOUNT(x)
Definition: atacmds.h:186
#define ATTRIBUTE_FLAGS_PERFORMANCE(x)
Definition: atacmds.h:180
bool isSupportAutomaticTimer(const ata_smart_values *data)
Definition: atacmds.h:868
@ ATTRFLAG_NO_WORSTVAL
Definition: atacmds.h:676
#define EXTEND_SELF_TEST
Definition: atacmds.h:99
#define ATA_ENABLE_WRITE_CACHE
Definition: atacmds.h:71
bool isSupportSelectiveSelfTest(const ata_smart_values *data)
Definition: atacmds.h:883
bool isSCTDataTableCapable(const ata_identify_device *drive)
Definition: atacmds.h:895
#define ATA_DISABLE_READ_LOOK_AHEAD
Definition: atacmds.h:68
#define ATTRIBUTE_FLAGS_PREFAILURE(x)
Definition: atacmds.h:164
#define ATA_ENABLE_AAM
Definition: atacmds.h:69
bool isSupportExecuteOfflineImmediate(const ata_smart_values *data)
Definition: atacmds.h:862
bool isSupportOfflineAbort(const ata_smart_values *data)
Definition: atacmds.h:871
#define ABORT_SELF_TEST
Definition: atacmds.h:102
#define SELECTIVE_FLAG_ACTIVE
Definition: atacmds.h:501
#define ATTRIBUTE_FLAGS_ERRORRATE(x)
Definition: atacmds.h:183
#define EXTEND_CAPTIVE_SELF_TEST
Definition: atacmds.h:104
#define CONVEYANCE_CAPTIVE_SELF_TEST
Definition: atacmds.h:105
#define CONVEYANCE_SELF_TEST
Definition: atacmds.h:100
@ BUG_SAMSUNG3
Definition: atacmds.h:717
@ BUG_NOLOGDIR
Definition: atacmds.h:714
@ BUG_SAMSUNG
Definition: atacmds.h:715
@ BUG_SAMSUNG2
Definition: atacmds.h:716
#define ATA_SECURITY_FREEZE_LOCK
Definition: atacmds.h:57
#define SHORT_CAPTIVE_SELF_TEST
Definition: atacmds.h:103
#define ATA_DISABLE_APM
Definition: atacmds.h:66
#define NUMBER_ATA_SMART_ATTRIBUTES
Definition: atacmds.h:110
#define SELECTIVE_CAPTIVE_SELF_TEST
Definition: atacmds.h:106
#define ATTRIBUTE_FLAGS_ONLINE(x)
Definition: atacmds.h:174
bool isSCTFeatureControlCapable(const ata_identify_device *drive)
Definition: atacmds.h:892
bool isSCTCapable(const ata_identify_device *drive)
Definition: atacmds.h:886
ata_attr_state
Definition: atacmds.h:902
@ ATTRSTATE_FAILED_NOW
Definition: atacmds.h:908
@ ATTRSTATE_NON_EXISTING
Definition: atacmds.h:903
@ ATTRSTATE_NO_THRESHOLD
Definition: atacmds.h:905
@ ATTRSTATE_FAILED_PAST
Definition: atacmds.h:907
@ ATTRSTATE_NO_NORMVAL
Definition: atacmds.h:904
void ata_print_identify_data(const void *id, bool all_words, int bit_level)
static void print_standby_timer(const char *msg, int timer, const ata_identify_device &drive)
Definition: ataprint.cpp:3307
static const char * sct_ptemp(signed char x, char(&buf)[20])
Definition: ataprint.cpp:2949
static void ataPrintSCTErrorRecoveryControl(bool set, unsigned short read_timer, unsigned short write_timer, bool power_on, bool mfg_default=false)
Definition: ataprint.cpp:3158
static void PrintSmartCapability(const ata_smart_values *data)
Definition: ataprint.cpp:1042
static const char * infofound(const char *output)
Definition: ataprint.cpp:40
const char * ataprint_cpp_cvsid
Definition: ataprint.cpp:36
static void ataPrintSCTCapability(const ata_identify_device *drive)
Definition: ataprint.cpp:1349
const devstat_entry_info devstat_info_0x04[]
Definition: ataprint.cpp:1696
static void PrintSmartTotalTimeCompleteOffline(const ata_smart_values *data)
Definition: ataprint.cpp:982
static void print_aam_level(const char *msg, int level, int recommended=-1)
Definition: ataprint.cpp:3183
const devstat_entry_info devstat_info_0x01[]
Definition: ataprint.cpp:1659
static void set_json_globals_from_device_statistics(int page, int offset, int64_t val)
Definition: ataprint.cpp:1761
static void print_sata_version_and_speed(unsigned short word222, unsigned short word076, unsigned short word077)
Definition: ataprint.cpp:616
static void print_ata_security_status(const char *msg, unsigned short state, unsigned short master_password_id)
Definition: ataprint.cpp:3244
static void PrintSmartOfflineCollectCap(const ata_smart_values *data)
Definition: ataprint.cpp:992
int ataPrintMain(ata_device *device, const ata_print_options &options)
Definition: ataprint.cpp:3341
static void PrintSmartOfflineStatus(const ata_smart_values *data)
Definition: ataprint.cpp:857
static void print_drive_info(const ata_identify_device *drive, const ata_size_info &sizes, int rpm, const drive_settings *dbentry, const char *dbversion)
Definition: ataprint.cpp:639
static void PrintSmartSelfExecStatus(const ata_smart_values *data, firmwarebug_defs firmwarebugs)
Definition: ataprint.cpp:885
const int num_devstat_infos
Definition: ataprint.cpp:1750
static const char * get_sata_version(unsigned short word222)
Definition: ataprint.cpp:554
const devstat_entry_info devstat_info_0x03[]
Definition: ataprint.cpp:1683
static void PrintSmartConveyanceSelfTestPollingTime(const ata_smart_values *data)
Definition: ataprint.cpp:1101
static bool is_permissive()
Definition: ataprint.cpp:46
const devstat_entry_info devstat_info_0x02[]
Definition: ataprint.cpp:1676
static int ataPrintSmartSelfTestlog(const ata_smart_selftestlog *log, bool allentries, firmwarebug_defs firmwarebugs)
Definition: ataprint.cpp:2654
static int PrintSmartErrorlog(const ata_smart_errorlog *data, firmwarebug_defs firmwarebugs)
Definition: ataprint.cpp:2184
static const char * get_ata_major_version(const ata_identify_device *drive)
Definition: ataprint.cpp:436
static const char * sct_device_state_msg(unsigned char state)
Definition: ataprint.cpp:2987
static const char * sct_pbar(int x, char(&buf)[64])
Definition: ataprint.cpp:2965
static std::string format_st_er_desc(unsigned char CR, unsigned char FR, unsigned char ST, unsigned char ER, unsigned short SC, const ata_smart_errorlog_error_struct *lba28_regs, const ata_smart_exterrlog_error *lba48_regs)
Definition: ataprint.cpp:67
static void ataPrintSelectiveSelfTestLog(const ata_selective_self_test_log *log, const ata_smart_values *sv)
Definition: ataprint.cpp:2806
static const char * get_pata_version(unsigned short word222, char(&buf)[32])
Definition: ataprint.cpp:541
static bool print_pending_defects_log(ata_device *device, unsigned nsectors, unsigned max_entries)
Definition: ataprint.cpp:2012
static void PrintSmartAttribWithThres(const ata_smart_values *data, const ata_smart_thresholds_pvt *thresholds, const ata_vendor_attr_defs &defs, int rpm, int onlyfailed, unsigned char format)
Definition: ataprint.cpp:1192
static void PrintSmartExtendedSelfTestPollingTime(const ata_smart_values *data)
Definition: ataprint.cpp:1088
#define P(n)
static void print_device_statistics_page(const json::ref &jref, const unsigned char *data, int page)
Definition: ataprint.cpp:1784
static bool print_device_statistics(ata_device *device, unsigned nsectors, const std::vector< int > &single_pages, bool all_pages, bool ssd_page, bool use_gplog)
Definition: ataprint.cpp:1895
static void PrintSataPhyEventCounters(const unsigned char *data, bool reset)
Definition: ataprint.cpp:2075
static void PrintSmartErrorLogCapability(const ata_smart_values *data, const ata_identify_device *identity)
Definition: ataprint.cpp:1067
static void PrintSmartShortSelfTestPollingTime(const ata_smart_values *data)
Definition: ataprint.cpp:1075
static const char * OfflineDataCollectionStatus(unsigned char status_byte)
Definition: ataprint.cpp:827
static int find_msb(unsigned short word)
Definition: ataprint.cpp:428
static std::string format_milliseconds(unsigned msec)
Definition: ataprint.cpp:2149
static void set_json_globals_from_smart_attrib(int id, const char *name, const ata_vendor_attr_defs &defs, uint64_t rawval)
Definition: ataprint.cpp:1138
static void PrintGeneralSmartValues(const ata_smart_values *data, const ata_identify_device *drive, firmwarebug_defs firmwarebugs)
Definition: ataprint.cpp:1369
static void PrintLogPages(const char *type, const unsigned char *data, unsigned char logaddr, unsigned page, unsigned num_pages, unsigned max_pages)
Definition: ataprint.cpp:1618
static void sct_jtemp2(const json::ref &jref, const char *name, signed char x)
Definition: ataprint.cpp:2957
static unsigned GetNumLogSectors(const ata_smart_log_directory *logdir, unsigned logaddr, bool gpl)
Definition: ataprint.cpp:1405
const ata_smart_log_directory * fake_logdir(ata_smart_log_directory *logdir, const ata_print_options &options)
Definition: ataprint.cpp:1513
static void print_apm_level(const char *msg, int level)
Definition: ataprint.cpp:3214
const devstat_entry_info devstat_info_0x07[]
Definition: ataprint.cpp:1731
static const char * get_error_log_state_desc(unsigned state)
Definition: ataprint.cpp:2168
static int ataPrintSCTTempHist(const ata_sct_temperature_history_table *tmh)
Definition: ataprint.cpp:3086
const devstat_entry_info devstat_info_0x00[]
Definition: ataprint.cpp:1654
static const char * get_log_rw(unsigned logaddr)
Definition: ataprint.cpp:1486
static const char * GetLogName(unsigned logaddr)
Definition: ataprint.cpp:1421
const devstat_entry_info devstat_info_0x05[]
Definition: ataprint.cpp:1705
static int PrintSmartExtSelfTestLog(const ata_smart_extselftestlog *log, unsigned nsectors, unsigned max_entries)
Definition: ataprint.cpp:2722
static void jset_sata_speed(const char *key, int value, int speed, const char *str)
Definition: ataprint.cpp:597
static const char * get_sata_speed(int speed)
Definition: ataprint.cpp:578
static int find_failed_attr(const ata_smart_values *data, const ata_smart_thresholds_pvt *thresholds, const ata_vendor_attr_defs &defs, int onlyfailed)
Definition: ataprint.cpp:1117
static int ataPrintSCTStatus(const ata_sct_status_response *sts)
Definition: ataprint.cpp:3001
static const char * get_device_statistics_page_name(int page)
Definition: ataprint.cpp:1752
const devstat_entry_info devstat_info_0x06[]
Definition: ataprint.cpp:1723
static const char * get_ata_minor_version(const ata_identify_device *drive)
Definition: ataprint.cpp:462
static int ataPrintSmartSelfTestEntry(const json::ref &jref, unsigned testnum, unsigned char test_type, unsigned char test_status, unsigned short timestamp, uint64_t failing_lba, bool print_error_only, bool &print_header)
Definition: ataprint.cpp:2559
static int PrintSmartExtErrorLog(ata_device *device, const firmwarebug_defs &firmwarebugs, const ata_smart_exterrlog *log, unsigned nsectors, unsigned max_errors)
Definition: ataprint.cpp:2338
static void PrintLogDirectories(const ata_smart_log_directory *gplogdir, const ata_smart_log_directory *smartlogdir)
Definition: ataprint.cpp:1529