Annotation of embedaddon/smartmontools/ataprint.cpp, revision 1.1.1.1
1.1 misho 1: /*
2: * ataprint.cpp
3: *
4: * Home page of code is: http://smartmontools.sourceforge.net
5: *
6: * Copyright (C) 2002-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7: * Copyright (C) 2008-11 Christian Franke <smartmontools-support@lists.sourceforge.net>
8: * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
9: *
10: * This program is free software; you can redistribute it and/or modify
11: * it under the terms of the GNU General Public License as published by
12: * the Free Software Foundation; either version 2, or (at your option)
13: * any later version.
14: *
15: * You should have received a copy of the GNU General Public License
16: * (for example COPYING); if not, write to the Free
17: * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18: *
19: * This code was originally developed as a Senior Thesis by Michael Cornwell
20: * at the Concurrent Systems Laboratory (now part of the Storage Systems
21: * Research Center), Jack Baskin School of Engineering, University of
22: * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
23: *
24: */
25:
26: #include "config.h"
27:
28: #include <ctype.h>
29: #include <errno.h>
30: #include <stdio.h>
31: #include <stdlib.h>
32: #include <string.h>
33:
34: #include "int64.h"
35: #include "atacmdnames.h"
36: #include "atacmds.h"
37: #include "dev_interface.h"
38: #include "ataprint.h"
39: #include "smartctl.h"
40: #include "utility.h"
41: #include "knowndrives.h"
42:
43: const char * ataprint_cpp_cvsid = "$Id: ataprint.cpp 3438 2011-10-11 21:36:27Z chrfranke $"
44: ATAPRINT_H_CVSID;
45:
46:
47: static const char * infofound(const char *output) {
48: return (*output ? output : "[No Information Found]");
49: }
50:
51: // Return true if '-T permissive' is specified,
52: // used to ignore missing capabilities
53: static bool is_permissive()
54: {
55: if (!failuretest_permissive)
56: return false;
57: failuretest_permissive--;
58: return true;
59: }
60:
61: /* For the given Command Register (CR) and Features Register (FR), attempts
62: * to construct a string that describes the contents of the Status
63: * Register (ST) and Error Register (ER). The caller passes the string
64: * buffer and the return value is a pointer to this string. If the
65: * meanings of the flags of the error register are not known for the given
66: * command then it returns NULL.
67: *
68: * The meanings of the flags of the error register for all commands are
69: * described in the ATA spec and could all be supported here in theory.
70: * Currently, only a few commands are supported (those that have been seen
71: * to produce errors). If many more are to be added then this function
72: * should probably be redesigned.
73: */
74:
75: static const char * construct_st_er_desc(
76: char * s,
77: unsigned char CR, unsigned char FR,
78: unsigned char ST, unsigned char ER,
79: unsigned short SC,
80: const ata_smart_errorlog_error_struct * lba28_regs,
81: const ata_smart_exterrlog_error * lba48_regs
82: )
83: {
84: const char *error_flag[8];
85: int i, print_lba=0, print_sector=0;
86:
87: // Set of character strings corresponding to different error codes.
88: // Please keep in alphabetic order if you add more.
89: const char *abrt = "ABRT"; // ABORTED
90: const char *amnf = "AMNF"; // ADDRESS MARK NOT FOUND
91: const char *ccto = "CCTO"; // COMMAND COMPLETION TIMED OUT
92: const char *eom = "EOM"; // END OF MEDIA
93: const char *icrc = "ICRC"; // INTERFACE CRC ERROR
94: const char *idnf = "IDNF"; // ID NOT FOUND
95: const char *ili = "ILI"; // MEANING OF THIS BIT IS COMMAND-SET SPECIFIC
96: const char *mc = "MC"; // MEDIA CHANGED
97: const char *mcr = "MCR"; // MEDIA CHANGE REQUEST
98: const char *nm = "NM"; // NO MEDIA
99: const char *obs = "obs"; // OBSOLETE
100: const char *tk0nf = "TK0NF"; // TRACK 0 NOT FOUND
101: const char *unc = "UNC"; // UNCORRECTABLE
102: const char *wp = "WP"; // WRITE PROTECTED
103:
104: /* If for any command the Device Fault flag of the status register is
105: * not used then used_device_fault should be set to 0 (in the CR switch
106: * below)
107: */
108: int uses_device_fault = 1;
109:
110: /* A value of NULL means that the error flag isn't used */
111: for (i = 0; i < 8; i++)
112: error_flag[i] = NULL;
113:
114: switch (CR) {
115: case 0x10: // RECALIBRATE
116: error_flag[2] = abrt;
117: error_flag[1] = tk0nf;
118: break;
119: case 0x20: /* READ SECTOR(S) */
120: case 0x21: // READ SECTOR(S)
121: case 0x24: // READ SECTOR(S) EXT
122: case 0xC4: /* READ MULTIPLE */
123: case 0x29: // READ MULTIPLE EXT
124: error_flag[6] = unc;
125: error_flag[5] = mc;
126: error_flag[4] = idnf;
127: error_flag[3] = mcr;
128: error_flag[2] = abrt;
129: error_flag[1] = nm;
130: error_flag[0] = amnf;
131: print_lba=1;
132: break;
133: case 0x22: // READ LONG (with retries)
134: case 0x23: // READ LONG (without retries)
135: error_flag[4] = idnf;
136: error_flag[2] = abrt;
137: error_flag[0] = amnf;
138: print_lba=1;
139: break;
140: case 0x2a: // READ STREAM DMA
141: case 0x2b: // READ STREAM PIO
142: if (CR==0x2a)
143: error_flag[7] = icrc;
144: error_flag[6] = unc;
145: error_flag[5] = mc;
146: error_flag[4] = idnf;
147: error_flag[3] = mcr;
148: error_flag[2] = abrt;
149: error_flag[1] = nm;
150: error_flag[0] = ccto;
151: print_lba=1;
152: print_sector=SC;
153: break;
154: case 0x3A: // WRITE STREAM DMA
155: case 0x3B: // WRITE STREAM PIO
156: if (CR==0x3A)
157: error_flag[7] = icrc;
158: error_flag[6] = wp;
159: error_flag[5] = mc;
160: error_flag[4] = idnf;
161: error_flag[3] = mcr;
162: error_flag[2] = abrt;
163: error_flag[1] = nm;
164: error_flag[0] = ccto;
165: print_lba=1;
166: print_sector=SC;
167: break;
168: case 0x25: // READ DMA EXT
169: case 0x26: // READ DMA QUEUED EXT
170: case 0xC7: // READ DMA QUEUED
171: case 0xC8: // READ DMA (with retries)
172: case 0xC9: // READ DMA (without retries, obsolete since ATA-5)
173: case 0x60: // READ FPDMA QUEUED (NCQ)
174: error_flag[7] = icrc;
175: error_flag[6] = unc;
176: error_flag[5] = mc;
177: error_flag[4] = idnf;
178: error_flag[3] = mcr;
179: error_flag[2] = abrt;
180: error_flag[1] = nm;
181: error_flag[0] = amnf;
182: print_lba=1;
183: if (CR==0x25 || CR==0xC8)
184: print_sector=SC;
185: break;
186: case 0x30: /* WRITE SECTOR(S) */
187: case 0x31: // WRITE SECTOR(S)
188: case 0x34: // WRITE SECTOR(S) EXT
189: case 0xC5: /* WRITE MULTIPLE */
190: case 0x39: // WRITE MULTIPLE EXT
191: case 0xCE: // WRITE MULTIPLE FUA EXT
192: error_flag[6] = wp;
193: error_flag[5] = mc;
194: error_flag[4] = idnf;
195: error_flag[3] = mcr;
196: error_flag[2] = abrt;
197: error_flag[1] = nm;
198: print_lba=1;
199: break;
200: case 0x32: // WRITE LONG (with retries)
201: case 0x33: // WRITE LONG (without retries)
202: error_flag[4] = idnf;
203: error_flag[2] = abrt;
204: print_lba=1;
205: break;
206: case 0x3C: // WRITE VERIFY
207: error_flag[6] = unc;
208: error_flag[4] = idnf;
209: error_flag[2] = abrt;
210: error_flag[0] = amnf;
211: print_lba=1;
212: break;
213: case 0x40: // READ VERIFY SECTOR(S) with retries
214: case 0x41: // READ VERIFY SECTOR(S) without retries
215: case 0x42: // READ VERIFY SECTOR(S) EXT
216: error_flag[6] = unc;
217: error_flag[5] = mc;
218: error_flag[4] = idnf;
219: error_flag[3] = mcr;
220: error_flag[2] = abrt;
221: error_flag[1] = nm;
222: error_flag[0] = amnf;
223: print_lba=1;
224: break;
225: case 0xA0: /* PACKET */
226: /* Bits 4-7 are all used for sense key (a 'command packet set specific error
227: * indication' according to the ATA/ATAPI-7 standard), so "Sense key" will
228: * be repeated in the error description string if more than one of those
229: * bits is set.
230: */
231: error_flag[7] = "Sense key (bit 3)",
232: error_flag[6] = "Sense key (bit 2)",
233: error_flag[5] = "Sense key (bit 1)",
234: error_flag[4] = "Sense key (bit 0)",
235: error_flag[2] = abrt;
236: error_flag[1] = eom;
237: error_flag[0] = ili;
238: break;
239: case 0xA1: /* IDENTIFY PACKET DEVICE */
240: case 0xEF: /* SET FEATURES */
241: case 0x00: /* NOP */
242: case 0xC6: /* SET MULTIPLE MODE */
243: error_flag[2] = abrt;
244: break;
245: case 0x2F: // READ LOG EXT
246: error_flag[6] = unc;
247: error_flag[4] = idnf;
248: error_flag[2] = abrt;
249: error_flag[0] = obs;
250: break;
251: case 0x3F: // WRITE LOG EXT
252: error_flag[4] = idnf;
253: error_flag[2] = abrt;
254: error_flag[0] = obs;
255: break;
256: case 0xB0: /* SMART */
257: switch(FR) {
258: case 0xD0: // SMART READ DATA
259: case 0xD1: // SMART READ ATTRIBUTE THRESHOLDS
260: case 0xD5: /* SMART READ LOG */
261: error_flag[6] = unc;
262: error_flag[4] = idnf;
263: error_flag[2] = abrt;
264: error_flag[0] = obs;
265: break;
266: case 0xD6: /* SMART WRITE LOG */
267: error_flag[4] = idnf;
268: error_flag[2] = abrt;
269: error_flag[0] = obs;
270: break;
271: case 0xD2: // Enable/Disable Attribute Autosave
272: case 0xD3: // SMART SAVE ATTRIBUTE VALUES (ATA-3)
273: case 0xD8: // SMART ENABLE OPERATIONS
274: case 0xD9: /* SMART DISABLE OPERATIONS */
275: case 0xDA: /* SMART RETURN STATUS */
276: case 0xDB: // Enable/Disable Auto Offline (SFF)
277: error_flag[2] = abrt;
278: break;
279: case 0xD4: // SMART EXECUTE IMMEDIATE OFFLINE
280: error_flag[4] = idnf;
281: error_flag[2] = abrt;
282: break;
283: default:
284: return NULL;
285: break;
286: }
287: break;
288: case 0xB1: /* DEVICE CONFIGURATION */
289: switch (FR) {
290: case 0xC0: /* DEVICE CONFIGURATION RESTORE */
291: error_flag[2] = abrt;
292: break;
293: default:
294: return NULL;
295: break;
296: }
297: break;
298: case 0xCA: // WRITE DMA (with retries)
299: case 0xCB: // WRITE DMA (without retries, obsolete since ATA-5)
300: case 0x35: // WRITE DMA EXT
301: case 0x3D: // WRITE DMA FUA EXT
302: case 0xCC: // WRITE DMA QUEUED
303: case 0x36: // WRITE DMA QUEUED EXT
304: case 0x3E: // WRITE DMA QUEUED FUA EXT
305: case 0x61: // WRITE FPDMA QUEUED (NCQ)
306: error_flag[7] = icrc;
307: error_flag[6] = wp;
308: error_flag[5] = mc;
309: error_flag[4] = idnf;
310: error_flag[3] = mcr;
311: error_flag[2] = abrt;
312: error_flag[1] = nm;
313: error_flag[0] = amnf;
314: print_lba=1;
315: if (CR==0x35)
316: print_sector=SC;
317: break;
318: case 0xE4: // READ BUFFER
319: case 0xE8: // WRITE BUFFER
320: error_flag[2] = abrt;
321: break;
322: default:
323: return NULL;
324: }
325:
326: s[0] = '\0';
327:
328: /* We ignore any status flags other than Device Fault and Error */
329:
330: if (uses_device_fault && (ST & (1 << 5))) {
331: strcat(s, "Device Fault");
332: if (ST & 1) // Error flag
333: strcat(s, "; ");
334: }
335: if (ST & 1) { // Error flag
336: int count = 0;
337:
338: strcat(s, "Error: ");
339: for (i = 7; i >= 0; i--)
340: if ((ER & (1 << i)) && (error_flag[i])) {
341: if (count++ > 0)
342: strcat(s, ", ");
343: strcat(s, error_flag[i]);
344: }
345: }
346:
347: // If the error was a READ or WRITE error, print the Logical Block
348: // Address (LBA) at which the read or write failed.
349: if (print_lba) {
350: char tmp[128];
351: // print number of sectors, if known, and append to print string
352: if (print_sector) {
353: snprintf(tmp, 128, " %d sectors", print_sector);
354: strcat(s, tmp);
355: }
356:
357: if (lba28_regs) {
358: unsigned lba;
359: // bits 24-27: bits 0-3 of DH
360: lba = 0xf & lba28_regs->drive_head;
361: lba <<= 8;
362: // bits 16-23: CH
363: lba |= lba28_regs->cylinder_high;
364: lba <<= 8;
365: // bits 8-15: CL
366: lba |= lba28_regs->cylinder_low;
367: lba <<= 8;
368: // bits 0-7: SN
369: lba |= lba28_regs->sector_number;
370: snprintf(tmp, 128, " at LBA = 0x%08x = %u", lba, lba);
371: strcat(s, tmp);
372: }
373: else if (lba48_regs) {
374: // This assumes that upper LBA registers are 0 for 28-bit commands
375: // (TODO: detect 48-bit commands above)
376: uint64_t lba48;
377: lba48 = lba48_regs->lba_high_register_hi;
378: lba48 <<= 8;
379: lba48 |= lba48_regs->lba_mid_register_hi;
380: lba48 <<= 8;
381: lba48 |= lba48_regs->lba_low_register_hi;
382: lba48 |= lba48_regs->device_register & 0xf;
383: lba48 <<= 8;
384: lba48 |= lba48_regs->lba_high_register;
385: lba48 <<= 8;
386: lba48 |= lba48_regs->lba_mid_register;
387: lba48 <<= 8;
388: lba48 |= lba48_regs->lba_low_register;
389: snprintf(tmp, 128, " at LBA = 0x%08"PRIx64" = %"PRIu64, lba48, lba48);
390: strcat(s, tmp);
391: }
392: }
393:
394: return s;
395: }
396:
397: static inline const char * construct_st_er_desc(char * s,
398: const ata_smart_errorlog_struct * data)
399: {
400: return construct_st_er_desc(s,
401: data->commands[4].commandreg,
402: data->commands[4].featuresreg,
403: data->error_struct.status,
404: data->error_struct.error_register,
405: data->error_struct.sector_count,
406: &data->error_struct, (const ata_smart_exterrlog_error *)0);
407: }
408:
409: static inline const char * construct_st_er_desc(char * s,
410: const ata_smart_exterrlog_error_log * data)
411: {
412: return construct_st_er_desc(s,
413: data->commands[4].command_register,
414: data->commands[4].features_register,
415: data->error.status_register,
416: data->error.error_register,
417: data->error.count_register_hi << 8 | data->error.count_register,
418: (const ata_smart_errorlog_error_struct *)0, &data->error);
419: }
420:
421: static void print_drive_info(const ata_identify_device * drive,
422: const ata_size_info & sizes,
423: const drive_settings * dbentry)
424: {
425: // format drive information (with byte swapping as needed)
426: char model[40+1], serial[20+1], firmware[8+1];
427: ata_format_id_string(model, drive->model, sizeof(model)-1);
428: ata_format_id_string(serial, drive->serial_no, sizeof(serial)-1);
429: ata_format_id_string(firmware, drive->fw_rev, sizeof(firmware)-1);
430:
431: // Print model family if known
432: if (dbentry && *dbentry->modelfamily)
433: pout("Model Family: %s\n", dbentry->modelfamily);
434:
435: pout("Device Model: %s\n", infofound(model));
436: if (!dont_print_serial_number) {
437: pout("Serial Number: %s\n", infofound(serial));
438:
439: unsigned oui = 0; uint64_t unique_id = 0;
440: int naa = ata_get_wwn(drive, oui, unique_id);
441: if (naa >= 0)
442: pout("LU WWN Device Id: %x %06x %09"PRIx64"\n", naa, oui, unique_id);
443: }
444: pout("Firmware Version: %s\n", infofound(firmware));
445:
446: if (sizes.capacity) {
447: // Print capacity
448: char num[64], cap[32];
449: pout("User Capacity: %s bytes [%s]\n",
450: format_with_thousands_sep(num, sizeof(num), sizes.capacity),
451: format_capacity(cap, sizeof(cap), sizes.capacity));
452:
453: // Print sector sizes.
454: if (sizes.phy_sector_size == sizes.log_sector_size)
455: pout("Sector Size: %u bytes logical/physical\n", sizes.log_sector_size);
456: else {
457: pout("Sector Sizes: %u bytes logical, %u bytes physical",
458: sizes.log_sector_size, sizes.phy_sector_size);
459: if (sizes.log_sector_offset)
460: pout(" (offset %u bytes)", sizes.log_sector_offset);
461: pout("\n");
462: }
463: }
464:
465: // See if drive is recognized
466: pout("Device is: %s\n", !dbentry ?
467: "Not in smartctl database [for details use: -P showall]":
468: "In smartctl database [for details use: -P show]");
469:
470: // now get ATA version info
471: const char *description; unsigned short minorrev;
472: int version = ataVersionInfo(&description, drive, &minorrev);
473:
474: // SMART Support was first added into the ATA/ATAPI-3 Standard with
475: // Revision 3 of the document, July 25, 1995. Look at the "Document
476: // Status" revision commands at the beginning of
477: // http://www.t13.org/Documents/UploadedDocuments/project/d2008r7b-ATA-3.pdf
478: // to see this. So it's not enough to check if we are ATA-3.
479: // Version=-3 indicates ATA-3 BEFORE Revision 3.
480: // Version=0 indicates that no info is found. This may happen if
481: // the OS provides only part of the IDENTIFY data.
482:
483: std::string majorstr, minorstr;
484: if (version) {
485: if (version <= 8) {
486: majorstr = strprintf("%d", abs(version));
487: if (description)
488: minorstr = description;
489: else if (!minorrev)
490: minorstr = "Exact ATA specification draft version not indicated";
491: else
492: minorstr = strprintf("Not recognized. Minor revision code: 0x%04x", minorrev);
493: }
494: else {
495: // Bit 9 in word 80 of ATA IDENTIFY data does not mean "ATA-9" but "ACS-2"
496: // TODO: handle this in ataVersionInfo()
497: majorstr = "8";
498: if (description)
499: minorstr = description;
500: else if (!minorrev)
501: minorstr = strprintf("ACS-%d (revision not indicated)", version-9+2);
502: else
503: minorstr = strprintf("ACS-%d (unknown minor revision code: 0x%04x)", version-9+2, minorrev);
504: }
505: }
506:
507: pout("ATA Version is: %s\n", infofound(majorstr.c_str()));
508: pout("ATA Standard is: %s\n", infofound(minorstr.c_str()));
509:
510: // print current time and date and timezone
511: char timedatetz[DATEANDEPOCHLEN]; dateandtimezone(timedatetz);
512: pout("Local Time is: %s\n", timedatetz);
513:
514: // Print warning message, if there is one
515: if (dbentry && *dbentry->warningmsg)
516: pout("\n==> WARNING: %s\n\n", dbentry->warningmsg);
517:
518: if (!version || version >= 3)
519: return;
520:
521: pout("SMART is only available in ATA Version 3 Revision 3 or greater.\n");
522: pout("We will try to proceed in spite of this.\n");
523: }
524:
525: static const char *OfflineDataCollectionStatus(unsigned char status_byte)
526: {
527: unsigned char stat=status_byte & 0x7f;
528:
529: switch(stat){
530: case 0x00:
531: return "was never started";
532: case 0x02:
533: return "was completed without error";
534: case 0x03:
535: if (status_byte == 0x03)
536: return "is in progress";
537: else
538: return "is in a Reserved state";
539: case 0x04:
540: return "was suspended by an interrupting command from host";
541: case 0x05:
542: return "was aborted by an interrupting command from host";
543: case 0x06:
544: return "was aborted by the device with a fatal error";
545: default:
546: if (stat >= 0x40)
547: return "is in a Vendor Specific state";
548: else
549: return "is in a Reserved state";
550: }
551: }
552:
553:
554: // prints verbose value Off-line data collection status byte
555: static void PrintSmartOfflineStatus(const ata_smart_values * data)
556: {
557: pout("Offline data collection status: (0x%02x)\t",
558: (int)data->offline_data_collection_status);
559:
560: // Off-line data collection status byte is not a reserved
561: // or vendor specific value
562: pout("Offline data collection activity\n"
563: "\t\t\t\t\t%s.\n", OfflineDataCollectionStatus(data->offline_data_collection_status));
564:
565: // Report on Automatic Data Collection Status. Only IBM documents
566: // this bit. See SFF 8035i Revision 2 for details.
567: if (data->offline_data_collection_status & 0x80)
568: pout("\t\t\t\t\tAuto Offline Data Collection: Enabled.\n");
569: else
570: pout("\t\t\t\t\tAuto Offline Data Collection: Disabled.\n");
571:
572: return;
573: }
574:
575: static void PrintSmartSelfExecStatus(const ata_smart_values * data,
576: unsigned char fix_firmwarebug)
577: {
578: pout("Self-test execution status: ");
579:
580: switch (data->self_test_exec_status >> 4)
581: {
582: case 0:
583: pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
584: (int)data->self_test_exec_status);
585: pout("without error or no self-test has ever \n\t\t\t\t\tbeen run.\n");
586: break;
587: case 1:
588: pout("(%4d)\tThe self-test routine was aborted by\n\t\t\t\t\t",
589: (int)data->self_test_exec_status);
590: pout("the host.\n");
591: break;
592: case 2:
593: pout("(%4d)\tThe self-test routine was interrupted\n\t\t\t\t\t",
594: (int)data->self_test_exec_status);
595: pout("by the host with a hard or soft reset.\n");
596: break;
597: case 3:
598: pout("(%4d)\tA fatal error or unknown test error\n\t\t\t\t\t",
599: (int)data->self_test_exec_status);
600: pout("occurred while the device was executing\n\t\t\t\t\t");
601: pout("its self-test routine and the device \n\t\t\t\t\t");
602: pout("was unable to complete the self-test \n\t\t\t\t\t");
603: pout("routine.\n");
604: break;
605: case 4:
606: pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
607: (int)data->self_test_exec_status);
608: pout("a test element that failed and the test\n\t\t\t\t\t");
609: pout("element that failed is not known.\n");
610: break;
611: case 5:
612: pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
613: (int)data->self_test_exec_status);
614: pout("the electrical element of the test\n\t\t\t\t\t");
615: pout("failed.\n");
616: break;
617: case 6:
618: pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
619: (int)data->self_test_exec_status);
620: pout("the servo (and/or seek) element of the \n\t\t\t\t\t");
621: pout("test failed.\n");
622: break;
623: case 7:
624: pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
625: (int)data->self_test_exec_status);
626: pout("the read element of the test failed.\n");
627: break;
628: case 8:
629: pout("(%4d)\tThe previous self-test completed having\n\t\t\t\t\t",
630: (int)data->self_test_exec_status);
631: pout("a test element that failed and the\n\t\t\t\t\t");
632: pout("device is suspected of having handling\n\t\t\t\t\t");
633: pout("damage.\n");
634: break;
635: case 15:
636: if (fix_firmwarebug == FIX_SAMSUNG3 && data->self_test_exec_status == 0xf0) {
637: pout("(%4d)\tThe previous self-test routine completed\n\t\t\t\t\t",
638: (int)data->self_test_exec_status);
639: pout("with unknown result or self-test in\n\t\t\t\t\t");
640: pout("progress with less than 10%% remaining.\n");
641: }
642: else {
643: pout("(%4d)\tSelf-test routine in progress...\n\t\t\t\t\t",
644: (int)data->self_test_exec_status);
645: pout("%1d0%% of test remaining.\n",
646: (int)(data->self_test_exec_status & 0x0f));
647: }
648: break;
649: default:
650: pout("(%4d)\tReserved.\n",
651: (int)data->self_test_exec_status);
652: break;
653: }
654:
655: }
656:
657: static void PrintSmartTotalTimeCompleteOffline (const ata_smart_values * data)
658: {
659: pout("Total time to complete Offline \n");
660: pout("data collection: \t\t(%5d) seconds.\n",
661: (int)data->total_time_to_complete_off_line);
662: }
663:
664: static void PrintSmartOfflineCollectCap(const ata_smart_values *data)
665: {
666: pout("Offline data collection\n");
667: pout("capabilities: \t\t\t (0x%02x) ",
668: (int)data->offline_data_collection_capability);
669:
670: if (data->offline_data_collection_capability == 0x00){
671: pout("\tOffline data collection not supported.\n");
672: }
673: else {
674: pout( "%s\n", isSupportExecuteOfflineImmediate(data)?
675: "SMART execute Offline immediate." :
676: "No SMART execute Offline immediate.");
677:
678: pout( "\t\t\t\t\t%s\n", isSupportAutomaticTimer(data)?
679: "Auto Offline data collection on/off support.":
680: "No Auto Offline data collection support.");
681:
682: pout( "\t\t\t\t\t%s\n", isSupportOfflineAbort(data)?
683: "Abort Offline collection upon new\n\t\t\t\t\tcommand.":
684: "Suspend Offline collection upon new\n\t\t\t\t\tcommand.");
685:
686: pout( "\t\t\t\t\t%s\n", isSupportOfflineSurfaceScan(data)?
687: "Offline surface scan supported.":
688: "No Offline surface scan supported.");
689:
690: pout( "\t\t\t\t\t%s\n", isSupportSelfTest(data)?
691: "Self-test supported.":
692: "No Self-test supported.");
693:
694: pout( "\t\t\t\t\t%s\n", isSupportConveyanceSelfTest(data)?
695: "Conveyance Self-test supported.":
696: "No Conveyance Self-test supported.");
697:
698: pout( "\t\t\t\t\t%s\n", isSupportSelectiveSelfTest(data)?
699: "Selective Self-test supported.":
700: "No Selective Self-test supported.");
701: }
702: }
703:
704: static void PrintSmartCapability(const ata_smart_values *data)
705: {
706: pout("SMART capabilities: ");
707: pout("(0x%04x)\t", (int)data->smart_capability);
708:
709: if (data->smart_capability == 0x00)
710: {
711: pout("Automatic saving of SMART data\t\t\t\t\tis not implemented.\n");
712: }
713: else
714: {
715:
716: pout( "%s\n", (data->smart_capability & 0x01)?
717: "Saves SMART data before entering\n\t\t\t\t\tpower-saving mode.":
718: "Does not save SMART data before\n\t\t\t\t\tentering power-saving mode.");
719:
720: if ( data->smart_capability & 0x02 )
721: {
722: pout("\t\t\t\t\tSupports SMART auto save timer.\n");
723: }
724: }
725: }
726:
727: static void PrintSmartErrorLogCapability(const ata_smart_values * data, const ata_identify_device * identity)
728: {
729: pout("Error logging capability: ");
730:
731: if ( isSmartErrorLogCapable(data, identity) )
732: {
733: pout(" (0x%02x)\tError logging supported.\n",
734: (int)data->errorlog_capability);
735: }
736: else {
737: pout(" (0x%02x)\tError logging NOT supported.\n",
738: (int)data->errorlog_capability);
739: }
740: }
741:
742: static void PrintSmartShortSelfTestPollingTime(const ata_smart_values * data)
743: {
744: pout("Short self-test routine \n");
745: if (isSupportSelfTest(data))
746: pout("recommended polling time: \t (%4d) minutes.\n",
747: (int)data->short_test_completion_time);
748: else
749: pout("recommended polling time: \t Not Supported.\n");
750: }
751:
752: static void PrintSmartExtendedSelfTestPollingTime(const ata_smart_values * data)
753: {
754: pout("Extended self-test routine\n");
755: if (isSupportSelfTest(data))
756: pout("recommended polling time: \t (%4d) minutes.\n",
757: (int)data->extend_test_completion_time);
758: else
759: pout("recommended polling time: \t Not Supported.\n");
760: }
761:
762: static void PrintSmartConveyanceSelfTestPollingTime(const ata_smart_values * data)
763: {
764: pout("Conveyance self-test routine\n");
765: if (isSupportConveyanceSelfTest(data))
766: pout("recommended polling time: \t (%4d) minutes.\n",
767: (int)data->conveyance_test_completion_time);
768: else
769: pout("recommended polling time: \t Not Supported.\n");
770: }
771:
772: // Check SMART attribute table for Threshold failure
773: // onlyfailed=0: are or were any age or prefailure attributes <= threshold
774: // onlyfailed=1: are any prefailure attributes <= threshold now
775: static int find_failed_attr(const ata_smart_values * data,
776: const ata_smart_thresholds_pvt * thresholds,
777: const ata_vendor_attr_defs & defs, int onlyfailed)
778: {
779: for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
780: const ata_smart_attribute & attr = data->vendor_attributes[i];
781:
782: ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs);
783:
784: if (!onlyfailed) {
785: if (state >= ATTRSTATE_FAILED_PAST)
786: return attr.id;
787: }
788: else {
789: if (state == ATTRSTATE_FAILED_NOW && ATTRIBUTE_FLAGS_PREFAILURE(attr.flags))
790: return attr.id;
791: }
792: }
793: return 0;
794: }
795:
796: // onlyfailed=0 : print all attribute values
797: // onlyfailed=1: just ones that are currently failed and have prefailure bit set
798: // onlyfailed=2: ones that are failed, or have failed with or without prefailure bit set
799: static void PrintSmartAttribWithThres(const ata_smart_values * data,
800: const ata_smart_thresholds_pvt * thresholds,
801: const ata_vendor_attr_defs & defs,
802: int onlyfailed, unsigned char format)
803: {
804: bool needheader = true;
805:
806: // step through all vendor attributes
807: for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
808: const ata_smart_attribute & attr = data->vendor_attributes[i];
809:
810: // Check attribute and threshold
811: unsigned char threshold = 0;
812: ata_attr_state state = ata_get_attr_state(attr, i, thresholds->thres_entries, defs, &threshold);
813: if (state == ATTRSTATE_NON_EXISTING)
814: continue;
815:
816: // These break out of the loop if we are only printing certain entries...
817: if (onlyfailed == 1 && !(ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) && state == ATTRSTATE_FAILED_NOW))
818: continue;
819:
820: if (onlyfailed == 2 && state < ATTRSTATE_FAILED_PAST)
821: continue;
822:
823: // print header only if needed
824: if (needheader) {
825: if (!onlyfailed) {
826: pout("SMART Attributes Data Structure revision number: %d\n",(int)data->revnumber);
827: pout("Vendor Specific SMART Attributes with Thresholds:\n");
828: }
829: if (format == 0)
830: pout("ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE\n");
831: else
832: pout("ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE\n");
833: needheader = false;
834: }
835:
836: // Format value, worst, threshold
837: std::string valstr, worstr, threstr;
838: if (state > ATTRSTATE_NO_NORMVAL)
839: valstr = strprintf("%.3d", attr.current);
840: else
841: valstr = "---";
842: if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL))
843: worstr = strprintf("%.3d", attr.worst);
844: else
845: worstr = "---";
846: if (state > ATTRSTATE_NO_THRESHOLD)
847: threstr = strprintf("%.3d", threshold);
848: else
849: threstr = "---";
850:
851: // Print line for each valid attribute
852: std::string attrname = ata_get_smart_attr_name(attr.id, defs);
853: std::string rawstr = ata_format_attr_raw_value(attr, defs);
854:
855: if (format == 0)
856: pout("%3d %-24s0x%04x %-3s %-3s %-3s %-10s%-9s%-12s%s\n",
857: attr.id, attrname.c_str(), attr.flags,
858: valstr.c_str(), worstr.c_str(), threstr.c_str(),
859: (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? "Pre-fail" : "Old_age"),
860: (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? "Always" : "Offline"),
861: (state == ATTRSTATE_FAILED_NOW ? "FAILING_NOW" :
862: state == ATTRSTATE_FAILED_PAST ? "In_the_past"
863: : " -" ) ,
864: rawstr.c_str());
865: else
866: pout("%3d %-24s%c%c%c%c%c%c%c %-3s %-3s %-3s %-5s%s\n",
867: attr.id, attrname.c_str(),
868: (ATTRIBUTE_FLAGS_PREFAILURE(attr.flags) ? 'P' : '-'),
869: (ATTRIBUTE_FLAGS_ONLINE(attr.flags) ? 'O' : '-'),
870: (ATTRIBUTE_FLAGS_PERFORMANCE(attr.flags) ? 'S' : '-'),
871: (ATTRIBUTE_FLAGS_ERRORRATE(attr.flags) ? 'R' : '-'),
872: (ATTRIBUTE_FLAGS_EVENTCOUNT(attr.flags) ? 'C' : '-'),
873: (ATTRIBUTE_FLAGS_SELFPRESERVING(attr.flags) ? 'K' : '-'),
874: (ATTRIBUTE_FLAGS_OTHER(attr.flags) ? '+' : ' '),
875: valstr.c_str(), worstr.c_str(), threstr.c_str(),
876: (state == ATTRSTATE_FAILED_NOW ? "NOW" :
877: state == ATTRSTATE_FAILED_PAST ? "Past"
878: : "-" ),
879: rawstr.c_str());
880:
881: }
882:
883: if (!needheader) {
884: if (!onlyfailed && format == 1)
885: pout("%28s||||||_ K auto-keep\n"
886: "%28s|||||__ C event count\n"
887: "%28s||||___ R error rate\n"
888: "%28s|||____ S speed/performance\n"
889: "%28s||_____ O updated online\n"
890: "%28s|______ P prefailure warning\n",
891: "", "", "", "", "", "");
892: pout("\n");
893: }
894: }
895:
896: // Print SMART related SCT capabilities
897: static void ataPrintSCTCapability(const ata_identify_device *drive)
898: {
899: unsigned short sctcaps = drive->words088_255[206-88];
900: if (!(sctcaps & 0x01))
901: return;
902: pout("SCT capabilities: \t (0x%04x)\tSCT Status supported.\n", sctcaps);
903: if (sctcaps & 0x08)
904: pout("\t\t\t\t\tSCT Error Recovery Control supported.\n");
905: if (sctcaps & 0x10)
906: pout("\t\t\t\t\tSCT Feature Control supported.\n");
907: if (sctcaps & 0x20)
908: pout("\t\t\t\t\tSCT Data Table supported.\n");
909: }
910:
911:
912: static void PrintGeneralSmartValues(const ata_smart_values *data, const ata_identify_device *drive,
913: unsigned char fix_firmwarebug)
914: {
915: pout("General SMART Values:\n");
916:
917: PrintSmartOfflineStatus(data);
918:
919: if (isSupportSelfTest(data)){
920: PrintSmartSelfExecStatus(data, fix_firmwarebug);
921: }
922:
923: PrintSmartTotalTimeCompleteOffline(data);
924: PrintSmartOfflineCollectCap(data);
925: PrintSmartCapability(data);
926:
927: PrintSmartErrorLogCapability(data, drive);
928:
929: pout( "\t\t\t\t\t%s\n", isGeneralPurposeLoggingCapable(drive)?
930: "General Purpose Logging supported.":
931: "No General Purpose Logging support.");
932:
933: if (isSupportSelfTest(data)){
934: PrintSmartShortSelfTestPollingTime (data);
935: PrintSmartExtendedSelfTestPollingTime (data);
936: }
937: if (isSupportConveyanceSelfTest(data))
938: PrintSmartConveyanceSelfTestPollingTime (data);
939:
940: ataPrintSCTCapability(drive);
941:
942: pout("\n");
943: }
944:
945: // Get # sectors of a log addr, 0 if log does not exist.
946: static unsigned GetNumLogSectors(const ata_smart_log_directory * logdir, unsigned logaddr, bool gpl)
947: {
948: if (!logdir)
949: return 0;
950: if (logaddr > 0xff)
951: return 0;
952: if (logaddr == 0)
953: return 1;
954: unsigned n = logdir->entry[logaddr-1].numsectors;
955: if (gpl)
956: // GP logs may have >255 sectors
957: n |= logdir->entry[logaddr-1].reserved << 8;
958: return n;
959: }
960:
961: // Get name of log.
962: // Table A.2 of T13/2161-D Revision 1 (ACS-3), August 13, 2011.
963: static const char * GetLogName(unsigned logaddr)
964: {
965: switch (logaddr) {
966: case 0x00: return "Log Directory";
967: case 0x01: return "Summary SMART error log";
968: case 0x02: return "Comprehensive SMART error log";
969: case 0x03: return "Ext. Comprehensive SMART error log";
970: case 0x04: return "Device Statistics log";
971: case 0x05: return "Reserved for the CFA"; // ACS-2
972: case 0x06: return "SMART self-test log";
973: case 0x07: return "Extended self-test log";
974: case 0x08: return "Power Conditions log"; // ACS-2
975: case 0x09: return "Selective self-test log";
976: case 0x0d: return "LPS Mis-alignment log"; // ACS-2
977: case 0x10: return "NCQ Command Error log";
978: case 0x11: return "SATA Phy Event Counters";
979: case 0x19: return "LBA Status log"; // ACS-3
980: case 0x20: return "Streaming performance log"; // Obsolete
981: case 0x21: return "Write stream error log";
982: case 0x22: return "Read stream error log";
983: case 0x23: return "Delayed sector log"; // Obsolete
984: case 0x30: return "IDENTIFY DEVICE data log"; // ACS-3
985: case 0xe0: return "SCT Command/Status";
986: case 0xe1: return "SCT Data Transfer";
987: default:
988: if (0xa0 <= logaddr && logaddr <= 0xdf)
989: return "Device vendor specific log";
990: if (0x80 <= logaddr && logaddr <= 0x9f)
991: return "Host vendor specific log";
992: if (0x12 <= logaddr && logaddr <= 0x17)
993: return "Reserved for Serial ATA";
994: return "Reserved";
995: }
996: /*NOTREACHED*/
997: }
998:
999: // Print SMART and/or GP Log Directory
1000: static void PrintLogDirectories(const ata_smart_log_directory * gplogdir,
1001: const ata_smart_log_directory * smartlogdir)
1002: {
1003: if (gplogdir)
1004: pout("General Purpose Log Directory Version %u\n", gplogdir->logversion);
1005: if (smartlogdir)
1006: pout("SMART %sLog Directory Version %u%s\n",
1007: (gplogdir ? " " : ""), smartlogdir->logversion,
1008: (smartlogdir->logversion==1 ? " [multi-sector log support]" : ""));
1009:
1010: for (unsigned i = 0; i <= 0xff; i++) {
1011: // Get number of sectors
1012: unsigned smart_numsect = GetNumLogSectors(smartlogdir, i, false);
1013: unsigned gp_numsect = GetNumLogSectors(gplogdir , i, true );
1014:
1015: if (!(smart_numsect || gp_numsect))
1016: continue; // Log does not exist
1017:
1018: const char * name = GetLogName(i);
1019:
1020: // Print name and length of log.
1021: // If both SMART and GP exist, print separate entries if length differ.
1022: if (smart_numsect == gp_numsect)
1023: pout( "GP/S Log at address 0x%02x has %4d sectors [%s]\n", i, smart_numsect, name);
1024: else {
1025: if (gp_numsect)
1026: pout("GP %sLog at address 0x%02x has %4d sectors [%s]\n", (smartlogdir?" ":""),
1027: i, gp_numsect, name);
1028: if (smart_numsect)
1029: pout("SMART Log at address 0x%02x has %4d sectors [%s]\n", i, smart_numsect, name);
1030: }
1031: }
1032: pout("\n");
1033: }
1034:
1035: // Print hexdump of log pages.
1036: // Format is compatible with 'xxd -r'.
1037: static void PrintLogPages(const char * type, const unsigned char * data,
1038: unsigned char logaddr, unsigned page,
1039: unsigned num_pages, unsigned max_pages)
1040: {
1041: pout("%s Log 0x%02x [%s], Page %u-%u (of %u)\n",
1042: type, logaddr, GetLogName(logaddr), page, page+num_pages-1, max_pages);
1043: for (unsigned i = 0; i < num_pages * 512; i += 16) {
1044: const unsigned char * p = data+i;
1045: pout("%07x: %02x %02x %02x %02x %02x %02x %02x %02x "
1046: "%02x %02x %02x %02x %02x %02x %02x %02x ",
1047: (page * 512) + i,
1048: p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
1049: p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15]);
1050: #define P(n) (' ' <= p[n] && p[n] <= '~' ? (int)p[n] : '.')
1051: pout("|%c%c%c%c%c%c%c%c"
1052: "%c%c%c%c%c%c%c%c|\n",
1053: P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
1054: P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15));
1055: #undef P
1056: if ((i & 0x1ff) == 0x1f0)
1057: pout("\n");
1058: }
1059: }
1060:
1061: ///////////////////////////////////////////////////////////////////////
1062: // Device statistics (Log 0x04)
1063:
1064: // See Section A.5 of
1065: // ATA/ATAPI Command Set - 3 (ACS-3)
1066: // T13/2161-D Revision 1, August 13, 2011
1067:
1068: struct devstat_entry_info
1069: {
1070: short size; // #bytes of value, -1 for signed char
1071: const char * name;
1072: };
1073:
1074: const devstat_entry_info devstat_info_0x00[] = {
1075: { 2, "List of supported log pages" },
1076: { 0, 0 }
1077: };
1078:
1079: const devstat_entry_info devstat_info_0x01[] = {
1080: { 2, "General Statistics" },
1081: { 4, "Lifetime Power-On Resets" },
1082: { 4, "Power-on Hours" }, // spec says no flags(?)
1083: { 6, "Logical Sectors Written" },
1084: { 6, "Number of Write Commands" },
1085: { 6, "Logical Sectors Read" },
1086: { 6, "Number of Read Commands" },
1087: { 0, 0 }
1088: };
1089:
1090: const devstat_entry_info devstat_info_0x02[] = {
1091: { 2, "Freefall Statistics" },
1092: { 4, "Number of Free-Fall Events Detected" },
1093: { 4, "Overlimit Shock Events" },
1094: { 0, 0 }
1095: };
1096:
1097: const devstat_entry_info devstat_info_0x03[] = {
1098: { 2, "Rotating Media Statistics" },
1099: { 4, "Spindle Motor Power-on Hours" },
1100: { 4, "Head Flying Hours" },
1101: { 4, "Head Load Events" },
1102: { 4, "Number of Reallocated Logical Sectors" },
1103: { 4, "Read Recovery Attempts" },
1104: { 4, "Number of Mechanical Start Failures" },
1105: { 4, "Number of Realloc. Candidate Logical Sectors" }, // ACS-3
1106: { 0, 0 }
1107: };
1108:
1109: const devstat_entry_info devstat_info_0x04[] = {
1110: { 2, "General Errors Statistics" },
1111: { 4, "Number of Reported Uncorrectable Errors" },
1112: //{ 4, "Number of Resets Between Command Acceptance and Command Completion" },
1113: { 4, "Resets Between Cmd Acceptance and Completion" },
1114: { 0, 0 }
1115: };
1116:
1117: const devstat_entry_info devstat_info_0x05[] = {
1118: { 2, "Temperature Statistics" },
1119: { -1, "Current Temperature" },
1120: { -1, "Average Short Term Temperature" },
1121: { -1, "Average Long Term Temperature" },
1122: { -1, "Highest Temperature" },
1123: { -1, "Lowest Temperature" },
1124: { -1, "Highest Average Short Term Temperature" },
1125: { -1, "Lowest Average Short Term Temperature" },
1126: { -1, "Highest Average Long Term Temperature" },
1127: { -1, "Lowest Average Long Term Temperature" },
1128: { 4, "Time in Over-Temperature" },
1129: { -1, "Specified Maximum Operating Temperature" },
1130: { 4, "Time in Under-Temperature" },
1131: { -1, "Specified Minimum Operating Temperature" },
1132: { 0, 0 }
1133: };
1134:
1135: const devstat_entry_info devstat_info_0x06[] = {
1136: { 2, "Transport Statistics" },
1137: { 4, "Number of Hardware Resets" },
1138: { 4, "Number of ASR Events" },
1139: { 4, "Number of Interface CRC Errors" },
1140: { 0, 0 }
1141: };
1142:
1143: const devstat_entry_info devstat_info_0x07[] = {
1144: { 2, "Solid State Device Statistics" },
1145: { 1, "Percentage Used Endurance Indicator" },
1146: { 0, 0 }
1147: };
1148:
1149: const devstat_entry_info * devstat_infos[] = {
1150: devstat_info_0x00,
1151: devstat_info_0x01,
1152: devstat_info_0x02,
1153: devstat_info_0x03,
1154: devstat_info_0x04,
1155: devstat_info_0x05,
1156: devstat_info_0x06,
1157: devstat_info_0x07
1158: };
1159:
1160: const int num_devstat_infos = sizeof(devstat_infos)/sizeof(devstat_infos[0]);
1161:
1162: static void print_device_statistics_page(const unsigned char * data, int page,
1163: bool & need_trailer)
1164: {
1165: const devstat_entry_info * info = (page < num_devstat_infos ? devstat_infos[page] : 0);
1166: const char * name = (info ? info[0].name : "Unknown Statistics");
1167:
1168: // Check page number in header
1169: static const char line[] = " ===== = = == ";
1170: if (!data[2]) {
1171: pout("%3d%s%s (empty) ==\n", page, line, name);
1172: return;
1173: }
1174: if (data[2] != page) {
1175: pout("%3d%s%s (invalid page %d in header) ==\n", page, line, name, data[2]);
1176: return;
1177: }
1178:
1179: pout("%3d%s%s (rev %d) ==\n", page, line, name, data[0]);
1180:
1181: // Print entries
1182: for (int i = 1, offset = 8; offset < 512-7; i++, offset+=8) {
1183: // Check for last known entry
1184: if (info && !info[i].size)
1185: info = 0;
1186:
1187: // Skip unsupported entries
1188: unsigned char flags = data[offset+7];
1189: if (!(flags & 0x80))
1190: continue;
1191:
1192: // Get value size, default to max if unknown
1193: int size = (info ? info[i].size : 7);
1194:
1195: // Format value
1196: char valstr[32];
1197: if (flags & 0x40) { // valid flag
1198: // Get value
1199: int64_t val;
1200: if (size < 0) {
1201: val = (signed char)data[offset];
1202: }
1203: else {
1204: val = 0;
1205: for (int j = 0; j < size; j++)
1206: val |= (int64_t)data[offset+j] << (j*8);
1207: }
1208: snprintf(valstr, sizeof(valstr), "%"PRId64, val);
1209: }
1210: else {
1211: // Value not known (yet)
1212: strcpy(valstr, "-");
1213: }
1214:
1215: pout("%3d 0x%03x %d%c %15s%c %s\n",
1216: page, offset,
1217: abs(size),
1218: (flags & 0x1f ? '+' : ' '), // unknown flags
1219: valstr,
1220: (flags & 0x20 ? '~' : ' '), // normalized flag
1221: (info ? info[i].name : "Unknown"));
1222: if (flags & 0x20)
1223: need_trailer = true;
1224: }
1225: }
1226:
1227: static bool print_device_statistics(ata_device * device, unsigned nsectors,
1228: const std::vector<int> & single_pages, bool all_pages, bool ssd_page)
1229: {
1230: // Read list of supported pages from page 0
1231: unsigned char page_0[512] = {0, };
1232: if (!ataReadLogExt(device, 0x04, 0, 0, page_0, 1))
1233: return false;
1234:
1235: unsigned char nentries = page_0[8];
1236: if (!(page_0[2] == 0 && nentries > 0)) {
1237: pout("Device Statistics page 0 is invalid (page=%d, nentries=%d)\n", page_0[2], nentries);
1238: return false;
1239: }
1240:
1241: // Prepare list of pages to print
1242: std::vector<int> pages;
1243: unsigned i;
1244: if (all_pages) {
1245: // Add all supported pages
1246: for (i = 0; i < nentries; i++) {
1247: int page = page_0[8+1+i];
1248: if (page)
1249: pages.push_back(page);
1250: }
1251: ssd_page = false;
1252: }
1253: // Add manually specified pages
1254: bool print_page_0 = false;
1255: for (i = 0; i < single_pages.size() || ssd_page; i++) {
1256: int page = (i < single_pages.size() ? single_pages[i] : 7);
1257: if (!page)
1258: print_page_0 = true;
1259: else if (page >= (int)nsectors)
1260: pout("Device Statistics Log has only %u pages\n", nsectors);
1261: else
1262: pages.push_back(page);
1263: if (page == 7)
1264: ssd_page = false;
1265: }
1266:
1267: // Print list of supported pages if requested
1268: if (print_page_0) {
1269: pout("Device Statistics (GP Log 0x04) supported pages\n");
1270: pout("Page Description\n");
1271: for (i = 0; i < nentries; i++) {
1272: int page = page_0[8+1+i];
1273: pout("%3d %s\n", page,
1274: (page < num_devstat_infos ? devstat_infos[page][0].name : "Unknown Statistics"));
1275: }
1276: pout("\n");
1277: }
1278:
1279: // Read & print pages
1280: if (!pages.empty()) {
1281: pout("Device Statistics (GP Log 0x04)\n");
1282: pout("Page Offset Size Value Description\n");
1283: bool need_trailer = false;
1284:
1285: for (i = 0; i < pages.size(); i++) {
1286: int page = pages[i];
1287: unsigned char page_n[512] = {0, };
1288: if (!ataReadLogExt(device, 0x04, 0, page, page_n, 1))
1289: return false;
1290: print_device_statistics_page(page_n, page, need_trailer);
1291: }
1292:
1293: if (need_trailer)
1294: pout("%30s|_ ~ normalized value\n", "");
1295: pout("\n");
1296: }
1297:
1298: return true;
1299: }
1300:
1301:
1302: ///////////////////////////////////////////////////////////////////////
1303:
1304: // Print log 0x11
1305: static void PrintSataPhyEventCounters(const unsigned char * data, bool reset)
1306: {
1307: if (checksum(data))
1308: checksumwarning("SATA Phy Event Counters");
1309: pout("SATA Phy Event Counters (GP Log 0x11)\n");
1310: if (data[0] || data[1] || data[2] || data[3])
1311: pout("[Reserved: 0x%02x 0x%02x 0x%02x 0x%02x]\n",
1312: data[0], data[1], data[2], data[3]);
1313: pout("ID Size Value Description\n");
1314:
1315: for (unsigned i = 4; ; ) {
1316: // Get counter id and size (bits 14:12)
1317: unsigned id = data[i] | (data[i+1] << 8);
1318: unsigned size = ((id >> 12) & 0x7) << 1;
1319: id &= 0x8fff;
1320:
1321: // End of counter table ?
1322: if (!id)
1323: break;
1324: i += 2;
1325:
1326: if (!(2 <= size && size <= 8 && i + size < 512)) {
1327: pout("0x%04x %u: Invalid entry\n", id, size);
1328: break;
1329: }
1330:
1331: // Get value
1332: uint64_t val = 0, max_val = 0;
1333: for (unsigned j = 0; j < size; j+=2) {
1334: val |= (uint64_t)(data[i+j] | (data[i+j+1] << 8)) << (j*8);
1335: max_val |= (uint64_t)0xffffU << (j*8);
1336: }
1337: i += size;
1338:
1339: // Get name
1340: const char * name;
1341: switch (id) {
1342: case 0x001: name = "Command failed due to ICRC error"; break; // Mandatory
1343: case 0x002: name = "R_ERR response for data FIS"; break;
1344: case 0x003: name = "R_ERR response for device-to-host data FIS"; break;
1345: case 0x004: name = "R_ERR response for host-to-device data FIS"; break;
1346: case 0x005: name = "R_ERR response for non-data FIS"; break;
1347: case 0x006: name = "R_ERR response for device-to-host non-data FIS"; break;
1348: case 0x007: name = "R_ERR response for host-to-device non-data FIS"; break;
1349: case 0x008: name = "Device-to-host non-data FIS retries"; break;
1350: case 0x009: name = "Transition from drive PhyRdy to drive PhyNRdy"; break;
1351: case 0x00A: name = "Device-to-host register FISes sent due to a COMRESET"; break; // Mandatory
1352: case 0x00B: name = "CRC errors within host-to-device FIS"; break;
1353: case 0x00D: name = "Non-CRC errors within host-to-device FIS"; break;
1354: case 0x00F: name = "R_ERR response for host-to-device data FIS, CRC"; break;
1355: case 0x010: name = "R_ERR response for host-to-device data FIS, non-CRC"; break;
1356: case 0x012: name = "R_ERR response for host-to-device non-data FIS, CRC"; break;
1357: case 0x013: name = "R_ERR response for host-to-device non-data FIS, non-CRC"; break;
1358: default: name = (id & 0x8000 ? "Vendor specific" : "Unknown"); break;
1359: }
1360:
1361: // Counters stop at max value, add '+' in this case
1362: pout("0x%04x %u %12"PRIu64"%c %s\n", id, size, val,
1363: (val == max_val ? '+' : ' '), name);
1364: }
1365: if (reset)
1366: pout("All counters reset\n");
1367: pout("\n");
1368: }
1369:
1370: // Get description for 'state' value from SMART Error Logs
1371: static const char * get_error_log_state_desc(unsigned state)
1372: {
1373: state &= 0x0f;
1374: switch (state){
1375: case 0x0: return "in an unknown state";
1376: case 0x1: return "sleeping";
1377: case 0x2: return "in standby mode";
1378: case 0x3: return "active or idle";
1379: case 0x4: return "doing SMART Offline or Self-test";
1380: default:
1381: return (state < 0xb ? "in a reserved state"
1382: : "in a vendor specific state");
1383: }
1384: }
1385:
1386: // returns number of errors
1387: static int PrintSmartErrorlog(const ata_smart_errorlog *data,
1388: unsigned char fix_firmwarebug)
1389: {
1390: pout("SMART Error Log Version: %d\n", (int)data->revnumber);
1391:
1392: // if no errors logged, return
1393: if (!data->error_log_pointer){
1394: pout("No Errors Logged\n\n");
1395: return 0;
1396: }
1397: print_on();
1398: // If log pointer out of range, return
1399: if (data->error_log_pointer>5){
1400: pout("Invalid Error Log index = 0x%02x (T13/1321D rev 1c "
1401: "Section 8.41.6.8.2.2 gives valid range from 1 to 5)\n\n",
1402: (int)data->error_log_pointer);
1403: return 0;
1404: }
1405:
1406: // Some internal consistency checking of the data structures
1407: if ((data->ata_error_count-data->error_log_pointer)%5 && fix_firmwarebug != FIX_SAMSUNG2) {
1408: pout("Warning: ATA error count %d inconsistent with error log pointer %d\n\n",
1409: data->ata_error_count,data->error_log_pointer);
1410: }
1411:
1412: // starting printing error log info
1413: if (data->ata_error_count<=5)
1414: pout( "ATA Error Count: %d\n", (int)data->ata_error_count);
1415: else
1416: pout( "ATA Error Count: %d (device log contains only the most recent five errors)\n",
1417: (int)data->ata_error_count);
1418: print_off();
1419: pout("\tCR = Command Register [HEX]\n"
1420: "\tFR = Features Register [HEX]\n"
1421: "\tSC = Sector Count Register [HEX]\n"
1422: "\tSN = Sector Number Register [HEX]\n"
1423: "\tCL = Cylinder Low Register [HEX]\n"
1424: "\tCH = Cylinder High Register [HEX]\n"
1425: "\tDH = Device/Head Register [HEX]\n"
1426: "\tDC = Device Command Register [HEX]\n"
1427: "\tER = Error register [HEX]\n"
1428: "\tST = Status register [HEX]\n"
1429: "Powered_Up_Time is measured from power on, and printed as\n"
1430: "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
1431: "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
1432:
1433: // now step through the five error log data structures (table 39 of spec)
1434: for (int k = 4; k >= 0; k-- ) {
1435:
1436: // The error log data structure entries are a circular buffer
1437: int j, i=(data->error_log_pointer+k)%5;
1438: const ata_smart_errorlog_struct * elog = data->errorlog_struct+i;
1439: const ata_smart_errorlog_error_struct * summary = &(elog->error_struct);
1440:
1441: // Spec says: unused error log structures shall be zero filled
1442: if (nonempty(elog, sizeof(*elog))){
1443: // Table 57 of T13/1532D Volume 1 Revision 3
1444: const char *msgstate = get_error_log_state_desc(summary->state);
1445: int days = (int)summary->timestamp/24;
1446:
1447: // See table 42 of ATA5 spec
1448: print_on();
1449: pout("Error %d occurred at disk power-on lifetime: %d hours (%d days + %d hours)\n",
1450: (int)(data->ata_error_count+k-4), (int)summary->timestamp, days, (int)(summary->timestamp-24*days));
1451: print_off();
1452: pout(" When the command that caused the error occurred, the device was %s.\n\n",msgstate);
1453: pout(" After command completion occurred, registers were:\n"
1454: " ER ST SC SN CL CH DH\n"
1455: " -- -- -- -- -- -- --\n"
1456: " %02x %02x %02x %02x %02x %02x %02x",
1457: (int)summary->error_register,
1458: (int)summary->status,
1459: (int)summary->sector_count,
1460: (int)summary->sector_number,
1461: (int)summary->cylinder_low,
1462: (int)summary->cylinder_high,
1463: (int)summary->drive_head);
1464: // Add a description of the contents of the status and error registers
1465: // if possible
1466: char descbuf[256];
1467: const char * st_er_desc = construct_st_er_desc(descbuf, elog);
1468: if (st_er_desc)
1469: pout(" %s", st_er_desc);
1470: pout("\n\n");
1471: pout(" Commands leading to the command that caused the error were:\n"
1472: " CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name\n"
1473: " -- -- -- -- -- -- -- -- ---------------- --------------------\n");
1474: for ( j = 4; j >= 0; j--){
1475: const ata_smart_errorlog_command_struct * thiscommand = elog->commands+j;
1476:
1477: // Spec says: unused data command structures shall be zero filled
1478: if (nonempty(thiscommand, sizeof(*thiscommand))) {
1479: char timestring[32];
1480:
1481: // Convert integer milliseconds to a text-format string
1482: MsecToText(thiscommand->timestamp, timestring);
1483:
1484: pout(" %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
1485: (int)thiscommand->commandreg,
1486: (int)thiscommand->featuresreg,
1487: (int)thiscommand->sector_count,
1488: (int)thiscommand->sector_number,
1489: (int)thiscommand->cylinder_low,
1490: (int)thiscommand->cylinder_high,
1491: (int)thiscommand->drive_head,
1492: (int)thiscommand->devicecontrolreg,
1493: timestring,
1494: look_up_ata_command(thiscommand->commandreg, thiscommand->featuresreg));
1495: }
1496: }
1497: pout("\n");
1498: }
1499: }
1500: print_on();
1501: if (printing_is_switchable)
1502: pout("\n");
1503: print_off();
1504: return data->ata_error_count;
1505: }
1506:
1507: // Print SMART Extended Comprehensive Error Log (GP Log 0x03)
1508: static int PrintSmartExtErrorLog(const ata_smart_exterrlog * log,
1509: unsigned nsectors, unsigned max_errors)
1510: {
1511: pout("SMART Extended Comprehensive Error Log Version: %u (%u sectors)\n",
1512: log->version, nsectors);
1513:
1514: if (!log->device_error_count) {
1515: pout("No Errors Logged\n\n");
1516: return 0;
1517: }
1518: print_on();
1519:
1520: // Check index
1521: unsigned nentries = nsectors * 4;
1522: unsigned erridx = log->error_log_index;
1523: if (!(1 <= erridx && erridx <= nentries)){
1524: // Some Samsung disks (at least SP1614C/SW100-25, HD300LJ/ZT100-12) use the
1525: // former index from Summary Error Log (byte 1, now reserved) and set byte 2-3
1526: // to 0.
1527: if (!(erridx == 0 && 1 <= log->reserved1 && log->reserved1 <= nentries)) {
1528: pout("Invalid Error Log index = 0x%04x (reserved = 0x%02x)\n", erridx, log->reserved1);
1529: return 0;
1530: }
1531: pout("Invalid Error Log index = 0x%04x, trying reserved byte (0x%02x) instead\n", erridx, log->reserved1);
1532: erridx = log->reserved1;
1533: }
1534:
1535: // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
1536: // it is 1-based in practice.
1537: erridx--;
1538:
1539: // Calculate #errors to print
1540: unsigned errcnt = log->device_error_count;
1541:
1542: if (errcnt <= nentries)
1543: pout("Device Error Count: %u\n", log->device_error_count);
1544: else {
1545: errcnt = nentries;
1546: pout("Device Error Count: %u (device log contains only the most recent %u errors)\n",
1547: log->device_error_count, errcnt);
1548: }
1549:
1550: if (max_errors < errcnt)
1551: errcnt = max_errors;
1552:
1553: print_off();
1554: pout("\tCR = Command Register\n"
1555: "\tFEATR = Features Register\n"
1556: "\tCOUNT = Count (was: Sector Count) Register\n"
1557: "\tLBA_48 = Upper bytes of LBA High/Mid/Low Registers ] ATA-8\n"
1558: "\tLH = LBA High (was: Cylinder High) Register ] LBA\n"
1559: "\tLM = LBA Mid (was: Cylinder Low) Register ] Register\n"
1560: "\tLL = LBA Low (was: Sector Number) Register ]\n"
1561: "\tDV = Device (was: Device/Head) Register\n"
1562: "\tDC = Device Control Register\n"
1563: "\tER = Error register\n"
1564: "\tST = Status register\n"
1565: "Powered_Up_Time is measured from power on, and printed as\n"
1566: "DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,\n"
1567: "SS=sec, and sss=millisec. It \"wraps\" after 49.710 days.\n\n");
1568:
1569: // Iterate through circular buffer in reverse direction
1570: for (unsigned i = 0, errnum = log->device_error_count;
1571: i < errcnt; i++, errnum--, erridx = (erridx > 0 ? erridx - 1 : nentries - 1)) {
1572:
1573: const ata_smart_exterrlog_error_log & entry = log[erridx / 4].error_logs[erridx % 4];
1574:
1575: // Skip unused entries
1576: if (!nonempty(&entry, sizeof(entry))) {
1577: pout("Error %u [%u] log entry is empty\n", errnum, erridx);
1578: continue;
1579: }
1580:
1581: // Print error information
1582: print_on();
1583: const ata_smart_exterrlog_error & err = entry.error;
1584: pout("Error %u [%u] occurred at disk power-on lifetime: %u hours (%u days + %u hours)\n",
1585: errnum, erridx, err.timestamp, err.timestamp / 24, err.timestamp % 24);
1586: print_off();
1587:
1588: pout(" When the command that caused the error occurred, the device was %s.\n\n",
1589: get_error_log_state_desc(err.state));
1590:
1591: // Print registers
1592: pout(" After command completion occurred, registers were:\n"
1593: " ER -- ST COUNT LBA_48 LH LM LL DV DC\n"
1594: " -- -- -- == -- == == == -- -- -- -- --\n"
1595: " %02x -- %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
1596: err.error_register,
1597: err.status_register,
1598: err.count_register_hi,
1599: err.count_register,
1600: err.lba_high_register_hi,
1601: err.lba_mid_register_hi,
1602: err.lba_low_register_hi,
1603: err.lba_high_register,
1604: err.lba_mid_register,
1605: err.lba_low_register,
1606: err.device_register,
1607: err.device_control_register);
1608:
1609: // Add a description of the contents of the status and error registers
1610: // if possible
1611: char descbuf[256];
1612: const char * st_er_desc = construct_st_er_desc(descbuf, &entry);
1613: if (st_er_desc)
1614: pout(" %s", st_er_desc);
1615: pout("\n\n");
1616:
1617: // Print command history
1618: pout(" Commands leading to the command that caused the error were:\n"
1619: " CR FEATR COUNT LBA_48 LH LM LL DV DC Powered_Up_Time Command/Feature_Name\n"
1620: " -- == -- == -- == == == -- -- -- -- -- --------------- --------------------\n");
1621: for (int ci = 4; ci >= 0; ci--) {
1622: const ata_smart_exterrlog_command & cmd = entry.commands[ci];
1623:
1624: // Skip unused entries
1625: if (!nonempty(&cmd, sizeof(cmd)))
1626: continue;
1627:
1628: // Print registers, timestamp and ATA command name
1629: char timestring[32];
1630: MsecToText(cmd.timestamp, timestring);
1631:
1632: pout(" %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %16s %s\n",
1633: cmd.command_register,
1634: cmd.features_register_hi,
1635: cmd.features_register,
1636: cmd.count_register_hi,
1637: cmd.count_register,
1638: cmd.lba_high_register_hi,
1639: cmd.lba_mid_register_hi,
1640: cmd.lba_low_register_hi,
1641: cmd.lba_high_register,
1642: cmd.lba_mid_register,
1643: cmd.lba_low_register,
1644: cmd.device_register,
1645: cmd.device_control_register,
1646: timestring,
1647: look_up_ata_command(cmd.command_register, cmd.features_register));
1648: }
1649: pout("\n");
1650: }
1651:
1652: print_on();
1653: if (printing_is_switchable)
1654: pout("\n");
1655: print_off();
1656: return log->device_error_count;
1657: }
1658:
1659: // Print SMART Extended Self-test Log (GP Log 0x07)
1660: static int PrintSmartExtSelfTestLog(const ata_smart_extselftestlog * log,
1661: unsigned nsectors, unsigned max_entries)
1662: {
1663: pout("SMART Extended Self-test Log Version: %u (%u sectors)\n",
1664: log->version, nsectors);
1665:
1666: if (!log->log_desc_index){
1667: pout("No self-tests have been logged. [To run self-tests, use: smartctl -t]\n\n");
1668: return 0;
1669: }
1670:
1671: // Check index
1672: unsigned nentries = nsectors * 19;
1673: unsigned logidx = log->log_desc_index;
1674: if (logidx > nentries) {
1675: pout("Invalid Self-test Log index = 0x%04x (reserved = 0x%02x)\n", logidx, log->reserved1);
1676: return 0;
1677: }
1678:
1679: // Index base is not clearly specified by ATA8-ACS (T13/1699-D Revision 6a),
1680: // it is 1-based in practice.
1681: logidx--;
1682:
1683: bool print_header = true;
1684: int errcnt = 0, igncnt = 0;
1685: int ext_ok_testnum = -1;
1686:
1687: // Iterate through circular buffer in reverse direction
1688: for (unsigned i = 0, testnum = 1;
1689: i < nentries && testnum <= max_entries;
1690: i++, logidx = (logidx > 0 ? logidx - 1 : nentries - 1)) {
1691:
1692: const ata_smart_extselftestlog_desc & entry = log[logidx / 19].log_descs[logidx % 19];
1693:
1694: // Skip unused entries
1695: if (!nonempty(&entry, sizeof(entry)))
1696: continue;
1697:
1698: // Get LBA
1699: const unsigned char * b = entry.failing_lba;
1700: uint64_t lba48 = b[0]
1701: | ( b[1] << 8)
1702: | ( b[2] << 16)
1703: | ((uint64_t)b[3] << 24)
1704: | ((uint64_t)b[4] << 32)
1705: | ((uint64_t)b[5] << 40);
1706:
1707: // Print entry
1708: int state = ataPrintSmartSelfTestEntry(testnum, entry.self_test_type,
1709: entry.self_test_status, entry.timestamp, lba48,
1710: false /*!print_error_only*/, print_header);
1711:
1712: if (state < 0) {
1713: // Self-test showed an error
1714: if (ext_ok_testnum < 0)
1715: errcnt++;
1716: else
1717: // Newer successful extended self-test exits
1718: igncnt++;
1719: }
1720: else if (state > 0 && ext_ok_testnum < 0) {
1721: // Latest successful extended self-test
1722: ext_ok_testnum = testnum;
1723: }
1724: testnum++;
1725: }
1726:
1727: if (igncnt)
1728: pout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
1729: igncnt, igncnt+errcnt, ext_ok_testnum);
1730:
1731: pout("\n");
1732: return errcnt;
1733: }
1734:
1735: static void ataPrintSelectiveSelfTestLog(const ata_selective_self_test_log * log, const ata_smart_values * sv)
1736: {
1737: int i,field1,field2;
1738: const char *msg;
1739: char tmp[64];
1740: uint64_t maxl=0,maxr=0;
1741: uint64_t current=log->currentlba;
1742: uint64_t currentend=current+65535;
1743:
1744: // print data structure revision number
1745: pout("SMART Selective self-test log data structure revision number %d\n",(int)log->logversion);
1746: if (1 != log->logversion)
1747: pout("Note: revision number not 1 implies that no selective self-test has ever been run\n");
1748:
1749: switch((sv->self_test_exec_status)>>4){
1750: case 0:msg="Completed";
1751: break;
1752: case 1:msg="Aborted_by_host";
1753: break;
1754: case 2:msg="Interrupted";
1755: break;
1756: case 3:msg="Fatal_error";
1757: break;
1758: case 4:msg="Completed_unknown_failure";
1759: break;
1760: case 5:msg="Completed_electrical_failure";
1761: break;
1762: case 6:msg="Completed_servo/seek_failure";
1763: break;
1764: case 7:msg="Completed_read_failure";
1765: break;
1766: case 8:msg="Completed_handling_damage??";
1767: break;
1768: case 15:msg="Self_test_in_progress";
1769: break;
1770: default:msg="Unknown_status ";
1771: break;
1772: }
1773:
1774: // find the number of columns needed for printing. If in use, the
1775: // start/end of span being read-scanned...
1776: if (log->currentspan>5) {
1777: maxl=current;
1778: maxr=currentend;
1779: }
1780: for (i=0; i<5; i++) {
1781: uint64_t start=log->span[i].start;
1782: uint64_t end =log->span[i].end;
1783: // ... plus max start/end of each of the five test spans.
1784: if (start>maxl)
1785: maxl=start;
1786: if (end > maxr)
1787: maxr=end;
1788: }
1789:
1790: // we need at least 7 characters wide fields to accomodate the
1791: // labels
1792: if ((field1=snprintf(tmp,64, "%"PRIu64, maxl))<7)
1793: field1=7;
1794: if ((field2=snprintf(tmp,64, "%"PRIu64, maxr))<7)
1795: field2=7;
1796:
1797: // now print the five test spans
1798: pout(" SPAN %*s %*s CURRENT_TEST_STATUS\n", field1, "MIN_LBA", field2, "MAX_LBA");
1799:
1800: for (i=0; i<5; i++) {
1801: uint64_t start=log->span[i].start;
1802: uint64_t end=log->span[i].end;
1803:
1804: if ((i+1)==(int)log->currentspan)
1805: // this span is currently under test
1806: pout(" %d %*"PRIu64" %*"PRIu64" %s [%01d0%% left] (%"PRIu64"-%"PRIu64")\n",
1807: i+1, field1, start, field2, end, msg,
1808: (int)(sv->self_test_exec_status & 0xf), current, currentend);
1809: else
1810: // this span is not currently under test
1811: pout(" %d %*"PRIu64" %*"PRIu64" Not_testing\n",
1812: i+1, field1, start, field2, end);
1813: }
1814:
1815: // if we are currently read-scanning, print LBAs and the status of
1816: // the read scan
1817: if (log->currentspan>5)
1818: pout("%5d %*"PRIu64" %*"PRIu64" Read_scanning %s\n",
1819: (int)log->currentspan, field1, current, field2, currentend,
1820: OfflineDataCollectionStatus(sv->offline_data_collection_status));
1821:
1822: /* Print selective self-test flags. Possible flag combinations are
1823: (numbering bits from 0-15):
1824: Bit-1 Bit-3 Bit-4
1825: Scan Pending Active
1826: 0 * * Don't scan
1827: 1 0 0 Will carry out scan after selective test
1828: 1 1 0 Waiting to carry out scan after powerup
1829: 1 0 1 Currently scanning
1830: 1 1 1 Currently scanning
1831: */
1832:
1833: pout("Selective self-test flags (0x%x):\n", (unsigned int)log->flags);
1834: if (log->flags & SELECTIVE_FLAG_DOSCAN) {
1835: if (log->flags & SELECTIVE_FLAG_ACTIVE)
1836: pout(" Currently read-scanning the remainder of the disk.\n");
1837: else if (log->flags & SELECTIVE_FLAG_PENDING)
1838: pout(" Read-scan of remainder of disk interrupted; will resume %d min after power-up.\n",
1839: (int)log->pendingtime);
1840: else
1841: pout(" After scanning selected spans, read-scan remainder of disk.\n");
1842: }
1843: else
1844: pout(" After scanning selected spans, do NOT read-scan remainder of disk.\n");
1845:
1846: // print pending time
1847: pout("If Selective self-test is pending on power-up, resume after %d minute delay.\n",
1848: (int)log->pendingtime);
1849:
1850: return;
1851: }
1852:
1853: // Format SCT Temperature value
1854: static const char * sct_ptemp(signed char x, char * buf)
1855: {
1856: if (x == -128 /*0x80 = unknown*/)
1857: strcpy(buf, " ?");
1858: else
1859: sprintf(buf, "%2d", x);
1860: return buf;
1861: }
1862:
1863: static const char * sct_pbar(int x, char * buf)
1864: {
1865: if (x <= 19)
1866: x = 0;
1867: else
1868: x -= 19;
1869: bool ov = false;
1870: if (x > 40) {
1871: x = 40; ov = true;
1872: }
1873: if (x > 0) {
1874: memset(buf, '*', x);
1875: if (ov)
1876: buf[x-1] = '+';
1877: buf[x] = 0;
1878: }
1879: else {
1880: buf[0] = '-'; buf[1] = 0;
1881: }
1882: return buf;
1883: }
1884:
1885: static const char * sct_device_state_msg(unsigned char state)
1886: {
1887: switch (state) {
1888: case 0: return "Active";
1889: case 1: return "Stand-by";
1890: case 2: return "Sleep";
1891: case 3: return "DST executing in background";
1892: case 4: return "SMART Off-line Data Collection executing in background";
1893: case 5: return "SCT command executing in background";
1894: default:return "Unknown";
1895: }
1896: }
1897:
1898: // Print SCT Status
1899: static int ataPrintSCTStatus(const ata_sct_status_response * sts)
1900: {
1901: pout("SCT Status Version: %u\n", sts->format_version);
1902: pout("SCT Version (vendor specific): %u (0x%04x)\n", sts->sct_version, sts->sct_version);
1903: pout("SCT Support Level: %u\n", sts->sct_spec);
1904: pout("Device State: %s (%u)\n",
1905: sct_device_state_msg(sts->device_state), sts->device_state);
1906: char buf1[20], buf2[20];
1907: if ( !sts->min_temp && !sts->life_min_temp && !sts->byte205
1908: && !sts->under_limit_count && !sts->over_limit_count ) {
1909: // "Reserved" fields not set, assume "old" format version 2
1910: // Table 11 of T13/1701DT Revision 5
1911: // Table 54 of T13/1699-D Revision 3e
1912: pout("Current Temperature: %s Celsius\n",
1913: sct_ptemp(sts->hda_temp, buf1));
1914: pout("Power Cycle Max Temperature: %s Celsius\n",
1915: sct_ptemp(sts->max_temp, buf2));
1916: pout("Lifetime Max Temperature: %s Celsius\n",
1917: sct_ptemp(sts->life_max_temp, buf2));
1918: }
1919: else {
1920: // Assume "new" format version 2 or version 3
1921: // T13/e06152r0-3 (Additional SCT Temperature Statistics)
1922: // Table 60 of T13/1699-D Revision 3f
1923: pout("Current Temperature: %s Celsius\n",
1924: sct_ptemp(sts->hda_temp, buf1));
1925: pout("Power Cycle Min/Max Temperature: %s/%s Celsius\n",
1926: sct_ptemp(sts->min_temp, buf1), sct_ptemp(sts->max_temp, buf2));
1927: pout("Lifetime Min/Max Temperature: %s/%s Celsius\n",
1928: sct_ptemp(sts->life_min_temp, buf1), sct_ptemp(sts->life_max_temp, buf2));
1929: if (sts->byte205) // e06152r0-2, removed in e06152r3
1930: pout("Lifetime Average Temperature: %s Celsius\n",
1931: sct_ptemp((signed char)sts->byte205, buf1));
1932: pout("Under/Over Temperature Limit Count: %2u/%u\n",
1933: sts->under_limit_count, sts->over_limit_count);
1934: }
1935: return 0;
1936: }
1937:
1938: // Print SCT Temperature History Table
1939: static int ataPrintSCTTempHist(const ata_sct_temperature_history_table * tmh)
1940: {
1941: char buf1[20], buf2[80];
1942: pout("SCT Temperature History Version: %u\n", tmh->format_version);
1943: pout("Temperature Sampling Period: %u minute%s\n",
1944: tmh->sampling_period, (tmh->sampling_period==1?"":"s"));
1945: pout("Temperature Logging Interval: %u minute%s\n",
1946: tmh->interval, (tmh->interval==1?"":"s"));
1947: pout("Min/Max recommended Temperature: %s/%s Celsius\n",
1948: sct_ptemp(tmh->min_op_limit, buf1), sct_ptemp(tmh->max_op_limit, buf2));
1949: pout("Min/Max Temperature Limit: %s/%s Celsius\n",
1950: sct_ptemp(tmh->under_limit, buf1), sct_ptemp(tmh->over_limit, buf2));
1951: pout("Temperature History Size (Index): %u (%u)\n", tmh->cb_size, tmh->cb_index);
1952: if (!(0 < tmh->cb_size && tmh->cb_size <= sizeof(tmh->cb) && tmh->cb_index < tmh->cb_size)) {
1953: pout("Error invalid Temperature History Size or Index\n");
1954: return 0;
1955: }
1956:
1957: // Print table
1958: pout("\nIndex Estimated Time Temperature Celsius\n");
1959: unsigned n = 0, i = (tmh->cb_index+1) % tmh->cb_size;
1960: unsigned interval = (tmh->interval > 0 ? tmh->interval : 1);
1961: time_t t = time(0) - (tmh->cb_size-1) * interval * 60;
1962: t -= t % (interval * 60);
1963: while (n < tmh->cb_size) {
1964: // Find range of identical temperatures
1965: unsigned n1 = n, n2 = n+1, i2 = (i+1) % tmh->cb_size;
1966: while (n2 < tmh->cb_size && tmh->cb[i2] == tmh->cb[i]) {
1967: n2++; i2 = (i2+1) % tmh->cb_size;
1968: }
1969: // Print range
1970: while (n < n2) {
1971: if (n == n1 || n == n2-1 || n2 <= n1+3) {
1972: char date[30];
1973: // TODO: Don't print times < boot time
1974: strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&t));
1975: pout(" %3u %s %s %s\n", i, date,
1976: sct_ptemp(tmh->cb[i], buf1), sct_pbar(tmh->cb[i], buf2));
1977: }
1978: else if (n == n1+1) {
1979: pout(" ... ..(%3u skipped). .. %s\n",
1980: n2-n1-2, sct_pbar(tmh->cb[i], buf2));
1981: }
1982: t += interval * 60; i = (i+1) % tmh->cb_size; n++;
1983: }
1984: }
1985: //assert(n == tmh->cb_size && i == (tmh->cb_index+1) % tmh->cb_size);
1986:
1987: return 0;
1988: }
1989:
1990: // Print SCT Error Recovery Control timers
1991: static void ataPrintSCTErrorRecoveryControl(bool set, unsigned short read_timer, unsigned short write_timer)
1992: {
1993: pout("SCT Error Recovery Control%s:\n", (set ? " set to" : ""));
1994: if (!read_timer)
1995: pout(" Read: Disabled\n");
1996: else
1997: pout(" Read: %6d (%0.1f seconds)\n", read_timer, read_timer/10.0);
1998: if (!write_timer)
1999: pout(" Write: Disabled\n");
2000: else
2001: pout(" Write: %6d (%0.1f seconds)\n", write_timer, write_timer/10.0);
2002: }
2003:
2004:
2005: int ataPrintMain (ata_device * device, const ata_print_options & options)
2006: {
2007: // If requested, check power mode first
2008: const char * powername = 0;
2009: bool powerchg = false;
2010: if (options.powermode) {
2011: unsigned char powerlimit = 0xff;
2012: int powermode = ataCheckPowerMode(device);
2013: switch (powermode) {
2014: case -1:
2015: if (device->get_errno() == ENOSYS) {
2016: pout("CHECK POWER MODE not implemented, ignoring -n option\n"); break;
2017: }
2018: powername = "SLEEP"; powerlimit = 2;
2019: break;
2020: case 0:
2021: powername = "STANDBY"; powerlimit = 3; break;
2022: case 0x80:
2023: powername = "IDLE"; powerlimit = 4; break;
2024: case 0xff:
2025: powername = "ACTIVE or IDLE"; break;
2026: default:
2027: pout("CHECK POWER MODE returned unknown value 0x%02x, ignoring -n option\n", powermode);
2028: break;
2029: }
2030: if (powername) {
2031: if (options.powermode >= powerlimit) {
2032: pout("Device is in %s mode, exit(%d)\n", powername, FAILPOWER);
2033: return FAILPOWER;
2034: }
2035: powerchg = (powermode != 0xff); // SMART tests will spin up drives
2036: }
2037: }
2038:
2039: // SMART values needed ?
2040: bool need_smart_val = (
2041: options.smart_check_status
2042: || options.smart_general_values
2043: || options.smart_vendor_attrib
2044: || options.smart_error_log
2045: || options.smart_selftest_log
2046: || options.smart_selective_selftest_log
2047: || options.smart_ext_error_log
2048: || options.smart_ext_selftest_log
2049: || options.smart_auto_offl_enable
2050: || options.smart_auto_offl_disable
2051: || options.smart_selftest_type != -1
2052: );
2053:
2054: // SMART must be enabled ?
2055: bool need_smart_enabled = (
2056: need_smart_val
2057: || options.smart_auto_save_enable
2058: || options.smart_auto_save_disable
2059: );
2060:
2061: // SMART feature set needed ?
2062: bool need_smart_support = (
2063: need_smart_enabled
2064: || options.smart_enable
2065: || options.smart_disable
2066: );
2067:
2068: // SMART and GP log directories needed ?
2069: bool need_smart_logdir = options.smart_logdir;
2070:
2071: bool need_gp_logdir = (
2072: options.gp_logdir
2073: || options.smart_ext_error_log
2074: || options.smart_ext_selftest_log
2075: || options.sataphy
2076: || options.devstat_all_pages
2077: || options.devstat_ssd_page
2078: || !options.devstat_pages.empty()
2079: );
2080:
2081: unsigned i;
2082: for (i = 0; i < options.log_requests.size(); i++) {
2083: if (options.log_requests[i].gpl)
2084: need_gp_logdir = true;
2085: else
2086: need_smart_logdir = true;
2087: }
2088:
2089: // SCT commands needed ?
2090: bool need_sct_support = (
2091: options.sct_temp_sts
2092: || options.sct_temp_hist
2093: || options.sct_temp_int
2094: || options.sct_erc_get
2095: || options.sct_erc_set
2096: );
2097:
2098: // Exit if no further options specified
2099: if (!( options.drive_info || need_smart_support
2100: || need_smart_logdir || need_gp_logdir
2101: || need_sct_support )) {
2102: if (powername)
2103: pout("Device is in %s mode\n", powername);
2104: else
2105: pout("ATA device successfully opened\n\n"
2106: "Use 'smartctl -a' (or '-x') to print SMART (and more) information\n\n");
2107: return 0;
2108: }
2109:
2110: // Start by getting Drive ID information. We need this, to know if SMART is supported.
2111: int returnval = 0;
2112: ata_identify_device drive; memset(&drive, 0, sizeof(drive));
2113: device->clear_err();
2114: int retid = ata_read_identity(device, &drive, options.fix_swapped_id);
2115: if (retid < 0) {
2116: pout("Smartctl: Device Read Identity Failed: %s\n\n",
2117: (device->get_errno() ? device->get_errmsg() : "Unknown error"));
2118: failuretest(MANDATORY_CMD, returnval|=FAILID);
2119: }
2120: else if (!nonempty(&drive, sizeof(drive))) {
2121: pout("Smartctl: Device Read Identity Failed: empty IDENTIFY data\n\n");
2122: failuretest(MANDATORY_CMD, returnval|=FAILID);
2123: }
2124:
2125: // If requested, show which presets would be used for this drive and exit.
2126: if (options.show_presets) {
2127: show_presets(&drive);
2128: return 0;
2129: }
2130:
2131: // Use preset vendor attribute options unless user has requested otherwise.
2132: ata_vendor_attr_defs attribute_defs = options.attribute_defs;
2133: unsigned char fix_firmwarebug = options.fix_firmwarebug;
2134: const drive_settings * dbentry = 0;
2135: if (!options.ignore_presets)
2136: dbentry = lookup_drive_apply_presets(&drive, attribute_defs,
2137: fix_firmwarebug);
2138:
2139: // Get capacity and sector sizes
2140: ata_size_info sizes;
2141: ata_get_size_info(&drive, sizes);
2142:
2143: // Print most drive identity information if requested
2144: if (options.drive_info) {
2145: pout("=== START OF INFORMATION SECTION ===\n");
2146: print_drive_info(&drive, sizes, dbentry);
2147: }
2148:
2149: // Check and print SMART support and state
2150: int smart_supported = -1, smart_enabled = -1;
2151: if (need_smart_support || options.drive_info) {
2152:
2153: // Packet device ?
2154: if (retid > 0) {
2155: pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n",
2156: packetdevicetype(retid-1));
2157: }
2158: else {
2159: // Disk device: SMART supported and enabled ?
2160: smart_supported = ataSmartSupport(&drive);
2161: smart_enabled = ataIsSmartEnabled(&drive);
2162:
2163: if (smart_supported < 0)
2164: pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
2165: if (smart_supported && smart_enabled < 0) {
2166: pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
2167: if (need_smart_support) {
2168: failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2169: // check SMART support by trying a command
2170: pout(" Checking to be sure by trying SMART RETURN STATUS command.\n");
2171: if (ataDoesSmartWork(device))
2172: smart_supported = smart_enabled = 1;
2173: }
2174: }
2175: else if (smart_supported < 0 && (smart_enabled > 0 || dbentry))
2176: // Assume supported if enabled or in drive database
2177: smart_supported = 1;
2178:
2179: if (smart_supported < 0)
2180: pout("SMART support is: Unknown - Try option -s with argument 'on' to enable it.");
2181: else if (!smart_supported)
2182: pout("SMART support is: Unavailable - device lacks SMART capability.\n");
2183: else {
2184: if (options.drive_info)
2185: pout("SMART support is: Available - device has SMART capability.\n");
2186: if (smart_enabled >= 0) {
2187: if (device->ata_identify_is_cached()) {
2188: if (options.drive_info)
2189: pout(" %sabled status cached by OS, trying SMART RETURN STATUS cmd.\n",
2190: (smart_enabled?"En":"Dis"));
2191: smart_enabled = ataDoesSmartWork(device);
2192: }
2193: if (options.drive_info)
2194: pout("SMART support is: %s\n",
2195: (smart_enabled ? "Enabled" : "Disabled"));
2196: }
2197: }
2198: }
2199: }
2200:
2201: // Print remaining drive info
2202: if (options.drive_info) {
2203: // Print the (now possibly changed) power mode if available
2204: if (powername)
2205: pout("Power mode %s %s\n", (powerchg?"was:":"is: "), powername);
2206: pout("\n");
2207: }
2208:
2209: // Exit if SMART is not supported but must be available to proceed
2210: if (smart_supported <= 0 && need_smart_support)
2211: failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2212:
2213: // START OF THE ENABLE/DISABLE SECTION OF THE CODE
2214: if ( options.smart_disable || options.smart_enable
2215: || options.smart_auto_save_disable || options.smart_auto_save_enable
2216: || options.smart_auto_offl_disable || options.smart_auto_offl_enable)
2217: pout("=== START OF ENABLE/DISABLE COMMANDS SECTION ===\n");
2218:
2219: // Enable/Disable SMART commands
2220: if (options.smart_enable) {
2221: if (ataEnableSmart(device)) {
2222: pout("Smartctl: SMART Enable Failed.\n\n");
2223: failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2224: }
2225: else {
2226: pout("SMART Enabled.\n");
2227: smart_enabled = 1;
2228: }
2229: }
2230:
2231: // Turn off SMART on device
2232: if (options.smart_disable) {
2233: if (ataDisableSmart(device)) {
2234: pout( "Smartctl: SMART Disable Failed.\n\n");
2235: failuretest(MANDATORY_CMD,returnval|=FAILSMART);
2236: }
2237: }
2238:
2239: // Exit if SMART is disabled but must be enabled to proceed
2240: if (options.smart_disable || (smart_enabled <= 0 && need_smart_enabled)) {
2241: pout("SMART Disabled. Use option -s with argument 'on' to enable it.\n");
2242: return returnval;
2243: }
2244:
2245: // Enable/Disable Auto-save attributes
2246: if (options.smart_auto_save_enable) {
2247: if (ataEnableAutoSave(device)){
2248: pout( "Smartctl: SMART Enable Attribute Autosave Failed.\n\n");
2249: failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2250: }
2251: else
2252: pout("SMART Attribute Autosave Enabled.\n");
2253: }
2254:
2255: if (options.smart_auto_save_disable) {
2256: if (ataDisableAutoSave(device)){
2257: pout( "Smartctl: SMART Disable Attribute Autosave Failed.\n\n");
2258: failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2259: }
2260: else
2261: pout("SMART Attribute Autosave Disabled.\n");
2262: }
2263:
2264: // Read SMART values and thresholds if necessary
2265: ata_smart_values smartval; memset(&smartval, 0, sizeof(smartval));
2266: ata_smart_thresholds_pvt smartthres; memset(&smartthres, 0, sizeof(smartthres));
2267: bool smart_val_ok = false, smart_thres_ok = false;
2268:
2269: if (need_smart_val) {
2270: if (ataReadSmartValues(device, &smartval)) {
2271: pout("Smartctl: SMART Read Values failed.\n\n");
2272: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2273: }
2274: else {
2275: smart_val_ok = true;
2276:
2277: if (options.smart_check_status || options.smart_vendor_attrib) {
2278: if (ataReadSmartThresholds(device, &smartthres)){
2279: pout("Smartctl: SMART Read Thresholds failed.\n\n");
2280: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2281: }
2282: else
2283: smart_thres_ok = true;
2284: }
2285: }
2286: }
2287:
2288: // Enable/Disable Off-line testing
2289: bool needupdate = false;
2290: if (options.smart_auto_offl_enable) {
2291: if (!isSupportAutomaticTimer(&smartval)){
2292: pout("Warning: device does not support SMART Automatic Timers.\n\n");
2293: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2294: }
2295: needupdate = smart_val_ok;
2296: if (ataEnableAutoOffline(device)){
2297: pout( "Smartctl: SMART Enable Automatic Offline Failed.\n\n");
2298: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2299: }
2300: else
2301: pout("SMART Automatic Offline Testing Enabled every four hours.\n");
2302: }
2303:
2304: if (options.smart_auto_offl_disable) {
2305: if (!isSupportAutomaticTimer(&smartval)){
2306: pout("Warning: device does not support SMART Automatic Timers.\n\n");
2307: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2308: }
2309: needupdate = smart_val_ok;
2310: if (ataDisableAutoOffline(device)){
2311: pout("Smartctl: SMART Disable Automatic Offline Failed.\n\n");
2312: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2313: }
2314: else
2315: pout("SMART Automatic Offline Testing Disabled.\n");
2316: }
2317:
2318: if (needupdate && ataReadSmartValues(device, &smartval)){
2319: pout("Smartctl: SMART Read Values failed.\n\n");
2320: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2321: smart_val_ok = false;
2322: }
2323:
2324: // all this for a newline!
2325: if ( options.smart_disable || options.smart_enable
2326: || options.smart_auto_save_disable || options.smart_auto_save_enable
2327: || options.smart_auto_offl_disable || options.smart_auto_offl_enable)
2328: pout("\n");
2329:
2330: // START OF READ-ONLY OPTIONS APART FROM -V and -i
2331: if ( options.smart_check_status || options.smart_general_values
2332: || options.smart_vendor_attrib || options.smart_error_log
2333: || options.smart_selftest_log || options.smart_selective_selftest_log
2334: || options.smart_ext_error_log || options.smart_ext_selftest_log
2335: || options.sct_temp_sts || options.sct_temp_hist )
2336: pout("=== START OF READ SMART DATA SECTION ===\n");
2337:
2338: // Check SMART status
2339: if (options.smart_check_status) {
2340:
2341: switch (ataSmartStatus2(device)) {
2342:
2343: case 0:
2344: // The case where the disk health is OK
2345: pout("SMART overall-health self-assessment test result: PASSED\n");
2346: if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
2347: if (options.smart_vendor_attrib)
2348: pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
2349: else {
2350: print_on();
2351: pout("Please note the following marginal Attributes:\n");
2352: PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 2, options.output_format);
2353: }
2354: returnval|=FAILAGE;
2355: }
2356: else
2357: pout("\n");
2358: break;
2359:
2360: case 1:
2361: // The case where the disk health is NOT OK
2362: print_on();
2363: pout("SMART overall-health self-assessment test result: FAILED!\n"
2364: "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
2365: print_off();
2366: if (smart_thres_ok && find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
2367: returnval|=FAILATTR;
2368: if (options.smart_vendor_attrib)
2369: pout("See vendor-specific Attribute list for failed Attributes.\n\n");
2370: else {
2371: print_on();
2372: pout("Failed Attributes:\n");
2373: PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 1, options.output_format);
2374: }
2375: }
2376: else
2377: pout("No failed Attributes found.\n\n");
2378: returnval|=FAILSTATUS;
2379: print_off();
2380: break;
2381:
2382: case -1:
2383: default:
2384: // Something went wrong with the SMART STATUS command.
2385: // The ATA SMART RETURN STATUS command provides the result in the ATA output
2386: // registers. Buggy ATA/SATA drivers and SAT Layers often do not properly
2387: // return the registers values.
2388: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2389: if (!(smart_val_ok && smart_thres_ok)) {
2390: print_on();
2391: pout("SMART overall-health self-assessment test result: UNKNOWN!\n"
2392: "SMART Status, Attributes and Thresholds cannot be read.\n\n");
2393: }
2394: else if (find_failed_attr(&smartval, &smartthres, attribute_defs, 1)) {
2395: print_on();
2396: pout("SMART overall-health self-assessment test result: FAILED!\n"
2397: "Drive failure expected in less than 24 hours. SAVE ALL DATA.\n");
2398: print_off();
2399: returnval|=FAILATTR;
2400: returnval|=FAILSTATUS;
2401: if (options.smart_vendor_attrib)
2402: pout("See vendor-specific Attribute list for failed Attributes.\n\n");
2403: else {
2404: print_on();
2405: pout("Failed Attributes:\n");
2406: PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 1, options.output_format);
2407: }
2408: }
2409: else {
2410: pout("SMART overall-health self-assessment test result: PASSED\n");
2411: pout("Warning: This result is based on an Attribute check.\n");
2412: if (find_failed_attr(&smartval, &smartthres, attribute_defs, 0)) {
2413: if (options.smart_vendor_attrib)
2414: pout("See vendor-specific Attribute list for marginal Attributes.\n\n");
2415: else {
2416: print_on();
2417: pout("Please note the following marginal Attributes:\n");
2418: PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs, 2, options.output_format);
2419: }
2420: returnval|=FAILAGE;
2421: }
2422: else
2423: pout("\n");
2424: }
2425: print_off();
2426: break;
2427: } // end of switch statement
2428:
2429: print_off();
2430: } // end of checking SMART Status
2431:
2432: // Print general SMART values
2433: if (smart_val_ok && options.smart_general_values)
2434: PrintGeneralSmartValues(&smartval, &drive, fix_firmwarebug);
2435:
2436: // Print vendor-specific attributes
2437: if (smart_val_ok && options.smart_vendor_attrib) {
2438: print_on();
2439: PrintSmartAttribWithThres(&smartval, &smartthres, attribute_defs,
2440: (printing_is_switchable ? 2 : 0), options.output_format);
2441: print_off();
2442: }
2443:
2444: // If GP Log is supported use smart log directory for
2445: // error and selftest log support check.
2446: if ( isGeneralPurposeLoggingCapable(&drive)
2447: && ( options.smart_error_log || options.smart_selftest_log
2448: || options.retry_error_log || options.retry_selftest_log))
2449: need_smart_logdir = true;
2450:
2451: ata_smart_log_directory smartlogdir_buf, gplogdir_buf;
2452: const ata_smart_log_directory * smartlogdir = 0, * gplogdir = 0;
2453:
2454: // Read SMART Log directory
2455: if (need_smart_logdir) {
2456: if (ataReadLogDirectory(device, &smartlogdir_buf, false)) {
2457: pout("Read SMART Log Directory failed.\n\n");
2458: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2459: }
2460: else
2461: smartlogdir = &smartlogdir_buf;
2462: }
2463:
2464: // Read GP Log directory
2465: if (need_gp_logdir) {
2466: if (ataReadLogDirectory(device, &gplogdir_buf, true)) {
2467: pout("Read GP Log Directory failed.\n\n");
2468: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2469: }
2470: else
2471: gplogdir = &gplogdir_buf;
2472: }
2473:
2474: // Print log directories
2475: if ((options.gp_logdir && gplogdir) || (options.smart_logdir && smartlogdir))
2476: PrintLogDirectories(gplogdir, smartlogdir);
2477:
2478: // Print log pages
2479: for (i = 0; i < options.log_requests.size(); i++) {
2480: const ata_log_request & req = options.log_requests[i];
2481:
2482: const char * type;
2483: unsigned max_nsectors;
2484: if (req.gpl) {
2485: type = "General Purpose";
2486: max_nsectors = GetNumLogSectors(gplogdir, req.logaddr, true);
2487: }
2488: else {
2489: type = "SMART";
2490: max_nsectors = GetNumLogSectors(smartlogdir, req.logaddr, false);
2491: }
2492:
2493: if (!max_nsectors) {
2494: if (!is_permissive()) {
2495: pout("%s Log 0x%02x does not exist (override with '-T permissive' option)\n", type, req.logaddr);
2496: continue;
2497: }
2498: max_nsectors = req.page+1;
2499: }
2500: if (max_nsectors <= req.page) {
2501: pout("%s Log 0x%02x has only %u sectors, output skipped\n", type, req.logaddr, max_nsectors);
2502: continue;
2503: }
2504:
2505: unsigned ns = req.nsectors;
2506: if (ns > max_nsectors - req.page) {
2507: if (req.nsectors != ~0U) // "FIRST-max"
2508: pout("%s Log 0x%02x has only %u sectors, output truncated\n", type, req.logaddr, max_nsectors);
2509: ns = max_nsectors - req.page;
2510: }
2511:
2512: // SMART log don't support sector offset, start with first sector
2513: unsigned offs = (req.gpl ? 0 : req.page);
2514:
2515: raw_buffer log_buf((offs + ns) * 512);
2516: bool ok;
2517: if (req.gpl)
2518: ok = ataReadLogExt(device, req.logaddr, 0x00, req.page, log_buf.data(), ns);
2519: else
2520: ok = ataReadSmartLog(device, req.logaddr, log_buf.data(), offs + ns);
2521: if (!ok)
2522: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2523: else
2524: PrintLogPages(type, log_buf.data() + offs*512, req.logaddr, req.page, ns, max_nsectors);
2525: }
2526:
2527: // Print SMART Extendend Comprehensive Error Log
2528: bool do_smart_error_log = options.smart_error_log;
2529: if (options.smart_ext_error_log) {
2530: bool ok = false;
2531: unsigned nsectors = GetNumLogSectors(gplogdir, 0x03, true);
2532: if (!nsectors)
2533: pout("SMART Extended Comprehensive Error Log (GP Log 0x03) not supported\n");
2534: else if (nsectors >= 256)
2535: pout("SMART Extended Comprehensive Error Log size %u not supported\n", nsectors);
2536: else {
2537: raw_buffer log_03_buf(nsectors * 512);
2538: ata_smart_exterrlog * log_03 = (ata_smart_exterrlog *)log_03_buf.data();
2539: if (!ataReadExtErrorLog(device, log_03, nsectors))
2540: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2541: else {
2542: if (PrintSmartExtErrorLog(log_03, nsectors, options.smart_ext_error_log))
2543: returnval |= FAILERR;
2544: ok = true;
2545: }
2546: }
2547:
2548: if (!ok) {
2549: if (options.retry_error_log)
2550: do_smart_error_log = true;
2551: else if (!do_smart_error_log)
2552: pout("Try '-l [xerror,]error' to read traditional SMART Error Log\n");
2553: }
2554: }
2555:
2556: // Print SMART error log
2557: if (do_smart_error_log) {
2558: if (!( ( smartlogdir && GetNumLogSectors(smartlogdir, 0x01, false))
2559: || (!smartlogdir && isSmartErrorLogCapable(&smartval, &drive) )
2560: || is_permissive() )) {
2561: pout("SMART Error Log not supported\n");
2562: }
2563: else {
2564: ata_smart_errorlog smarterror; memset(&smarterror, 0, sizeof(smarterror));
2565: if (ataReadErrorLog(device, &smarterror, fix_firmwarebug)) {
2566: pout("Smartctl: SMART Error Log Read Failed\n");
2567: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2568: }
2569: else {
2570: // quiet mode is turned on inside PrintSmartErrorLog()
2571: if (PrintSmartErrorlog(&smarterror, fix_firmwarebug))
2572: returnval|=FAILERR;
2573: print_off();
2574: }
2575: }
2576: }
2577:
2578: // Print SMART Extendend Self-test Log
2579: bool do_smart_selftest_log = options.smart_selftest_log;
2580: if (options.smart_ext_selftest_log) {
2581: bool ok = false;
2582: unsigned nsectors = GetNumLogSectors(gplogdir, 0x07, true);
2583: if (!nsectors)
2584: pout("SMART Extended Self-test Log (GP Log 0x07) not supported\n");
2585: else if (nsectors >= 256)
2586: pout("SMART Extended Self-test Log size %u not supported\n", nsectors);
2587: else {
2588: raw_buffer log_07_buf(nsectors * 512);
2589: ata_smart_extselftestlog * log_07 = (ata_smart_extselftestlog *)log_07_buf.data();
2590: if (!ataReadExtSelfTestLog(device, log_07, nsectors))
2591: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2592: else {
2593: if (PrintSmartExtSelfTestLog(log_07, nsectors, options.smart_ext_selftest_log))
2594: returnval |= FAILLOG;
2595: ok = true;
2596: }
2597: }
2598:
2599: if (!ok) {
2600: if (options.retry_selftest_log)
2601: do_smart_selftest_log = true;
2602: else if (!do_smart_selftest_log)
2603: pout("Try '-l [xselftest,]selftest' to read traditional SMART Self Test Log\n");
2604: }
2605: }
2606:
2607: // Print SMART self-test log
2608: if (do_smart_selftest_log) {
2609: if (!( ( smartlogdir && GetNumLogSectors(smartlogdir, 0x06, false))
2610: || (!smartlogdir && isSmartTestLogCapable(&smartval, &drive) )
2611: || is_permissive() )) {
2612: pout("SMART Self-test Log not supported\n");
2613: }
2614: else {
2615: ata_smart_selftestlog smartselftest; memset(&smartselftest, 0, sizeof(smartselftest));
2616: if (ataReadSelfTestLog(device, &smartselftest, fix_firmwarebug)) {
2617: pout("Smartctl: SMART Self Test Log Read Failed\n");
2618: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2619: }
2620: else {
2621: print_on();
2622: if (ataPrintSmartSelfTestlog(&smartselftest, !printing_is_switchable, fix_firmwarebug))
2623: returnval |= FAILLOG;
2624: print_off();
2625: pout("\n");
2626: }
2627: }
2628: }
2629:
2630: // Print SMART selective self-test log
2631: if (options.smart_selective_selftest_log) {
2632: ata_selective_self_test_log log;
2633:
2634: if (!isSupportSelectiveSelfTest(&smartval))
2635: pout("Device does not support Selective Self Tests/Logging\n");
2636: else if(ataReadSelectiveSelfTestLog(device, &log)) {
2637: pout("Smartctl: SMART Selective Self Test Log Read Failed\n");
2638: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2639: }
2640: else {
2641: print_on();
2642: // If any errors were found, they are logged in the SMART Self-test log.
2643: // So there is no need to print the Selective Self Test log in silent
2644: // mode.
2645: if (!printing_is_switchable)
2646: ataPrintSelectiveSelfTestLog(&log, &smartval);
2647: print_off();
2648: pout("\n");
2649: }
2650: }
2651:
2652: // SCT commands
2653: bool sct_ok = false;
2654: if (need_sct_support) {
2655: if (!isSCTCapable(&drive)) {
2656: pout("Warning: device does not support SCT Commands\n");
2657: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2658: }
2659: else
2660: sct_ok = true;
2661: }
2662:
2663: // Print SCT status and temperature history table
2664: if (sct_ok && (options.sct_temp_sts || options.sct_temp_hist || options.sct_temp_int)) {
2665: for (;;) {
2666: if (options.sct_temp_sts || options.sct_temp_hist) {
2667: ata_sct_status_response sts;
2668: ata_sct_temperature_history_table tmh;
2669: if (!options.sct_temp_hist) {
2670: // Read SCT status only
2671: if (ataReadSCTStatus(device, &sts)) {
2672: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2673: break;
2674: }
2675: }
2676: else {
2677: if (!isSCTDataTableCapable(&drive)) {
2678: pout("Warning: device does not support SCT Data Table command\n");
2679: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2680: break;
2681: }
2682: // Read SCT status and temperature history
2683: if (ataReadSCTTempHist(device, &tmh, &sts)) {
2684: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2685: break;
2686: }
2687: }
2688: if (options.sct_temp_sts)
2689: ataPrintSCTStatus(&sts);
2690: if (options.sct_temp_hist)
2691: ataPrintSCTTempHist(&tmh);
2692: pout("\n");
2693: }
2694: if (options.sct_temp_int) {
2695: // Set new temperature logging interval
2696: if (!isSCTFeatureControlCapable(&drive)) {
2697: pout("Warning: device does not support SCT Feature Control command\n");
2698: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2699: break;
2700: }
2701: if (ataSetSCTTempInterval(device, options.sct_temp_int, options.sct_temp_int_pers)) {
2702: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2703: break;
2704: }
2705: pout("Temperature Logging Interval set to %u minute%s (%s)\n",
2706: options.sct_temp_int, (options.sct_temp_int == 1 ? "" : "s"),
2707: (options.sct_temp_int_pers ? "persistent" : "volatile"));
2708: }
2709: break;
2710: }
2711: }
2712:
2713: // SCT Error Recovery Control
2714: if (sct_ok && (options.sct_erc_get || options.sct_erc_set)) {
2715: if (!isSCTErrorRecoveryControlCapable(&drive)) {
2716: pout("Warning: device does not support SCT Error Recovery Control command\n");
2717: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2718: }
2719: else {
2720: bool sct_erc_get = options.sct_erc_get;
2721: if (options.sct_erc_set) {
2722: // Set SCT Error Recovery Control
2723: if ( ataSetSCTErrorRecoveryControltime(device, 1, options.sct_erc_readtime )
2724: || ataSetSCTErrorRecoveryControltime(device, 2, options.sct_erc_writetime)) {
2725: pout("Warning: device does not support SCT (Set) Error Recovery Control command\n");
2726: if (!( (options.sct_erc_readtime == 70 && options.sct_erc_writetime == 70)
2727: || (options.sct_erc_readtime == 0 && options.sct_erc_writetime == 0)))
2728: pout("Retry with: 'scterc,70,70' to enable ERC or 'scterc,0,0' to disable\n");
2729: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2730: sct_erc_get = false;
2731: }
2732: else if (!sct_erc_get)
2733: ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
2734: options.sct_erc_writetime);
2735: }
2736:
2737: if (sct_erc_get) {
2738: // Print SCT Error Recovery Control
2739: unsigned short read_timer, write_timer;
2740: if ( ataGetSCTErrorRecoveryControltime(device, 1, read_timer )
2741: || ataGetSCTErrorRecoveryControltime(device, 2, write_timer)) {
2742: pout("Warning: device does not support SCT (Get) Error Recovery Control command\n");
2743: if (options.sct_erc_set) {
2744: pout("The previous SCT (Set) Error Recovery Control command succeeded\n");
2745: ataPrintSCTErrorRecoveryControl(true, options.sct_erc_readtime,
2746: options.sct_erc_writetime);
2747: }
2748: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2749: }
2750: else
2751: ataPrintSCTErrorRecoveryControl(false, read_timer, write_timer);
2752: }
2753: pout("\n");
2754: }
2755: }
2756:
2757: // Print Device Statistics
2758: if (options.devstat_all_pages || options.devstat_ssd_page || !options.devstat_pages.empty()) {
2759: unsigned nsectors = GetNumLogSectors(gplogdir, 0x04, true);
2760: if (!nsectors)
2761: pout("Device Statistics (GP Log 0x04) not supported\n");
2762: else if (!print_device_statistics(device, nsectors, options.devstat_pages,
2763: options.devstat_all_pages, options.devstat_ssd_page))
2764: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2765: }
2766:
2767: // Print SATA Phy Event Counters
2768: if (options.sataphy) {
2769: unsigned nsectors = GetNumLogSectors(gplogdir, 0x11, true);
2770: if (!nsectors)
2771: pout("SATA Phy Event Counters (GP Log 0x11) not supported\n");
2772: else if (nsectors != 1)
2773: pout("SATA Phy Event Counters with %u sectors not supported\n", nsectors);
2774: else {
2775: unsigned char log_11[512] = {0, };
2776: unsigned char features = (options.sataphy_reset ? 0x01 : 0x00);
2777: if (!ataReadLogExt(device, 0x11, features, 0, log_11, 1))
2778: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2779: else
2780: PrintSataPhyEventCounters(log_11, options.sataphy_reset);
2781: }
2782: }
2783:
2784: // START OF THE TESTING SECTION OF THE CODE. IF NO TESTING, RETURN
2785: if (!smart_val_ok || options.smart_selftest_type == -1)
2786: return returnval;
2787:
2788: pout("=== START OF OFFLINE IMMEDIATE AND SELF-TEST SECTION ===\n");
2789: // if doing a self-test, be sure it's supported by the hardware
2790: switch (options.smart_selftest_type) {
2791: case OFFLINE_FULL_SCAN:
2792: if (!isSupportExecuteOfflineImmediate(&smartval)){
2793: pout("Warning: device does not support Execute Offline Immediate function.\n\n");
2794: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2795: }
2796: break;
2797: case ABORT_SELF_TEST:
2798: case SHORT_SELF_TEST:
2799: case EXTEND_SELF_TEST:
2800: case SHORT_CAPTIVE_SELF_TEST:
2801: case EXTEND_CAPTIVE_SELF_TEST:
2802: if (!isSupportSelfTest(&smartval)){
2803: pout("Warning: device does not support Self-Test functions.\n\n");
2804: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2805: }
2806: break;
2807: case CONVEYANCE_SELF_TEST:
2808: case CONVEYANCE_CAPTIVE_SELF_TEST:
2809: if (!isSupportConveyanceSelfTest(&smartval)){
2810: pout("Warning: device does not support Conveyance Self-Test functions.\n\n");
2811: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2812: }
2813: break;
2814: case SELECTIVE_SELF_TEST:
2815: case SELECTIVE_CAPTIVE_SELF_TEST:
2816: if (!isSupportSelectiveSelfTest(&smartval)){
2817: pout("Warning: device does not support Selective Self-Test functions.\n\n");
2818: failuretest(MANDATORY_CMD, returnval|=FAILSMART);
2819: }
2820: break;
2821: default:
2822: break; // Vendor specific type
2823: }
2824:
2825: // Now do the test. Note ataSmartTest prints its own error/success
2826: // messages
2827: if (ataSmartTest(device, options.smart_selftest_type, options.smart_selective_args,
2828: &smartval, sizes.sectors ))
2829: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2830: else {
2831: // Tell user how long test will take to complete. This is tricky
2832: // because in the case of an Offline Full Scan, the completion
2833: // timer is volatile, and needs to be read AFTER the command is
2834: // given. If this will interrupt the Offline Full Scan, we don't
2835: // do it, just warn user.
2836: if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
2837: if (isSupportOfflineAbort(&smartval))
2838: pout("Note: giving further SMART commands will abort Offline testing\n");
2839: else if (ataReadSmartValues(device, &smartval)){
2840: pout("Smartctl: SMART Read Values failed.\n");
2841: failuretest(OPTIONAL_CMD, returnval|=FAILSMART);
2842: }
2843: }
2844:
2845: // Now say how long the test will take to complete
2846: int timewait = TestTime(&smartval, options.smart_selftest_type);
2847: if (timewait) {
2848: time_t t=time(NULL);
2849: if (options.smart_selftest_type == OFFLINE_FULL_SCAN) {
2850: t+=timewait;
2851: pout("Please wait %d seconds for test to complete.\n", (int)timewait);
2852: } else {
2853: t+=timewait*60;
2854: pout("Please wait %d minutes for test to complete.\n", (int)timewait);
2855: }
2856: pout("Test will complete after %s\n", ctime(&t));
2857:
2858: if ( options.smart_selftest_type != SHORT_CAPTIVE_SELF_TEST
2859: && options.smart_selftest_type != EXTEND_CAPTIVE_SELF_TEST
2860: && options.smart_selftest_type != CONVEYANCE_CAPTIVE_SELF_TEST
2861: && options.smart_selftest_type != SELECTIVE_CAPTIVE_SELF_TEST )
2862: pout("Use smartctl -X to abort test.\n");
2863: }
2864: }
2865:
2866: return returnval;
2867: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>