*
* Home page of code is: http://smartmontools.sourceforge.net
*
- * Copyright (C) 2002-9 Bruce Allen <smartmontools-support@lists.sourceforge.net>
- * Copyright (C) 2008-9 Christian Franke <smartmontools-support@lists.sourceforge.net>
+ * Copyright (C) 2002-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
+ * Copyright (C) 2008-11 Christian Franke <smartmontools-support@lists.sourceforge.net>
* Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
* Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
*
#include "config.h"
#include "int64.h"
#include "atacmds.h"
-#include "extern.h"
#include "utility.h"
#include "dev_ata_cmd_set.h" // for parsed_ata_device
-const char * atacmds_cpp_cvsid = "$Id: atacmds.cpp 2928 2009-10-03 16:24:53Z chrfranke $"
+const char * atacmds_cpp_cvsid = "$Id: atacmds.cpp 3345 2011-05-25 20:50:02Z chrfranke $"
ATACMDS_H_CVSID;
-// for passing global control variables
-extern smartmonctrl *con;
+// Print ATA debug messages?
+unsigned char ata_debugmode = 0;
+
+// Suppress serial number?
+// (also used in scsiprint.cpp)
+bool dont_print_serial_number = false;
+
#define SMART_CYL_LOW 0x4F
#define SMART_CYL_HI 0xC2
// that SMART was first added into the ATA/ATAPI-3 Standard with
// Revision 3 of the document, July 25, 1995. Look at the "Document
// Status" revision commands at the beginning of
-// http://www.t13.org/project/d2008r6.pdf to see this.
+// http://www.t13.org/Documents/UploadedDocuments/project/d2008r7b-ATA-3.pdf
+// to see this.
#define NOVAL_0 0x0000
#define NOVAL_1 0xffff
/* word 81: minor version number */
6 /* 0x0022 WARNING: */
};
-// When you add additional items to this list, you should then:
-// 0 -- update this list
-// 1 -- if needed, modify ataPrintSmartAttribRawValue()
-// 2 - if needed, modify ataPrintSmartAttribName()
-// 3 -- add drive in question into builtin_knowndrives[] table in knowndrives.cpp
-// 4 -- update smartctl.8
-// 5 -- update smartd.8
-// 6 -- do "make smartd.conf.5" to update smartd.conf.5
-// 7 -- update CHANGELOG file
-
-struct vendor_attr_arg_entry
-{
- unsigned char id; // attribute ID, 0 for all
- const char * name; // attribute name
- unsigned char val; // value for attribute defs array
-};
-
-// The order of these entries is (only) relevant for '-v help' output.
-const vendor_attr_arg_entry vendor_attribute_args[] = {
- { 9,"halfminutes", 4},
- { 9,"minutes", 1},
- { 9,"seconds", 3},
- { 9,"temp", 2},
- {192,"emergencyretractcyclect", 1},
- {193,"loadunload", 1},
- {194,"10xCelsius", 1},
- {194,"unknown", 2},
- {197,"increasing", 1},
- {198,"offlinescanuncsectorct", 2},
- {198,"increasing", 1},
- {200,"writeerrorcount", 1},
- {201,"detectedtacount", 1},
- {220,"temp", 1},
- { 0,"raw8", 253},
- { 0,"raw16", 254},
- { 0,"raw48", 255},
-};
-
-const unsigned num_vendor_attribute_args = sizeof(vendor_attribute_args)/sizeof(vendor_attribute_args[0]);
+// Compile time check of above array sizes
+typedef char assert_sizeof_minor_str [sizeof(minor_str) /sizeof(minor_str[0]) == MINOR_MAX+1 ? 1 : -1];
+typedef char assert_sizeof_actual_ver[sizeof(actual_ver)/sizeof(actual_ver[0]) == MINOR_MAX+1 ? 1 : -1];
// Get ID and increase flag of current pending or offline
// uncorrectable attribute.
-unsigned char get_unc_attr_id(bool offline, const unsigned char * defs,
+unsigned char get_unc_attr_id(bool offline, const ata_vendor_attr_defs & defs,
bool & increase)
{
unsigned char id = (!offline ? 197 : 198);
- increase = (defs[id] == 1);
+ const ata_vendor_attr_defs::entry & def = defs[id];
+ if (def.flags & ATTRFLAG_INCREASING)
+ increase = true; // '-v 19[78],increasing' option
+ else if (def.name.empty() || (id == 198 && def.name == "Offline_Scan_UNC_SectCt"))
+ increase = false; // no or '-v 198,offlinescanuncsectorct' option
+ else
+ id = 0; // other '-v 19[78],...' option
return id;
}
+#if 0 // TODO: never used
// This are the meanings of the Self-test failure checkpoint byte.
// This is in the self-test log at offset 4 bytes into the self-test
// descriptor and in the SMART READ DATA structure at byte offset
return NULL;
}
}
+#endif
+
+
+// Table of raw print format names
+struct format_name_entry
+{
+ const char * name;
+ ata_attr_raw_format format;
+};
-// This is a utility function for parsing pairs like "9,minutes" or
-// "220,temp", and putting the correct flag into the attributedefs
-// array. Returns 1 if problem, 0 if pair has been recongized.
-int parse_attribute_def(const char * pair, unsigned char * defs)
+const format_name_entry format_names[] = {
+ {"raw8" , RAWFMT_RAW8},
+ {"raw16" , RAWFMT_RAW16},
+ {"raw48" , RAWFMT_RAW48},
+ {"hex48" , RAWFMT_HEX48},
+ {"raw64" , RAWFMT_RAW64},
+ {"hex64" , RAWFMT_HEX64},
+ {"raw16(raw16)" , RAWFMT_RAW16_OPT_RAW16},
+ {"raw16(avg16)" , RAWFMT_RAW16_OPT_AVG16},
+ {"raw24/raw24" , RAWFMT_RAW24_DIV_RAW24},
+ {"raw24/raw32" , RAWFMT_RAW24_DIV_RAW32},
+ {"sec2hour" , RAWFMT_SEC2HOUR},
+ {"min2hour" , RAWFMT_MIN2HOUR},
+ {"halfmin2hour" , RAWFMT_HALFMIN2HOUR},
+ {"msec24hour32" , RAWFMT_MSEC24_HOUR32},
+ {"tempminmax" , RAWFMT_TEMPMINMAX},
+ {"temp10x" , RAWFMT_TEMP10X},
+};
+
+const unsigned num_format_names = sizeof(format_names)/sizeof(format_names[0]);
+
+// Table to map old to new '-v' option arguments
+const char * map_old_vendor_opts[][2] = {
+ { "9,halfminutes" , "9,halfmin2hour,Power_On_Half_Minutes"},
+ { "9,minutes" , "9,min2hour,Power_On_Minutes"},
+ { "9,seconds" , "9,sec2hour,Power_On_Seconds"},
+ { "9,temp" , "9,tempminmax,Temperature_Celsius"},
+ {"192,emergencyretractcyclect" , "192,raw48,Emerg_Retract_Cycle_Ct"},
+ {"193,loadunload" , "193,raw24/raw24"},
+ {"194,10xCelsius" , "194,temp10x,Temperature_Celsius_x10"},
+ {"194,unknown" , "194,raw48,Unknown_Attribute"},
+ {"197,increasing" , "197,raw48+,Total_Pending_Sectors"}, // '+' sets flag
+ {"198,offlinescanuncsectorct" , "198,raw48,Offline_Scan_UNC_SectCt"}, // see also get_unc_attr_id() above
+ {"198,increasing" , "198,raw48+,Total_Offl_Uncorrectabl"}, // '+' sets flag
+ {"200,writeerrorcount" , "200,raw48,Write_Error_Count"},
+ {"201,detectedtacount" , "201,raw48,Detected_TA_Count"},
+ {"220,temp" , "220,raw48,Temperature_Celsius"},
+};
+
+const unsigned num_old_vendor_opts = sizeof(map_old_vendor_opts)/sizeof(map_old_vendor_opts[0]);
+
+// Parse vendor attribute display def (-v option).
+// Return false on error.
+bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
+ ata_vendor_def_prior priority)
{
- int id = 0, nc = -1;
- char name[32+1];
- if (pair[0] == 'N') {
- // "N,name"
- if (!(sscanf(pair, "N,%32s%n", name, &nc) == 1 && nc == (int)strlen(pair)))
- return 1;
+ // Map old -> new options
+ unsigned i;
+ for (i = 0; i < num_old_vendor_opts; i++) {
+ if (!strcmp(opt, map_old_vendor_opts[i][0])) {
+ opt = map_old_vendor_opts[i][1];
+ break;
+ }
+ }
+
+ // Parse option
+ int len = strlen(opt);
+ int id = 0, n1 = -1, n2 = -1;
+ char fmtname[32+1], attrname[32+1];
+ if (opt[0] == 'N') {
+ // "N,format"
+ if (!( sscanf(opt, "N,%32[^,]%n,%32[^,]%n", fmtname, &n1, attrname, &n2) >= 1
+ && (n1 == len || n2 == len)))
+ return false;
}
else {
- // "attr,name"
- if (!( sscanf(pair, "%d,%32s%n", &id, name, &nc) == 2
- && 1 <= id && id <= 255 && nc == (int)strlen(pair)))
- return 1;
+ // "id,format[+][,name]"
+ if (!( sscanf(opt, "%d,%32[^,]%n,%32[^,]%n", &id, fmtname, &n1, attrname, &n2) >= 2
+ && 1 <= id && id <= 255 && (n1 == len || n2 == len)))
+ return false;
}
+ if (n1 == len)
+ attrname[0] = 0;
- // Find pair
- unsigned i;
+ unsigned flags = 0;
+ // For "-v 19[78],increasing" above
+ if (fmtname[strlen(fmtname)-1] == '+') {
+ fmtname[strlen(fmtname)-1] = 0;
+ flags = ATTRFLAG_INCREASING;
+ }
+
+ // Split "format[:byteorder]"
+ char byteorder[8+1] = "";
+ if (strchr(fmtname, ':')) {
+ if (!( sscanf(fmtname, "%*[^:]%n:%8[012345rvwz]%n", &n1, byteorder, &n2) >= 1
+ && n2 == (int)strlen(fmtname)))
+ return false;
+ fmtname[n1] = 0;
+ if (strchr(byteorder, 'v'))
+ flags |= (ATTRFLAG_NO_NORMVAL|ATTRFLAG_NO_WORSTVAL);
+ if (strchr(byteorder, 'w'))
+ flags |= ATTRFLAG_NO_WORSTVAL;
+ }
+
+ // Find format name
for (i = 0; ; i++) {
- if (i >= num_vendor_attribute_args)
- return 1; // Not found
- if ( (!vendor_attribute_args[i].id || vendor_attribute_args[i].id == id)
- && !strcmp(vendor_attribute_args[i].name, name) )
+ if (i >= num_format_names)
+ return false; // Not found
+ if (!strcmp(fmtname, format_names[i].name))
break;
}
+ ata_attr_raw_format format = format_names[i].format;
+
+ // 64-bit formats use the normalized and worst value bytes.
+ if (!*byteorder && (format == RAWFMT_RAW64 || format == RAWFMT_HEX64))
+ flags |= (ATTRFLAG_NO_NORMVAL|ATTRFLAG_NO_WORSTVAL);
if (!id) {
- // "N,name" -> set all entries
- for (int j = 0; j < MAX_ATTRIBUTE_NUM; j++)
- defs[j] = vendor_attribute_args[i].val;
+ // "N,format" -> set format for all entries
+ for (i = 0; i < MAX_ATTRIBUTE_NUM; i++) {
+ if (defs[i].priority >= priority)
+ continue;
+ if (attrname[0])
+ defs[i].name = attrname;
+ defs[i].priority = priority;
+ defs[i].raw_format = format;
+ defs[i].flags = flags;
+ strcpy(defs[i].byteorder, byteorder);
+ }
+ }
+ else if (defs[id].priority <= priority) {
+ // "id,format[,name]"
+ if (attrname[0])
+ defs[id].name = attrname;
+ defs[id].raw_format = format;
+ defs[id].priority = priority;
+ defs[id].flags = flags;
+ strcpy(defs[id].byteorder, byteorder);
}
- else
- // "attr,name"
- defs[id] = vendor_attribute_args[i].val;
- return 0;
+ return true;
}
+
// Return a multiline string containing a list of valid arguments for
// parse_attribute_def(). The strings are preceeded by tabs and followed
// (except for the last) by newlines.
std::string create_vendor_attribute_arg_list()
{
std::string s;
- for (unsigned i = 0; i < num_vendor_attribute_args; i++) {
- if (i > 0)
- s += '\n';
- if (!vendor_attribute_args[i].id)
- s += "\tN,";
- else
- s += strprintf("\t%d,", vendor_attribute_args[i].id);
- s += vendor_attribute_args[i].name;
- }
+ unsigned i;
+ for (i = 0; i < num_format_names; i++)
+ s += strprintf("%s\tN,%s[:012345rvwz][,ATTR_NAME]",
+ (i>0 ? "\n" : ""), format_names[i].name);
+ for (i = 0; i < num_old_vendor_opts; i++)
+ s += strprintf("\n\t%s", map_old_vendor_opts[i][0]);
return s;
}
return;
}
-// Invalidate serial number and adjust checksum in IDENTIFY data
-static void invalidate_serno(ata_identify_device * id){
+// Invalidate serial number and WWN and adjust checksum in IDENTIFY data
+static void invalidate_serno(ata_identify_device * id)
+{
unsigned char sum = 0;
- for (unsigned i = 0; i < sizeof(id->serial_no); i++) {
+ unsigned i;
+ for (i = 0; i < sizeof(id->serial_no); i++) {
sum += id->serial_no[i]; sum -= id->serial_no[i] = 'X';
}
+ unsigned char * b = (unsigned char *)id;
+ for (i = 2*108; i < 2*112; i++) { // words108-111: WWN
+ sum += b[i]; sum -= b[i] = 0x00;
+ }
+
#ifndef __NetBSD__
bool must_swap = !!isbigendian();
if (must_swap)
sprintf(buf, "0x%02x", r.val()); return buf;
}
-void print_regs(const char * prefix, const ata_in_regs & r, const char * suffix = "\n")
+static void print_regs(const char * prefix, const ata_in_regs & r, const char * suffix = "\n")
{
char bufs[7][4+1+13];
pout("%s FR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, CMD=%s%s", prefix,
preg(r.command, bufs[6]), suffix);
}
-void print_regs(const char * prefix, const ata_out_regs & r, const char * suffix = "\n")
+static void print_regs(const char * prefix, const ata_out_regs & r, const char * suffix = "\n")
{
char bufs[7][4+1+13];
pout("%sERR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, STS=%s%s", prefix,
static void prettyprint(const unsigned char *p, const char *name){
pout("\n===== [%s] DATA START (BASE-16) =====\n", name);
for (int i=0; i<512; i+=16, p+=16)
+#define P(n) (isprint((int)(p[n]))?(int)(p[n]):'.')
// print complete line to avoid slow tty output and extra lines in syslog.
pout("%03d-%03d: %02x %02x %02x %02x %02x %02x %02x %02x "
- "%02x %02x %02x %02x %02x %02x %02x %02x\n",
+ "%02x %02x %02x %02x %02x %02x %02x %02x"
+ " |%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c|"
+ "%c",
i, i+16-1,
p[ 0], p[ 1], p[ 2], p[ 3], p[ 4], p[ 5], p[ 6], p[ 7],
- p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15]);
+ p[ 8], p[ 9], p[10], p[11], p[12], p[13], p[14], p[15],
+ P( 0), P( 1), P( 2), P( 3), P( 4), P( 5), P( 6), P( 7),
+ P( 8), P( 9), P(10), P(11), P(12), P(13), P(14), P(15),
+ '\n');
+#undef P
pout("===== [%s] DATA END (512 Bytes) =====\n\n", name);
}
int sendsdata=(command==WRITE_LOG);
// If reporting is enabled, say what the command will be before it's executed
- if (con->reportataioctl){
+ if (ata_debugmode) {
// conditional is true for commands that use parameters
int usesparam=(command==READ_LOG ||
command==AUTO_OFFLINE ||
// if requested, pretty-print the input data structure
- if (con->reportataioctl>1 && sendsdata)
+ if (ata_debugmode > 1 && sendsdata)
//pout("REPORT-IOCTL: Device=%s Command=%s\n", device->get_dev_name(), commandstrings[command]);
prettyprint((unsigned char *)data, commandstrings[command]);
pout("Unrecognized command %d in smartcommandhandler()\n"
"Please contact " PACKAGE_BUGREPORT "\n", command);
device->set_err(ENOSYS);
- errno = ENOSYS;
return -1;
}
- if (con->reportataioctl)
+ if (ata_debugmode)
print_regs(" Input: ", in.in_regs,
(in.direction==ata_cmd_in::data_in ? " IN\n":
in.direction==ata_cmd_in::data_out ? " OUT\n":"\n"));
ata_cmd_out out;
bool ok = device->ata_pass_through(in, out);
- if (con->reportataioctl && out.out_regs.is_set())
+ if (ata_debugmode && out.out_regs.is_set())
print_regs(" Output: ", out.out_regs);
if (ok) switch (command) {
retval = 0;
break;
case CHECK_POWER_MODE:
- data[0] = out.out_regs.sector_count;
- retval = 0;
+ if (out.out_regs.sector_count.is_set()) {
+ data[0] = out.out_regs.sector_count;
+ retval = 0;
+ }
+ else {
+ pout("CHECK POWER MODE: incomplete response, ATA output registers missing\n");
+ device->set_err(ENOSYS);
+ retval = -1;
+ }
break;
case STATUS_CHECK:
// Cyl low and Cyl high unchanged means "Good SMART status"
retval = 1;
else if (out.out_regs.lba_mid == SMART_CYL_LOW) {
retval = 0;
- if (con->reportataioctl)
+ if (ata_debugmode)
pout("SMART STATUS RETURN: half healthy response sequence, "
"probable SAT/USB truncation\n");
} else if (out.out_regs.lba_mid == SRET_STATUS_MID_EXCEEDED) {
retval = 1;
- if (con->reportataioctl)
+ if (ata_debugmode)
pout("SMART STATUS RETURN: half unhealthy response sequence, "
"probable SAT/USB truncation\n");
- } else {
+ }
+ else if (!out.out_regs.is_set()) {
+ pout("SMART STATUS RETURN: incomplete response, ATA output registers missing\n");
+ device->set_err(ENOSYS);
+ retval = -1;
+ }
+ else {
// We haven't gotten output that makes sense; print out some debugging info
- pout("Error SMART Status command failed\n"
- "Please get assistance from %s\n", PACKAGE_HOMEPAGE);
- errno = EIO;
+ pout("Error SMART Status command failed\n");
+ pout("Please get assistance from %s\n", PACKAGE_HOMEPAGE);
+ pout("Register values returned from SMART Status command are:\n");
+ print_regs(" ", out.out_regs);
+ device->set_err(EIO);
retval = -1;
}
break;
}
// If requested, invalidate serial number before any printing is done
- if ((command == IDENTIFY || command == PIDENTIFY) && !retval && con->dont_print_serial)
+ if ((command == IDENTIFY || command == PIDENTIFY) && !retval && dont_print_serial_number)
invalidate_serno((ata_identify_device *)data);
// If reporting is enabled, say what output was produced by the command
- if (con->reportataioctl){
+ if (ata_debugmode) {
if (device->get_errno())
pout("REPORT-IOCTL: Device=%s Command=%s returned %d errno=%d [%s]\n",
device->get_dev_name(), commandstrings[command], retval,
device->get_dev_name(), commandstrings[command], retval);
// if requested, pretty-print the output data structure
- if (con->reportataioctl>1 && getsdata) {
+ if (ata_debugmode > 1 && getsdata) {
if (command==CHECK_POWER_MODE)
pout("Sector Count Register (BASE-16): %02x\n", (unsigned char)(*data));
else
}
}
- errno = device->get_errno(); // TODO: Callers should not call syserror()
return retval;
}
-// Get number of sectors from IDENTIFY sector. If the drive doesn't
-// support LBA addressing or has no user writable sectors
-// (eg, CDROM or DVD) then routine returns zero.
-uint64_t get_num_sectors(const ata_identify_device * drive)
+// Get capacity and sector sizes from IDENTIFY data
+void ata_get_size_info(const ata_identify_device * id, ata_size_info & sizes)
{
- unsigned short command_set_2 = drive->command_set_2;
- unsigned short capabilities_0 = drive->words047_079[49-47];
- unsigned short sects_16 = drive->words047_079[60-47];
- unsigned short sects_32 = drive->words047_079[61-47];
- unsigned short lba_16 = drive->words088_255[100-88];
- unsigned short lba_32 = drive->words088_255[101-88];
- unsigned short lba_48 = drive->words088_255[102-88];
- unsigned short lba_64 = drive->words088_255[103-88];
+ sizes.sectors = sizes.capacity = 0;
+ sizes.log_sector_size = sizes.phy_sector_size = 0;
+ sizes.log_sector_offset = 0;
+
+ // Return if no LBA support
+ if (!(id->words047_079[49-47] & 0x0200))
+ return;
+
+ // Determine 28-bit LBA capacity
+ unsigned lba28 = (unsigned)id->words047_079[61-47] << 16
+ | (unsigned)id->words047_079[60-47] ;
+
+ // Determine 48-bit LBA capacity if supported
+ uint64_t lba48 = 0;
+ if ((id->command_set_2 & 0xc400) == 0x4400)
+ lba48 = (uint64_t)id->words088_255[103-88] << 48
+ | (uint64_t)id->words088_255[102-88] << 32
+ | (uint64_t)id->words088_255[101-88] << 16
+ | (uint64_t)id->words088_255[100-88] ;
- // LBA support?
- if (!(capabilities_0 & 0x0200))
- return 0; // No
+ // Return if capacity unknown (ATAPI CD/DVD)
+ if (!(lba28 || lba48))
+ return;
+
+ // Determine sector sizes
+ sizes.log_sector_size = sizes.phy_sector_size = 512;
- // if drive supports LBA addressing, determine 32-bit LBA capacity
- uint64_t lba32 = (unsigned int)sects_32 << 16 |
- (unsigned int)sects_16 << 0 ;
+ unsigned short word106 = id->words088_255[106-88];
+ if ((word106 & 0xc000) == 0x4000) {
+ // Long Logical/Physical Sectors (LLS/LPS) ?
+ if (word106 & 0x1000)
+ // Logical sector size is specified in 16-bit words
+ sizes.log_sector_size = sizes.phy_sector_size =
+ ((id->words088_255[118-88] << 16) | id->words088_255[117-88]) << 1;
- uint64_t lba64 = 0;
- // if drive supports 48-bit addressing, determine THAT capacity
- if ((command_set_2 & 0xc000) == 0x4000 && (command_set_2 & 0x0400))
- lba64 = (uint64_t)lba_64 << 48 |
- (uint64_t)lba_48 << 32 |
- (uint64_t)lba_32 << 16 |
- (uint64_t)lba_16 << 0 ;
+ if (word106 & 0x2000)
+ // Physical sector size is multiple of logical sector size
+ sizes.phy_sector_size <<= (word106 & 0x0f);
- // return the larger of the two possible capacities
- return (lba32 > lba64 ? lba32 : lba64);
+ unsigned short word209 = id->words088_255[209-88];
+ if ((word209 & 0xc000) == 0x4000)
+ sizes.log_sector_offset = (word209 & 0x3fff) * sizes.log_sector_size;
+ }
+
+ // Some early 4KiB LLS disks (Samsung N3U-3) return bogus lba28 value
+ if (lba48 >= lba28 || (lba48 && sizes.log_sector_size > 512))
+ sizes.sectors = lba48;
+ else
+ sizes.sectors = lba28;
+
+ sizes.capacity = sizes.sectors * sizes.log_sector_size;
}
// This function computes the checksum of a single disk sector (512
}
// Convenience function for formatting strings from ata_identify_device
-void format_ata_string(char * out, const char * in, int n, bool fix_swap)
+void ata_format_id_string(char * out, const unsigned char * in, int n)
{
- bool must_swap = !fix_swap;
+ bool must_swap = true;
#ifdef __NetBSD__
/* NetBSD kernel delivers IDENTIFY data in host byte order (but all else is LE) */
+ // TODO: Handle NetBSD case in os_netbsd.cpp
if (isbigendian())
must_swap = !must_swap;
#endif
char tmp[65];
n = n > 64 ? 64 : n;
if (!must_swap)
- strncpy(tmp, in, n);
+ strncpy(tmp, (const char *)in, n);
else
- swapbytes(tmp, in, n);
+ swapbytes(tmp, (const char *)in, n);
tmp[n] = '\0';
trim(out, tmp);
}
return (int)result;
}
-
-
-
// Reads current Device Identity info (512 bytes) into buf. Returns 0
// if all OK. Returns -1 if no ATA Device identity can be
// established. Returns >0 if Device is ATA Packet Device (not SMART
// capable). The value of the integer helps identify the type of
// Packet device, which is useful so that the user can connect the
// formal device number with whatever object is inside their computer.
-int ataReadHDIdentity (ata_device * device, struct ata_identify_device *buf){
+int ata_read_identity(ata_device * device, ata_identify_device * buf, bool fix_swapped_id)
+{
unsigned short *rawshort=(unsigned short *)buf;
unsigned char *rawbyte =(unsigned char *)buf;
// See if device responds either to IDENTIFY DEVICE or IDENTIFY
// PACKET DEVICE
+ bool packet = false;
if ((smartcommandhandler(device, IDENTIFY, 0, (char *)buf))){
if (smartcommandhandler(device, PIDENTIFY, 0, (char *)buf)){
return -1;
}
+ packet = true;
+ }
+
+ unsigned i;
+ if (fix_swapped_id) {
+ // Swap ID strings
+ for (i = 0; i < sizeof(buf->serial_no)-1; i += 2)
+ swap2((char *)(buf->serial_no+i));
+ for (i = 0; i < sizeof(buf->fw_rev)-1; i += 2)
+ swap2((char *)(buf->fw_rev+i));
+ for (i = 0; i < sizeof(buf->model)-1; i += 2)
+ swap2((char *)(buf->model+i));
}
#ifndef __NetBSD__
// if machine is big-endian, swap byte order as needed
// NetBSD kernel delivers IDENTIFY data in host byte order
+ // TODO: Handle NetBSD case in os_netbsd.cpp
if (isbigendian()){
- int i;
// swap various capability words that are needed
for (i=0; i<33; i++)
// If there is a checksum there, validate it
if ((rawshort[255] & 0x00ff) == 0x00a5 && checksum(rawbyte))
checksumwarning("Drive Identity Structure");
-
+
+ // AT Attachment 8 - ATA/ATAPI Command Set (ATA8-ACS)
+ // T13/1699-D Revision 6a (Final Draft), September 6, 2008.
+ // Sections 7.16.7 and 7.17.6:
+ //
+ // Word 0 of IDENTIFY DEVICE data:
+ // Bit 15 = 0 : ATA device
+ //
+ // Word 0 of IDENTIFY PACKET DEVICE data:
+ // Bits 15:14 = 10b : ATAPI device
+ // Bits 15:14 = 11b : Reserved
+ // Bits 12:8 : Device type (SPC-4, e.g 0x05 = CD/DVD)
+
+ // CF+ and CompactFlash Specification Revision 4.0, May 24, 2006.
+ // Section 6.2.1.6:
+ //
+ // Word 0 of IDENTIFY DEVICE data:
+ // 848Ah = Signature for CompactFlash Storage Card
+ // 044Ah = Alternate value turns on ATA device while preserving all retired bits
+ // 0040h = Alternate value turns on ATA device while zeroing all retired bits
+
+ // Assume ATA if IDENTIFY DEVICE returns CompactFlash Signature
+ if (!packet && rawbyte[1] == 0x84 && rawbyte[0] == 0x8a)
+ return 0;
+
// If this is a PACKET DEVICE, return device type
if (rawbyte[1] & 0x80)
return 1+(rawbyte[1] & 0x1f);
// the version number. See notes above.
int ataVersionInfo(const char ** description, const ata_identify_device * drive, unsigned short * minor)
{
- // check that arrays at the top of this file are defined
- // consistently
- if (sizeof(minor_str) != sizeof(char *)*(1+MINOR_MAX)){
- pout("Internal error in ataVersionInfo(). minor_str[] size %d\n"
- "is not consistent with value of MINOR_MAX+1 = %d\n",
- (int)(sizeof(minor_str)/sizeof(char *)), MINOR_MAX+1);
- fflush(NULL);
- abort();
- }
- if (sizeof(actual_ver) != sizeof(int)*(1+MINOR_MAX)){
- pout("Internal error in ataVersionInfo(). actual_ver[] size %d\n"
- "is not consistent with value of MINOR_MAX = %d\n",
- (int)(sizeof(actual_ver)/sizeof(int)), MINOR_MAX+1);
- fflush(NULL);
- abort();
- }
-
// get major and minor ATA revision numbers
unsigned short major = drive->major_rev_num;
*minor=drive->minor_rev_num;
// First check if device has ANY ATA version information in it
if (major==NOVAL_0 || major==NOVAL_1) {
*description=NULL;
- return -1;
+ return 0; // No info found
}
// The minor revision number has more information - try there first
}
}
- // Try new ATA-8 minor revision numbers (Table 31 of T13/1699-D Revision 6)
+ // Try new ATA-8 ACS minor revision numbers.
+ // Table 55 of T13/2015-D Revision 4a (ACS-2), December 9, 2010.
// (not in actual_ver/minor_str to avoid large sparse tables)
const char *desc;
switch (*minor) {
case 0x0027: desc = "ATA-8-ACS revision 3c"; break;
case 0x0028: desc = "ATA-8-ACS revision 6"; break;
case 0x0029: desc = "ATA-8-ACS revision 4"; break;
+ case 0x0031: desc = "ACS-2 revision 2"; break;
case 0x0033: desc = "ATA-8-ACS revision 3e"; break;
case 0x0039: desc = "ATA-8-ACS revision 4c"; break;
case 0x0042: desc = "ATA-8-ACS revision 3f"; break;
case 0x0052: desc = "ATA-8-ACS revision 3b"; break;
case 0x0107: desc = "ATA-8-ACS revision 2d"; break;
+ case 0x0110: desc = "ACS-2 revision 3"; break;
default: desc = 0; break;
}
if (desc) {
return i;
}
+// Get World Wide Name (WWN) fields.
+// Return NAA field or -1 if WWN is unsupported.
+// Table 34 of T13/1699-D Revision 6a (ATA8-ACS), September 6, 2008.
+// (WWN was introduced in ATA/ATAPI-7 and is mandatory since ATA8-ACS Revision 3b)
+int ata_get_wwn(const ata_identify_device * id, unsigned & oui, uint64_t & unique_id)
+{
+ // Don't use word 84 to be compatible with some older ATA-7 disks
+ unsigned short word087 = id->csf_default;
+ if ((word087 & 0xc100) != 0x4100)
+ return -1; // word not valid or WWN support bit 8 not set
+
+ unsigned short word108 = id->words088_255[108-88];
+ unsigned short word109 = id->words088_255[109-88];
+ unsigned short word110 = id->words088_255[110-88];
+ unsigned short word111 = id->words088_255[111-88];
+
+ oui = ((word108 & 0x0fff) << 12) | (word109 >> 4);
+ unique_id = ((uint64_t)(word109 & 0xf) << 32)
+ | (unsigned)((word110 << 16) | word111);
+ return (word108 >> 12);
+}
+
// returns 1 if SMART supported, 0 if SMART unsupported, -1 if can't tell
int ataSmartSupport(const ata_identify_device * drive)
{
int ataReadSmartValues(ata_device * device, struct ata_smart_values *data){
if (smartcommandhandler(device, READ_VALUES, 0, (char *)data)){
- syserror("Error SMART Values Read failed");
+ pout("Error SMART Values Read failed: %s\n", device->get_errmsg());
return -1;
}
// get data from device
if (smartcommandhandler(device, READ_LOG, 0x06, (char *)data)){
- syserror("Error SMART Error Self-Test Log Read failed");
+ pout("Error SMART Error Self-Test Log Read failed: %s\n", device->get_errmsg());
return -1;
}
// get data from device
if (smartcommandhandler(device, READ_LOG, 0x09, (char *)data)){
- syserror("Error SMART Read Selective Self-Test Log failed");
+ pout("Error SMART Read Selective Self-Test Log failed: %s\n", device->get_errmsg());
return -1;
}
// Writes the selective self-test log (log #9)
int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_args & args,
- const ata_smart_values * sv, uint64_t num_sectors)
+ const ata_smart_values * sv, uint64_t num_sectors,
+ const ata_selective_selftest_args * prev_args)
{
// Disk size must be known
if (!num_sectors) {
break;
}
}
+
+ if ( (mode == SEL_REDO || mode == SEL_NEXT)
+ && prev_args && i < prev_args->num_spans
+ && !data->span[i].start && !data->span[i].end) {
+ // Some drives do not preserve the selective self-test log accross
+ // power-cyles. If old span on drive is cleared use span provided
+ // by caller. This is used by smartd (first span only).
+ data->span[i].start = prev_args->span[i].start;
+ data->span[i].end = prev_args->span[i].end;
+ }
+
switch (mode) {
case SEL_RANGE: // -t select,START-END
break;
// swap endian order if needed
if (isbigendian()){
swap2((char *)&(data->logversion));
- for (int i=0;i<5;i++){
- swap8((char *)&(data->span[i].start));
- swap8((char *)&(data->span[i].end));
+ for (int b = 0; b < 5; b++) {
+ swap8((char *)&(data->span[b].start));
+ swap8((char *)&(data->span[b].end));
}
swap8((char *)&(data->currentlba));
swap2((char *)&(data->currentspan));
// write new selective self-test log
if (smartcommandhandler(device, WRITE_LOG, 0x09, (char *)data)){
- syserror("Error Write Selective Self-Test Log failed");
+ pout("Error Write Selective Self-Test Log failed: %s\n", device->get_errmsg());
return -3;
}
// get data from device
if (smartcommandhandler(device, READ_LOG, 0x01, (char *)data)){
- syserror("Error SMART Error Log Read failed");
+ pout("Error SMART Error Log Read failed: %s\n", device->get_errmsg());
return -1;
}
// get data from device
if (smartcommandhandler(device, READ_THRESHOLDS, 0, (char *)data)){
- syserror("Error SMART Thresholds Read failed");
+ pout("Error SMART Thresholds Read failed: %s\n", device->get_errmsg());
return -1;
}
int ataEnableSmart (ata_device * device ){
if (smartcommandhandler(device, ENABLE, 0, NULL)){
- syserror("Error SMART Enable failed");
+ pout("Error SMART Enable failed: %s\n", device->get_errmsg());
return -1;
}
return 0;
int ataDisableSmart (ata_device * device ){
if (smartcommandhandler(device, DISABLE, 0, NULL)){
- syserror("Error SMART Disable failed");
+ pout("Error SMART Disable failed: %s\n", device->get_errmsg());
return -1;
}
return 0;
int ataEnableAutoSave(ata_device * device){
if (smartcommandhandler(device, AUTOSAVE, 241, NULL)){
- syserror("Error SMART Enable Auto-save failed");
+ pout("Error SMART Enable Auto-save failed: %s\n", device->get_errmsg());
return -1;
}
return 0;
int ataDisableAutoSave(ata_device * device){
if (smartcommandhandler(device, AUTOSAVE, 0, NULL)){
- syserror("Error SMART Disable Auto-save failed");
+ pout("Error SMART Disable Auto-save failed: %s\n", device->get_errmsg());
return -1;
}
return 0;
/* timer hard coded to 4 hours */
if (smartcommandhandler(device, AUTO_OFFLINE, 248, NULL)){
- syserror("Error SMART Enable Automatic Offline failed");
+ pout("Error SMART Enable Automatic Offline failed: %s\n", device->get_errmsg());
return -1;
}
return 0;
int ataDisableAutoOffline (ata_device * device){
if (smartcommandhandler(device, AUTO_OFFLINE, 0, NULL)){
- syserror("Error SMART Disable Automatic Offline failed");
+ pout("Error SMART Disable Automatic Offline failed: %s\n", device->get_errmsg());
return -1;
}
return 0;
const ata_smart_values * sv, uint64_t num_sectors)
{
char cmdmsg[128]; const char *type, *captive;
- int errornum, cap, retval, select=0;
+ int cap, retval, select=0;
// Boolean, if set, says test is captive
cap=testtype & CAPTIVE_MASK;
else if ((select=(testtype==SELECTIVE_SELF_TEST || testtype==SELECTIVE_CAPTIVE_SELF_TEST)))
type="Selective self-test";
else
- type="[Unrecognized] self-test";
+ type = 0;
// If doing a selective self-test, first use WRITE_LOG to write the
// selective self-test log.
// Print ouf message that we are sending the command to test
if (testtype==ABORT_SELF_TEST)
sprintf(cmdmsg,"Abort SMART off-line mode self-test routine");
+ else if (!type)
+ sprintf(cmdmsg, "SMART EXECUTE OFF-LINE IMMEDIATE subcommand 0x%02x", testtype);
else
sprintf(cmdmsg,"Execute SMART %s routine immediately in %s mode",type,captive);
pout("Sending command: \"%s\".\n",cmdmsg);
}
// Now send the command to test
- errornum=smartcommandhandler(device, IMMEDIATE_OFFLINE, testtype, NULL);
-
- if (errornum && !(cap && errno==EIO)){
- char errormsg[128];
- sprintf(errormsg,"Command \"%s\" failed",cmdmsg);
- syserror(errormsg);
- pout("\n");
- return -1;
+ if (smartcommandhandler(device, IMMEDIATE_OFFLINE, testtype, NULL)) {
+ if (!(cap && device->get_errno() == EIO)) {
+ pout("Command \"%s\" failed: %s\n", cmdmsg, device->get_errmsg());
+ return -1;
+ }
}
// Since the command succeeded, tell user
if (testtype==ABORT_SELF_TEST)
pout("Self-testing aborted!\n");
- else
- pout("Drive command \"%s\" successful.\nTesting has begun.\n",cmdmsg);
+ else {
+ pout("Drive command \"%s\" successful.\n", cmdmsg);
+ if (type)
+ pout("Testing has begun.\n");
+ }
return 0;
}
return data->offline_data_collection_capability & 0x40;
}
-
-
-// Loop over all valid attributes. If they are prefailure attributes
-// and are at or below the threshold value, then return the ID of the
-// first failing attribute found. Return 0 if all prefailure
-// attributes are in bounds. The spec says "Bit 0
-// -Pre-failure/advisory - If the value of this bit equals zero, an
-// attribute value less than or equal to its corresponding attribute
-// threshold indicates an advisory condition where the usage or age of
-// the device has exceeded its intended design life period. If the
-// value of this bit equals one, an atribute value less than or equal
-// to its corresponding attribute threshold indicates a pre-failure
-// condition where imminent loss of data is being predicted."
-
-
-// onlyfailed=0 : are or were any age or prefailure attributes <= threshold
-// onlyfailed=1: are any prefailure attributes <= threshold now
-int ataCheckSmart(const ata_smart_values * data,
- const ata_smart_thresholds_pvt * thresholds,
- int onlyfailed)
-{
- // loop over all attributes
- for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++){
-
- // pointers to disk's values and vendor's thresholds
- const ata_smart_attribute * disk = data->vendor_attributes+i;
- const ata_smart_threshold_entry * thre = thresholds->thres_entries+i;
-
- // consider only valid attributes
- if (disk->id && thre->id){
- int failednow,failedever;
-
- failednow =disk->current <= thre->threshold;
- failedever=disk->worst <= thre->threshold;
-
- if (!onlyfailed && failedever)
- return disk->id;
-
- if (onlyfailed && failednow && ATTRIBUTE_FLAGS_PREFAILURE(disk->flags))
- return disk->id;
+// Get attribute state
+ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr,
+ int attridx,
+ const ata_smart_threshold_entry * thresholds,
+ const ata_vendor_attr_defs & defs,
+ unsigned char * threshval /* = 0 */)
+{
+ if (!attr.id)
+ return ATTRSTATE_NON_EXISTING;
+
+ // Normalized values (current,worst,threshold) not valid
+ // if specified by '-v' option.
+ // (Some SSD disks uses these bytes to store raw value).
+ if (defs[attr.id].flags & ATTRFLAG_NO_NORMVAL)
+ return ATTRSTATE_NO_NORMVAL;
+
+ // Normally threshold is at same index as attribute
+ int i = attridx;
+ if (thresholds[i].id != attr.id) {
+ // Find threshold id in table
+ for (i = 0; thresholds[i].id != attr.id; ) {
+ if (++i >= NUMBER_ATA_SMART_ATTRIBUTES)
+ // Threshold id missing or thresholds cannot be read
+ return ATTRSTATE_NO_THRESHOLD;
}
}
- return 0;
-}
+ unsigned char threshold = thresholds[i].threshold;
+ // Return threshold if requested
+ if (threshval)
+ *threshval = threshold;
+ // Don't report a failed attribute if its threshold is 0.
+ // ATA-3 (X3T13/2008D Revision 7b) declares 0x00 as the "always passing"
+ // threshold (Later ATA versions declare all thresholds as "obsolete").
+ // In practice, threshold value 0 is often used for usage attributes.
+ if (!threshold)
+ return ATTRSTATE_OK;
-// This checks the n'th attribute in the attribute list, NOT the
-// attribute with id==n. If the attribute does not exist, or the
-// attribute is > threshold, then returns zero. If the attribute is
-// <= threshold (failing) then we the attribute number if it is a
-// prefail attribute. Else we return minus the attribute number if it
-// is a usage attribute.
-int ataCheckAttribute(const ata_smart_values * data,
- const ata_smart_thresholds_pvt * thresholds,
- int n)
-{
- if (n<0 || n>=NUMBER_ATA_SMART_ATTRIBUTES || !data || !thresholds)
- return 0;
-
- // pointers to disk's values and vendor's thresholds
- const ata_smart_attribute * disk = data->vendor_attributes+n;
- const ata_smart_threshold_entry * thre = thresholds->thres_entries+n;
+ // Failed now if current value is below threshold
+ if (attr.current <= threshold)
+ return ATTRSTATE_FAILED_NOW;
- if (!disk || !thre)
- return 0;
-
- // consider only valid attributes, check for failure
- if (!disk->id || !thre->id || (disk->id != thre->id) || disk->current> thre->threshold)
- return 0;
-
- // We have found a failed attribute. Return positive or negative?
- if (ATTRIBUTE_FLAGS_PREFAILURE(disk->flags))
- return disk->id;
- else
- return -1*(disk->id);
-}
+ // Failed in the past if worst value is below threshold
+ if (!(defs[attr.id].flags & ATTRFLAG_NO_WORSTVAL) && attr.worst <= threshold)
+ return ATTRSTATE_FAILED_PAST;
+ return ATTRSTATE_OK;
+}
-// Print temperature value and Min/Max value if present
-static void ataPrintTemperatureValue(char *out, const unsigned char *raw, const unsigned *word)
+// Get default raw value print format
+static ata_attr_raw_format get_default_raw_format(unsigned char id)
{
- out+=sprintf(out, "%u", word[0]);
- if (!word[1] && !word[2])
- return; // No Min/Max
+ switch (id) {
+ case 3: // Spin-up time
+ return RAWFMT_RAW16_OPT_AVG16;
- unsigned lo = ~0, hi = ~0;
- if (!raw[3]) {
- // 00 HH 00 LL 00 TT (IBM)
- hi = word[2]; lo = word[1];
+ case 5: // Reallocated sector count
+ case 196: // Reallocated event count
+ return RAWFMT_RAW16_OPT_RAW16;
+
+ case 190: // Temperature
+ case 194:
+ return RAWFMT_TEMPMINMAX;
+
+ default:
+ return RAWFMT_RAW48;
}
- else if (!word[2]) {
- // 00 00 HH LL 00 TT (Maxtor)
- hi = raw[3]; lo = raw[2];
+}
+
+// Get attribute raw value.
+uint64_t ata_get_attr_raw_value(const ata_smart_attribute & attr,
+ const ata_vendor_attr_defs & defs)
+{
+ const ata_vendor_attr_defs::entry & def = defs[attr.id];
+
+ // Use default byteorder if not specified
+ const char * byteorder = def.byteorder;
+ if (!*byteorder) {
+ switch (def.raw_format) {
+ case RAWFMT_RAW64:
+ case RAWFMT_HEX64:
+ byteorder = "543210wv"; break;
+ case RAWFMT_RAW24_DIV_RAW32:
+ case RAWFMT_MSEC24_HOUR32:
+ byteorder = "r543210"; break;
+ default:
+ byteorder = "543210"; break;
+ }
}
- if (lo > hi) {
- unsigned t = lo; lo = hi; hi = t;
+
+ // Build 64-bit value from selected bytes
+ uint64_t rawvalue = 0;
+ for (int i = 0; byteorder[i]; i++) {
+ unsigned char b;
+ switch (byteorder[i]) {
+ case '0': b = attr.raw[0]; break;
+ case '1': b = attr.raw[1]; break;
+ case '2': b = attr.raw[2]; break;
+ case '3': b = attr.raw[3]; break;
+ case '4': b = attr.raw[4]; break;
+ case '5': b = attr.raw[5]; break;
+ case 'r': b = attr.reserv; break;
+ case 'v': b = attr.current; break;
+ case 'w': b = attr.worst; break;
+ default : b = 0; break;
+ }
+ rawvalue <<= 8; rawvalue |= b;
}
- if (lo <= word[0] && word[0] <= hi)
- sprintf(out, " (Lifetime Min/Max %u/%u)", lo, hi);
- else
- sprintf(out, " (%u %u %u %u)", raw[5], raw[4], raw[3], raw[2]);
-}
+ return rawvalue;
+}
-// This routine prints the raw value of an attribute as a text string
-// into out. It also returns this 48-bit number as a long long. The
-// array defs[] contains non-zero values if particular attributes have
-// non-default interpretations.
-int64_t ataPrintSmartAttribRawValue(char *out,
- const ata_smart_attribute * attribute,
- const unsigned char * defs){
- int64_t rawvalue;
+// Format attribute raw value.
+std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
+ const ata_vendor_attr_defs & defs)
+{
+ // Get 48 bit or 64 bit raw value
+ uint64_t rawvalue = ata_get_attr_raw_value(attr, defs);
+
+ // Split into bytes and words
+ unsigned char raw[6];
+ raw[0] = (unsigned char) rawvalue;
+ raw[1] = (unsigned char)(rawvalue >> 8);
+ raw[2] = (unsigned char)(rawvalue >> 16);
+ raw[3] = (unsigned char)(rawvalue >> 24);
+ raw[4] = (unsigned char)(rawvalue >> 32);
+ raw[5] = (unsigned char)(rawvalue >> 40);
unsigned word[3];
- int j;
- unsigned char select;
-
- // convert the six individual bytes to a long long (8 byte) integer.
- // This is the value that we'll eventually return.
- rawvalue = 0;
- for (j=0; j<6; j++) {
- // This looks a bit roundabout, but is necessary. Don't
- // succumb to the temptation to use raw[j]<<(8*j) since under
- // the normal rules this will be promoted to the native type.
- // On a 32 bit machine this might then overflow.
- int64_t temp;
- temp = attribute->raw[j];
- temp <<= 8*j;
- rawvalue |= temp;
- }
-
- // convert quantities to three two-byte words
- for (j=0; j<3; j++){
- word[j] = attribute->raw[2*j+1];
- word[j] <<= 8;
- word[j] |= attribute->raw[2*j];
- }
-
- // if no data array, Attributes have default interpretations
- if (defs)
- select=defs[attribute->id];
- else
- select=0;
-
- // Print six one-byte quantities.
- if (select==253){
- for (j=0; j<5; j++)
- out+=sprintf(out, "%d ", attribute->raw[5-j]);
- out+=sprintf(out, "%d ", attribute->raw[0]);
- return rawvalue;
- }
-
- // Print three two-byte quantities
- if (select==254){
- out+=sprintf(out, "%d %d %d", word[2], word[1], word[0]);
- return rawvalue;
- }
-
- // Print one six-byte quantity
- if (select==255){
- out+=sprintf(out, "%"PRIu64, rawvalue);
- return rawvalue;
- }
+ word[0] = raw[0] | (raw[1] << 8);
+ word[1] = raw[2] | (raw[3] << 8);
+ word[2] = raw[4] | (raw[5] << 8);
- // This switch statement is where we handle Raw attributes
- // that are stored in an unusual vendor-specific format,
- switch (attribute->id){
- // Spin-up time
- case 3:
- out+=sprintf(out, "%d", word[0]);
- // if second nonzero then it stores the average spin-up time
- if (word[1])
- out+=sprintf(out, " (Average %d)", word[1]);
+ // Get print format
+ ata_attr_raw_format format = defs[attr.id].raw_format;
+ if (format == RAWFMT_DEFAULT)
+ format = get_default_raw_format(attr.id);
+
+ // Print
+ std::string s;
+ switch (format) {
+ case RAWFMT_RAW8:
+ s = strprintf("%d %d %d %d %d %d",
+ raw[5], raw[4], raw[3], raw[2], raw[1], raw[0]);
break;
- // reallocated sector count
- case 5:
- out+=sprintf(out, "%u", word[0]);
+
+ case RAWFMT_RAW16:
+ s = strprintf("%u %u %u", word[2], word[1], word[0]);
+ break;
+
+ case RAWFMT_RAW48:
+ case RAWFMT_RAW64:
+ s = strprintf("%"PRIu64, rawvalue);
+ break;
+
+ case RAWFMT_HEX48:
+ s = strprintf("0x%012"PRIx64, rawvalue);
+ break;
+
+ case RAWFMT_HEX64:
+ s = strprintf("0x%016"PRIx64, rawvalue);
+ break;
+
+ case RAWFMT_RAW16_OPT_RAW16:
+ s = strprintf("%u", word[0]);
if (word[1] || word[2])
- out+=sprintf(out, " (%u, %u)", word[2], word[1]);
+ s += strprintf(" (%u, %u)", word[2], word[1]);
break;
- // Power on time
- case 9:
- if (select==1){
+
+ case RAWFMT_RAW16_OPT_AVG16:
+ s = strprintf("%u", word[0]);
+ if (word[1])
+ s += strprintf(" (Average %u)", word[1]);
+ break;
+
+ case RAWFMT_RAW24_DIV_RAW24:
+ s = strprintf("%u/%u",
+ (unsigned)(rawvalue >> 24), (unsigned)(rawvalue & 0x00ffffffULL));
+ break;
+
+ case RAWFMT_RAW24_DIV_RAW32:
+ s = strprintf("%u/%u",
+ (unsigned)(rawvalue >> 32), (unsigned)(rawvalue & 0xffffffffULL));
+ break;
+
+ case RAWFMT_MIN2HOUR:
+ {
// minutes
- int64_t temp=word[0]+(word[1]<<16);
- int64_t tmp1=temp/60;
- int64_t tmp2=temp%60;
- out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
+ int64_t temp = word[0]+(word[1]<<16);
+ int64_t tmp1 = temp/60;
+ int64_t tmp2 = temp%60;
+ s = strprintf("%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
if (word[2])
- out+=sprintf(out, " (%u)", word[2]);
+ s += strprintf(" (%u)", word[2]);
}
- else if (select==3){
+ break;
+
+ case RAWFMT_SEC2HOUR:
+ {
// seconds
- int64_t hours=rawvalue/3600;
- int64_t minutes=(rawvalue-3600*hours)/60;
- int64_t seconds=rawvalue%60;
- out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m+%02"PRIu64"s", hours, minutes, seconds);
+ int64_t hours = rawvalue/3600;
+ int64_t minutes = (rawvalue-3600*hours)/60;
+ int64_t seconds = rawvalue%60;
+ s = strprintf("%"PRIu64"h+%02"PRIu64"m+%02"PRIu64"s", hours, minutes, seconds);
}
- else if (select==4){
+ break;
+
+ case RAWFMT_HALFMIN2HOUR:
+ {
// 30-second counter
- int64_t tmp1=rawvalue/120;
- int64_t tmp2=(rawvalue-120*tmp1)/2;
- out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
+ int64_t hours = rawvalue/120;
+ int64_t minutes = (rawvalue-120*hours)/2;
+ s += strprintf("%"PRIu64"h+%02"PRIu64"m", hours, minutes);
}
- else
- // hours
- out+=sprintf(out, "%"PRIu64, rawvalue); //stored in hours
- break;
- // Temperature
- case 190:
- ataPrintTemperatureValue(out, attribute->raw, word);
break;
- // Load unload cycles
- case 193:
- if (select==1){
- // loadunload
- long load =attribute->raw[0] + (attribute->raw[1]<<8) + (attribute->raw[2]<<16);
- long unload=attribute->raw[3] + (attribute->raw[4]<<8) + (attribute->raw[5]<<16);
- out+=sprintf(out, "%lu/%lu", load, unload);
+
+ case RAWFMT_MSEC24_HOUR32:
+ {
+ // hours + milliseconds
+ unsigned hours = (unsigned)(rawvalue & 0xffffffffULL);
+ unsigned milliseconds = (unsigned)(rawvalue >> 32);
+ unsigned seconds = milliseconds / 1000;
+ s = strprintf("%uh+%02um+%02u.%03us",
+ hours, seconds / 60, seconds % 60, milliseconds % 1000);
}
- else
- // associated
- out+=sprintf(out, "%"PRIu64, rawvalue);
break;
+
+ case RAWFMT_TEMPMINMAX:
// Temperature
- case 194:
- if (select==1){
- // ten times temperature in Celsius
- int deg=word[0]/10;
- int tenths=word[0]%10;
- out+=sprintf(out, "%d.%d", deg, tenths);
+ s = strprintf("%u", word[0]);
+ if (word[1] || word[2]) {
+ unsigned lo = ~0, hi = ~0;
+ if (!raw[3]) {
+ // 00 HH 00 LL 00 TT (IBM)
+ hi = word[2]; lo = word[1];
+ }
+ else if (!word[2]) {
+ // 00 00 HH LL 00 TT (Maxtor)
+ hi = raw[3]; lo = raw[2];
+ }
+ if (lo > hi) {
+ unsigned t = lo; lo = hi; hi = t;
+ }
+ if (lo <= word[0] && word[0] <= hi)
+ s += strprintf(" (Min/Max %u/%u)", lo, hi);
+ else
+ s += strprintf(" (%d %d %d %d)", raw[5], raw[4], raw[3], raw[2]);
}
- else if (select==2)
- // unknown attribute
- out+=sprintf(out, "%"PRIu64, rawvalue);
- else
- ataPrintTemperatureValue(out, attribute->raw, word);
break;
- // reallocated event count
- case 196:
- out+=sprintf(out, "%u", word[0]);
- if (word[1] || word[2])
- out+=sprintf(out, " (%u, %u)", word[2], word[1]);
+
+ case RAWFMT_TEMP10X:
+ // ten times temperature in Celsius
+ s = strprintf("%d.%d", word[0]/10, word[0]%10);
break;
+
default:
- out+=sprintf(out, "%"PRIu64, rawvalue);
+ s = "?"; // Should not happen
+ break;
}
-
- // Return the full value
- return rawvalue;
-}
-
-// Note some attribute names appear redundant because different
-// manufacturers use different attribute IDs for an attribute with the
-// same name. The variable val should contain a non-zero value if a particular
-// attributes has a non-default interpretation.
-void ataPrintSmartAttribName(char * out, unsigned char id, const unsigned char * definitions){
- const char *name;
- unsigned char val;
-
- // If no data array, use default interpretations
- if (definitions)
- val=definitions[id];
- else
- val=0;
+ return s;
+}
- switch (id){
-
+// Attribute names shouldn't be longer than 23 chars, otherwise they break the
+// output of smartctl.
+static const char * get_default_attr_name(unsigned char id)
+{
+ switch (id) {
case 1:
- name="Raw_Read_Error_Rate";
- break;
+ return "Raw_Read_Error_Rate";
case 2:
- name="Throughput_Performance";
- break;
+ return "Throughput_Performance";
case 3:
- name="Spin_Up_Time";
- break;
+ return "Spin_Up_Time";
case 4:
- name="Start_Stop_Count";
- break;
+ return "Start_Stop_Count";
case 5:
- name="Reallocated_Sector_Ct";
- break;
+ return "Reallocated_Sector_Ct";
case 6:
- name="Read_Channel_Margin";
- break;
+ return "Read_Channel_Margin";
case 7:
- name="Seek_Error_Rate";
- break;
+ return "Seek_Error_Rate";
case 8:
- name="Seek_Time_Performance";
- break;
+ return "Seek_Time_Performance";
case 9:
- switch (val) {
- case 1:
- name="Power_On_Minutes";
- break;
- case 2:
- name="Temperature_Celsius";
- break;
- case 3:
- name="Power_On_Seconds";
- break;
- case 4:
- name="Power_On_Half_Minutes";
- break;
- default:
- name="Power_On_Hours";
- break;
- }
- break;
+ return "Power_On_Hours";
case 10:
- name="Spin_Retry_Count";
- break;
+ return "Spin_Retry_Count";
case 11:
- name="Calibration_Retry_Count";
- break;
+ return "Calibration_Retry_Count";
case 12:
- name="Power_Cycle_Count";
- break;
+ return "Power_Cycle_Count";
case 13:
- name="Read_Soft_Error_Rate";
- break;
+ return "Read_Soft_Error_Rate";
case 175:
- name="Program_Fail_Count_Chip";
- break;
+ return "Program_Fail_Count_Chip";
case 176:
- name="Erase_Fail_Count_Chip";
- break;
+ return "Erase_Fail_Count_Chip";
case 177:
- name="Wear_Leveling_Count";
- break;
+ return "Wear_Leveling_Count";
case 178:
- name="Used_Rsvd_Blk_Cnt_Chip";
- break;
+ return "Used_Rsvd_Blk_Cnt_Chip";
case 179:
- name="Used_Rsvd_Blk_Cnt_Tot";
- break;
+ return "Used_Rsvd_Blk_Cnt_Tot";
case 180:
- name="Unused_Rsvd_Blk_Cnt_Tot";
- break;
+ return "Unused_Rsvd_Blk_Cnt_Tot";
case 181:
- name="Program_Fail_Cnt_Total";
- break;
+ return "Program_Fail_Cnt_Total";
case 182:
- name="Erase_Fail_Count_Total";
- break;
+ return "Erase_Fail_Count_Total";
case 183:
- name="Runtime_Bad_Block";
- break;
+ return "Runtime_Bad_Block";
case 184:
- name="End-to-End_Error";
- break;
+ return "End-to-End_Error";
case 187:
- name="Reported_Uncorrect";
- break;
+ return "Reported_Uncorrect";
case 188:
- name="Command_Timeout";
- break;
+ return "Command_Timeout";
case 189:
- name="High_Fly_Writes";
- break;
+ return "High_Fly_Writes";
case 190:
// Western Digital uses this for temperature.
// It's identical to Attribute 194 except that it
// is typically 55C. So if this attribute has failed
// in the past, it indicates that the drive temp exceeded
// 55C sometime in the past.
- name="Airflow_Temperature_Cel";
- break;
+ return "Airflow_Temperature_Cel";
case 191:
- name="G-Sense_Error_Rate";
- break;
+ return "G-Sense_Error_Rate";
case 192:
- switch (val) {
- case 1:
- // Fujitsu
- name="Emergency_Retract_Cycle_Ct";
- break;
- default:
- name="Power-Off_Retract_Count";
- break;
- }
- break;
+ return "Power-Off_Retract_Count";
case 193:
- name="Load_Cycle_Count";
- break;
+ return "Load_Cycle_Count";
case 194:
- switch (val){
- case 1:
- // Samsung SV1204H with RK100-13 firmware
- name="Temperature_Celsius_x10";
- break;
- case 2:
- // for disks with no temperature Attribute
- name="Unknown_Attribute";
- break;
- default:
- name="Temperature_Celsius";
- break;
- }
- break;
+ return "Temperature_Celsius";
case 195:
- // Fujitsu name="ECC_On_The_Fly_Count";
- name="Hardware_ECC_Recovered";
- break;
+ // Fujitsu: "ECC_On_The_Fly_Count";
+ return "Hardware_ECC_Recovered";
case 196:
- name="Reallocated_Event_Count";
- break;
+ return "Reallocated_Event_Count";
case 197:
- switch (val) {
- default:
- name="Current_Pending_Sector";
- break;
- case 1:
- // Not reset after sector reallocation
- name="Total_Pending_Sectors";
- break;
- }
- break;
+ return "Current_Pending_Sector";
case 198:
- switch (val){
- default:
- name="Offline_Uncorrectable";
- break;
- case 1:
- // Not reset after sector reallocation
- name="Total_Offl_Uncorrectabl"/*e*/;
- break;
- case 2:
- // Fujitsu
- name="Off-line_Scan_UNC_Sector_Ct";
- break;
- }
- break;
+ return "Offline_Uncorrectable";
case 199:
- name="UDMA_CRC_Error_Count";
- break;
+ return "UDMA_CRC_Error_Count";
case 200:
- switch (val) {
- case 1:
- // Fujitsu MHS2020AT
- name="Write_Error_Count";
- break;
- default:
- // Western Digital
- name="Multi_Zone_Error_Rate";
- break;
- }
- break;
+ // Western Digital
+ return "Multi_Zone_Error_Rate";
case 201:
- switch (val) {
- case 1:
- // Fujitsu
- name="Detected_TA_Count";
- break;
- default:
- name="Soft_Read_Error_Rate";
- break;
- }
- break;
+ return "Soft_Read_Error_Rate";
case 202:
- // Fujitsu
- name="TA_Increase_Count";
- // Maxtor: Data Address Mark Errors
- break;
+ // Fujitsu: "TA_Increase_Count"
+ return "Data_Address_Mark_Errs";
case 203:
// Fujitsu
- name="Run_Out_Cancel";
+ return "Run_Out_Cancel";
// Maxtor: ECC Errors
- break;
case 204:
- // Fujitsu
- name="Shock_Count_Write_Opern";
- // Maxtor: Soft ECC Correction
- break;
+ // Fujitsu: "Shock_Count_Write_Opern"
+ return "Soft_ECC_Correction";
case 205:
- // Fujitsu
- name="Shock_Rate_Write_Opern";
- // Maxtor: Thermal Aspirates
- break;
+ // Fujitsu: "Shock_Rate_Write_Opern"
+ return "Thermal_Asperity_Rate";
case 206:
// Fujitsu
- name="Flying_Height";
- break;
+ return "Flying_Height";
case 207:
// Maxtor
- name="Spin_High_Current";
- break;
+ return "Spin_High_Current";
case 208:
// Maxtor
- name="Spin_Buzz";
- break;
+ return "Spin_Buzz";
case 209:
// Maxtor
- name="Offline_Seek_Performnce";
- break;
+ return "Offline_Seek_Performnce";
case 220:
- switch (val) {
- case 1:
- name="Temperature_Celsius";
- break;
- default:
- name="Disk_Shift";
- break;
- }
- break;
+ return "Disk_Shift";
case 221:
- name="G-Sense_Error_Rate";
- break;
+ return "G-Sense_Error_Rate";
case 222:
- name="Loaded_Hours";
- break;
+ return "Loaded_Hours";
case 223:
- name="Load_Retry_Count";
- break;
+ return "Load_Retry_Count";
case 224:
- name="Load_Friction";
- break;
+ return "Load_Friction";
case 225:
- name="Load_Cycle_Count";
- break;
+ return "Load_Cycle_Count";
case 226:
- name="Load-in_Time";
- break;
+ return "Load-in_Time";
case 227:
- name="Torq-amp_Count";
- break;
+ return "Torq-amp_Count";
case 228:
- name="Power-off_Retract_Count";
- break;
+ return "Power-off_Retract_Count";
case 230:
// seen in IBM DTPA-353750
- name="Head_Amplitude";
- break;
+ return "Head_Amplitude";
case 231:
- name="Temperature_Celsius";
- break;
+ return "Temperature_Celsius";
+ case 232:
+ // seen in Intel X25-E SSD
+ return "Available_Reservd_Space";
+ case 233:
+ // seen in Intel X25-E SSD
+ return "Media_Wearout_Indicator";
case 240:
- name="Head_Flying_Hours";
- break;
+ return "Head_Flying_Hours";
+ case 241:
+ return "Total_LBAs_Written";
+ case 242:
+ return "Total_LBAs_Read";
case 250:
- name="Read_Error_Retry_Rate";
- break;
+ return "Read_Error_Retry_Rate";
+ case 254:
+ return "Free_Fall_Sensor";
default:
- name="Unknown_Attribute";
- break;
+ return "Unknown_Attribute";
}
- sprintf(out,"%3hu %s",(short int)id,name);
- return;
}
-// Returns raw value of Attribute with ID==id. This will be in the
-// range 0 to 2^48-1 inclusive. If the Attribute does not exist,
-// return -1.
-int64_t ATAReturnAttributeRawValue(unsigned char id, const ata_smart_values * data)
+// Get attribute name
+std::string ata_get_smart_attr_name(unsigned char id, const ata_vendor_attr_defs & defs)
{
- // valid Attribute IDs are in the range 1 to 255 inclusive.
- if (!id || !data)
+ if (!defs[id].name.empty())
+ return defs[id].name;
+ else
+ return get_default_attr_name(id);
+}
+
+// Find attribute index for attribute id, -1 if not found.
+int ata_find_attr_index(unsigned char id, const ata_smart_values & smartval)
+{
+ if (!id)
return -1;
-
- // loop over Attributes to see if there is one with the desired ID
for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
- const ata_smart_attribute * ap = data->vendor_attributes + i;
- if (ap->id == id) {
- // we've found the desired Attribute. Return its value
- int64_t rawvalue=0;
- int j;
-
- for (j=0; j<6; j++) {
- // This looks a bit roundabout, but is necessary. Don't
- // succumb to the temptation to use raw[j]<<(8*j) since under
- // the normal rules this will be promoted to the native type.
- // On a 32 bit machine this might then overflow.
- int64_t temp;
- temp = ap->raw[j];
- temp <<= 8*j;
- rawvalue |= temp;
- } // loop over j
- return rawvalue;
- } // found desired Attribute
- } // loop over Attributes
-
- // fall-through: no such Attribute found
+ if (smartval.vendor_attributes[i].id == id)
+ return i;
+ }
return -1;
}
// Return Temperature Attribute raw value selected according to possible
// non-default interpretations. If the Attribute does not exist, return 0
-unsigned char ATAReturnTemperatureValue(const ata_smart_values * data, const unsigned char * defs)
+unsigned char ata_return_temperature_value(const ata_smart_values * data, const ata_vendor_attr_defs & defs)
{
for (int i = 0; i < 3; i++) {
static const unsigned char ids[3] = {194, 9, 220};
unsigned char id = ids[i];
- unsigned char select = (defs ? defs[id] : 0);
- int64_t raw; unsigned temp;
- if (!( (id == 194 && select <= 1) // ! -v 194,unknown
- || (id == 9 && select == 2) // -v 9,temp
- || (id == 220 && select == 1))) // -v 220,temp
+ const ata_attr_raw_format format = defs[id].raw_format;
+ if (!( (id == 194 && format == RAWFMT_DEFAULT)
+ || format == RAWFMT_TEMPMINMAX || format == RAWFMT_TEMP10X))
continue;
- raw = ATAReturnAttributeRawValue(id, data);
- if (raw < 0)
+ int idx = ata_find_attr_index(id, *data);
+ if (idx < 0)
continue;
- temp = (unsigned short)raw; // ignore possible min/max values in high words
- if (id == 194 && select == 1) // -v 194,10xCelsius
+ uint64_t raw = ata_get_attr_raw_value(data->vendor_attributes[idx], defs);
+ unsigned temp = (unsigned short)raw; // ignore possible min/max values in high words
+ if (format == RAWFMT_TEMP10X) // -v N,temp10x
temp = (temp+5) / 10;
if (!(0 < temp && temp <= 255))
continue;
// read SCT status via SMART log 0xe0
memset(sts, 0, sizeof(*sts));
if (smartcommandhandler(device, READ_LOG, 0xe0, (char *)sts)){
- syserror("Error Read SCT Status failed");
+ pout("Error Read SCT Status failed: %s\n", device->get_errmsg());
return -1;
}
cmd.function_code = 1; // Read table
cmd.table_id = 2; // Temperature History Table
+ // swap endian order if needed
+ if (isbigendian()) {
+ swapx(&cmd.action_code);
+ swapx(&cmd.function_code);
+ swapx(&cmd.table_id);
+ }
+
// write command via SMART log page 0xe0
if (smartcommandhandler(device, WRITE_LOG, 0xe0, (char *)&cmd)){
- syserror("Error Write SCT Data Table command failed");
+ pout("Error Write SCT Data Table command failed: %s\n", device->get_errmsg());
return -1;
}
// read SCT data via SMART log page 0xe1
memset(tmh, 0, sizeof(*tmh));
if (smartcommandhandler(device, READ_LOG, 0xe1, (char *)tmh)){
- syserror("Error Read SCT Data Table failed");
+ pout("Error Read SCT Data Table failed: %s\n", device->get_errmsg());
return -1;
}
return -1;
if (!(sts->ext_status_code == 0 && sts->action_code == 5 && sts->function_code == 1)) {
- pout("Error unexcepted SCT status 0x%04x (action_code=%u, function_code=%u)\n",
+ pout("Error unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n",
sts->ext_status_code, sts->action_code, sts->function_code);
return -1;
}
cmd.state = interval;
cmd.option_flags = (persistent ? 0x01 : 0x00);
+ // swap endian order if needed
+ if (isbigendian()) {
+ swapx(&cmd.action_code);
+ swapx(&cmd.function_code);
+ swapx(&cmd.feature_code);
+ swapx(&cmd.state);
+ swapx(&cmd.option_flags);
+ }
+
// write command via SMART log page 0xe0
if (smartcommandhandler(device, WRITE_LOG, 0xe0, (char *)&cmd)){
- syserror("Error Write SCT Feature Control Command failed");
+ pout("Error Write SCT Feature Control Command failed: %s\n", device->get_errmsg());
return -1;
}
return 0;
}
+// Get/Set SCT Error Recovery Control
+static int ataGetSetSCTErrorRecoveryControltime(ata_device * device, unsigned type,
+ bool set, unsigned short & time_limit)
+{
+ // Check initial status
+ ata_sct_status_response sts;
+ if (ataReadSCTStatus(device, &sts))
+ return -1;
+
+ // Do nothing if other SCT command is executing
+ if (sts.ext_status_code == 0xffff) {
+ pout("Another SCT command is executing, abort Error Recovery Control\n"
+ "(SCT ext_status_code 0x%04x, action_code=%u, function_code=%u)\n",
+ sts.ext_status_code, sts.action_code, sts.function_code);
+ return -1;
+ }
+
+ ata_sct_error_recovery_control_command cmd; memset(&cmd, 0, sizeof(cmd));
+ // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
+ cmd.action_code = 3; // Error Recovery Control command
+ cmd.function_code = (set ? 1 : 2); // 1=Set timer, 2=Get timer
+ cmd.selection_code = type; // 1=Read timer, 2=Write timer
+ if (set)
+ cmd.time_limit = time_limit;
+
+ // swap endian order if needed
+ if (isbigendian()) {
+ swapx(&cmd.action_code);
+ swapx(&cmd.function_code);
+ swapx(&cmd.selection_code);
+ swapx(&cmd.time_limit);
+ }
+
+ // write command via SMART log page 0xe0
+ // TODO: Debug output
+ ata_cmd_in in;
+ in.in_regs.command = ATA_SMART_CMD;
+ in.in_regs.lba_high = SMART_CYL_HI; in.in_regs.lba_mid = SMART_CYL_LOW;
+ in.in_regs.features = ATA_SMART_WRITE_LOG_SECTOR;
+ in.in_regs.lba_low = 0xe0;
+ in.set_data_out(&cmd, 1);
+
+ if (!set)
+ // Time limit returned in ATA registers
+ in.out_needed.sector_count = in.out_needed.lba_low = true;
+
+ ata_cmd_out out;
+ if (!device->ata_pass_through(in, out)) {
+ pout("Error Write SCT (%cet) Error Recovery Control Command failed: %s\n",
+ (!set ? 'G' : 'S'), device->get_errmsg());
+ return -1;
+ }
+
+ // re-read and check SCT status
+ if (ataReadSCTStatus(device, &sts))
+ return -1;
+
+ if (!(sts.ext_status_code == 0 && sts.action_code == 3 && sts.function_code == (set ? 1 : 2))) {
+ pout("Error unexcepted SCT status 0x%04x (action_code=%u, function_code=%u)\n",
+ sts.ext_status_code, sts.action_code, sts.function_code);
+ return -1;
+ }
+
+ if (!set) {
+ // Check whether registers are properly returned by ioctl()
+ if (!(out.out_regs.sector_count.is_set() && out.out_regs.lba_low.is_set())) {
+ // TODO: Output register support should be checked within each ata_pass_through()
+ // implementation before command is issued.
+ pout("Error SMART WRITE LOG does not return COUNT and LBA_LOW register\n");
+ return -1;
+ }
+ // Return value to caller
+ time_limit = out.out_regs.sector_count | (out.out_regs.lba_low << 8);
+ }
+
+ return 0;
+}
+
+// Get SCT Error Recovery Control
+int ataGetSCTErrorRecoveryControltime(ata_device * device, unsigned type, unsigned short & time_limit)
+{
+ return ataGetSetSCTErrorRecoveryControltime(device, type, false/*get*/, time_limit);
+}
+
+// Set SCT Error Recovery Control
+int ataSetSCTErrorRecoveryControltime(ata_device * device, unsigned type, unsigned short time_limit)
+{
+ return ataGetSetSCTErrorRecoveryControltime(device, type, true/*set*/, time_limit);
+}
+
+
// Print one self-test log entry.
-// Returns true if self-test showed an error.
-bool ataPrintSmartSelfTestEntry(unsigned testnum, unsigned char test_type,
- unsigned char test_status,
- unsigned short timestamp,
- uint64_t failing_lba,
- bool print_error_only, bool & print_header)
-{
- const char * msgtest;
+// Returns:
+// -1: self-test failed
+// 1: extended self-test completed without error
+// 0: otherwise
+int ataPrintSmartSelfTestEntry(unsigned testnum, unsigned char test_type,
+ unsigned char test_status,
+ unsigned short timestamp,
+ uint64_t failing_lba,
+ bool print_error_only, bool & print_header)
+{
+ // Check status and type for return value
+ int retval = 0;
+ switch (test_status >> 4) {
+ case 0x0:
+ if ((test_type & 0x0f) == 0x02)
+ retval = 1; // extended self-test completed without error
+ break;
+ case 0x3: case 0x4:
+ case 0x5: case 0x6:
+ case 0x7: case 0x8:
+ retval = -1; // self-test failed
+ break;
+ }
+
+ if (retval >= 0 && print_error_only)
+ return retval;
+
+ std::string msgtest;
switch (test_type) {
case 0x00: msgtest = "Offline"; break;
case 0x01: msgtest = "Short offline"; break;
case 0x84: msgtest = "Selective captive"; break;
default:
if ((0x40 <= test_type && test_type <= 0x7e) || 0x90 <= test_type)
- msgtest = "Vendor offline";
+ msgtest = strprintf("Vendor (0x%02x)", test_type);
else
- msgtest = "Reserved offline";
+ msgtest = strprintf("Reserved (0x%02x)", test_type);
}
- bool is_error = false;
- const char * msgstat;
+ std::string msgstat;
switch (test_status >> 4) {
case 0x0: msgstat = "Completed without error"; break;
case 0x1: msgstat = "Aborted by host"; break;
case 0x2: msgstat = "Interrupted (host reset)"; break;
- case 0x3: msgstat = "Fatal or unknown error"; is_error = true; break;
- case 0x4: msgstat = "Completed: unknown failure"; is_error = true; break;
- case 0x5: msgstat = "Completed: electrical failure"; is_error = true; break;
- case 0x6: msgstat = "Completed: servo/seek failure"; is_error = true; break;
- case 0x7: msgstat = "Completed: read failure"; is_error = true; break;
- case 0x8: msgstat = "Completed: handling damage??"; is_error = true; break;
+ case 0x3: msgstat = "Fatal or unknown error"; break;
+ case 0x4: msgstat = "Completed: unknown failure"; break;
+ case 0x5: msgstat = "Completed: electrical failure"; break;
+ case 0x6: msgstat = "Completed: servo/seek failure"; break;
+ case 0x7: msgstat = "Completed: read failure"; break;
+ case 0x8: msgstat = "Completed: handling damage??"; break;
case 0xf: msgstat = "Self-test routine in progress"; break;
- default: msgstat = "Unknown/reserved test status";
+ default: msgstat = strprintf("Unknown status (0x%x)", test_status >> 4);
}
- if (!is_error && print_error_only)
- return false;
-
// Print header once
if (print_header) {
print_header = false;
}
char msglba[32];
- if (is_error && failing_lba < 0xffffffffffffULL)
+ if (retval < 0 && failing_lba < 0xffffffffffffULL)
snprintf(msglba, sizeof(msglba), "%"PRIu64, failing_lba);
else
strcpy(msglba, "-");
- pout("#%2u %-19s %-29s %1d0%% %8u %s\n", testnum, msgtest, msgstat,
- test_status & 0x0f, timestamp, msglba);
+ pout("#%2u %-19s %-29s %1d0%% %8u %s\n", testnum,
+ msgtest.c_str(), msgstat.c_str(), test_status & 0x0f, timestamp, msglba);
- return is_error;
+ return retval;
}
// Print Smart self-test log, used by smartctl and smartd.
}
bool noheaderprinted = true;
- int retval=0, hours=0, testno=0;
+ int errcnt = 0, hours = 0, igncnt = 0;
+ int testno = 0, ext_ok_testno = -1;
// print log
for (int i = 20; i >= 0; i--) {
uint64_t lba48 = (log->lbafirstfailure < 0xffffffff ? log->lbafirstfailure : 0xffffffffffffULL);
// Print entry
- bool errorfound = ataPrintSmartSelfTestEntry(testno,
- log->selftestnumber, log->selfteststatus, log->timestamp,
- lba48, !allentries, noheaderprinted);
-
- // keep track of time of most recent error
- if (errorfound && !hours)
- hours=log->timestamp;
+ int state = ataPrintSmartSelfTestEntry(testno,
+ log->selftestnumber, log->selfteststatus,
+ log->timestamp, lba48, !allentries, noheaderprinted);
+
+ if (state < 0) {
+ // Self-test showed an error
+ if (ext_ok_testno < 0) {
+ errcnt++;
+
+ // keep track of time of most recent error
+ if (!hours)
+ hours = log->timestamp;
+ }
+ else
+ // Newer successful extended self-test exits
+ igncnt++;
+ }
+ else if (state > 0 && ext_ok_testno < 0) {
+ // Latest successful extended self-test
+ ext_ok_testno = testno;
+ }
}
}
- if (!allentries && retval)
+
+ if (igncnt)
+ pout("%d of %d failed self-tests are outdated by newer successful extended offline self-test #%2d\n",
+ igncnt, igncnt+errcnt, ext_ok_testno);
+
+ if (!allentries && !noheaderprinted)
pout("\n");
- hours = hours << 8;
- return (retval | hours);
+ return ((hours << 8) | errcnt);
}
")"; // )
// Compile regex
- regular_expression regex;
- if (!regex.compile(pattern, REG_EXTENDED))
- return set_err(EIO, "invalid regex");
+ const regular_expression regex(pattern, REG_EXTENDED);
// Parse buffer
const char * errmsg = 0;