X-Git-Url: https://git.proxmox.com/?a=blobdiff_plain;f=atacmds.cpp;h=d84d1f033fc2752e2e44f48c5db93cc7e7058003;hb=1855d6340ce44908628a0f1e3d8b82ae169c600e;hp=72c4030938f1010270f69ea1a9e79a7523905599;hpb=f4ebf3d14d1fc0a257b7183a18d1b1505c163361;p=mirror_smartmontools-debian.git diff --git a/atacmds.cpp b/atacmds.cpp index 72c4030..d84d1f0 100644 --- a/atacmds.cpp +++ b/atacmds.cpp @@ -3,8 +3,8 @@ * * Home page of code is: http://smartmontools.sourceforge.net * - * Copyright (C) 2002-9 Bruce Allen - * Copyright (C) 2008-9 Christian Franke + * Copyright (C) 2002-11 Bruce Allen + * Copyright (C) 2008-13 Christian Franke * Copyright (C) 1999-2000 Michael Cornwell * Copyright (C) 2000 Andre Hedrick * @@ -14,8 +14,7 @@ * any later version. * * You should have received a copy of the GNU General Public License - * (for example COPYING); if not, write to the Free - * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * (for example COPYING); If not, see . * * This code was originally developed as a Senior Thesis by Michael Cornwell * at the Concurrent Systems Laboratory (now part of the Storage Systems @@ -33,15 +32,19 @@ #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 3046 2010-01-22 21:30:02Z chrfranke $" +const char * atacmds_cpp_cvsid = "$Id: atacmds.cpp 3777 2013-02-19 18:32:15Z samm2 $" 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 @@ -53,98 +56,6 @@ extern smartmonctrl *con; #define SRET_STATUS_HI_EXCEEDED 0x2C #define SRET_STATUS_MID_EXCEEDED 0xF4 -// These Drive Identity tables are taken from hdparm 5.2, and are also -// given in the ATA/ATAPI specs for the IDENTIFY DEVICE command. Note -// 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. -#define NOVAL_0 0x0000 -#define NOVAL_1 0xffff -/* word 81: minor version number */ -#define MINOR_MAX 0x22 -static const char * const minor_str[] = { /* word 81 value: */ - "Device does not report version", /* 0x0000 */ - "ATA-1 X3T9.2 781D prior to revision 4", /* 0x0001 */ - "ATA-1 published, ANSI X3.221-1994", /* 0x0002 */ - "ATA-1 X3T9.2 781D revision 4", /* 0x0003 */ - "ATA-2 published, ANSI X3.279-1996", /* 0x0004 */ - "ATA-2 X3T10 948D prior to revision 2k", /* 0x0005 */ - "ATA-3 X3T10 2008D revision 1", /* 0x0006 */ /* SMART NOT INCLUDED */ - "ATA-2 X3T10 948D revision 2k", /* 0x0007 */ - "ATA-3 X3T10 2008D revision 0", /* 0x0008 */ - "ATA-2 X3T10 948D revision 3", /* 0x0009 */ - "ATA-3 published, ANSI X3.298-199x", /* 0x000a */ - "ATA-3 X3T10 2008D revision 6", /* 0x000b */ /* 1st VERSION WITH SMART */ - "ATA-3 X3T13 2008D revision 7 and 7a", /* 0x000c */ - "ATA/ATAPI-4 X3T13 1153D revision 6", /* 0x000d */ - "ATA/ATAPI-4 T13 1153D revision 13", /* 0x000e */ - "ATA/ATAPI-4 X3T13 1153D revision 7", /* 0x000f */ - "ATA/ATAPI-4 T13 1153D revision 18", /* 0x0010 */ - "ATA/ATAPI-4 T13 1153D revision 15", /* 0x0011 */ - "ATA/ATAPI-4 published, ANSI NCITS 317-1998", /* 0x0012 */ - "ATA/ATAPI-5 T13 1321D revision 3", /* 0x0013 */ - "ATA/ATAPI-4 T13 1153D revision 14", /* 0x0014 */ - "ATA/ATAPI-5 T13 1321D revision 1", /* 0x0015 */ - "ATA/ATAPI-5 published, ANSI NCITS 340-2000", /* 0x0016 */ - "ATA/ATAPI-4 T13 1153D revision 17", /* 0x0017 */ - "ATA/ATAPI-6 T13 1410D revision 0", /* 0x0018 */ - "ATA/ATAPI-6 T13 1410D revision 3a", /* 0x0019 */ - "ATA/ATAPI-7 T13 1532D revision 1", /* 0x001a */ - "ATA/ATAPI-6 T13 1410D revision 2", /* 0x001b */ - "ATA/ATAPI-6 T13 1410D revision 1", /* 0x001c */ - "ATA/ATAPI-7 published, ANSI INCITS 397-2005",/* 0x001d */ - "ATA/ATAPI-7 T13 1532D revision 0", /* 0x001e */ - "reserved", /* 0x001f */ - "reserved", /* 0x0020 */ - "ATA/ATAPI-7 T13 1532D revision 4a", /* 0x0021 */ - "ATA/ATAPI-6 published, ANSI INCITS 361-2002" /* 0x0022 */ -}; - -// NOTE ATA/ATAPI-4 REV 4 was the LAST revision where the device -// attribute structures were NOT completely vendor specific. So any -// disk that is ATA/ATAPI-4 or above can not be trusted to show the -// vendor values in sensible format. - -// Negative values below are because it doesn't support SMART -static const int actual_ver[] = { - /* word 81 value: */ - 0, /* 0x0000 WARNING: */ - 1, /* 0x0001 WARNING: */ - 1, /* 0x0002 WARNING: */ - 1, /* 0x0003 WARNING: */ - 2, /* 0x0004 WARNING: This array */ - 2, /* 0x0005 WARNING: corresponds */ - -3, /*<== */ /* 0x0006 WARNING: *exactly* */ - 2, /* 0x0007 WARNING: to the ATA/ */ - -3, /*<== */ /* 0x0008 WARNING: ATAPI version */ - 2, /* 0x0009 WARNING: listed in */ - 3, /* 0x000a WARNING: the */ - 3, /* 0x000b WARNING: minor_str */ - 3, /* 0x000c WARNING: array */ - 4, /* 0x000d WARNING: above. */ - 4, /* 0x000e WARNING: */ - 4, /* 0x000f WARNING: If you change */ - 4, /* 0x0010 WARNING: that one, */ - 4, /* 0x0011 WARNING: change this one */ - 4, /* 0x0012 WARNING: too!!! */ - 5, /* 0x0013 WARNING: */ - 4, /* 0x0014 WARNING: */ - 5, /* 0x0015 WARNING: */ - 5, /* 0x0016 WARNING: */ - 4, /* 0x0017 WARNING: */ - 6, /* 0x0018 WARNING: */ - 6, /* 0x0019 WARNING: */ - 7, /* 0x001a WARNING: */ - 6, /* 0x001b WARNING: */ - 6, /* 0x001c WARNING: */ - 7, /* 0x001d WARNING: */ - 7, /* 0x001e WARNING: */ - 0, /* 0x001f WARNING: */ - 0, /* 0x0020 WARNING: */ - 7, /* 0x0021 WARNING: */ - 6 /* 0x0022 WARNING: */ -}; // Get ID and increase flag of current pending or offline // uncorrectable attribute. @@ -152,7 +63,13 @@ 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].flags & ATTRFLAG_INCREASING); + 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; } @@ -197,14 +114,19 @@ const format_name_entry format_names[] = { {"raw16" , RAWFMT_RAW16}, {"raw48" , RAWFMT_RAW48}, {"hex48" , RAWFMT_HEX48}, + {"raw56" , RAWFMT_RAW56}, + {"hex56" , RAWFMT_HEX56}, {"raw64" , RAWFMT_RAW64}, {"hex64" , RAWFMT_HEX64}, {"raw16(raw16)" , RAWFMT_RAW16_OPT_RAW16}, {"raw16(avg16)" , RAWFMT_RAW16_OPT_AVG16}, - {"raw24/raw24" , RAWFMT_RAW24_RAW24}, + {"raw24(raw8)" , RAWFMT_RAW24_OPT_RAW8}, + {"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}, }; @@ -222,11 +144,11 @@ const char * map_old_vendor_opts[][2] = { {"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"}, + {"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"}, + {"220,temp" , "220,tempminmax,Temperature_Celsius"}, }; const unsigned num_old_vendor_opts = sizeof(map_old_vendor_opts)/sizeof(map_old_vendor_opts[0]); @@ -271,6 +193,19 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs, 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_format_names) @@ -280,9 +215,9 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs, } ata_attr_raw_format format = format_names[i].format; - // 64-bit formats use the normalized value bytes. - if (format == RAWFMT_RAW64 || format == RAWFMT_HEX64) - flags |= ATTRFLAG_NO_NORMVAL; + // 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,format" -> set format for all entries @@ -294,6 +229,7 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs, defs[i].priority = priority; defs[i].raw_format = format; defs[i].flags = flags; + snprintf(defs[i].byteorder, sizeof(defs[i].byteorder), "%s", byteorder); } } else if (defs[id].priority <= priority) { @@ -303,6 +239,7 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs, defs[id].raw_format = format; defs[id].priority = priority; defs[id].flags = flags; + snprintf(defs[id].byteorder, sizeof(defs[id].byteorder), "%s", byteorder); } return true; @@ -317,13 +254,42 @@ std::string create_vendor_attribute_arg_list() std::string s; unsigned i; for (i = 0; i < num_format_names; i++) - s += strprintf("%s\tN,%s[,ATTR_NAME]", + 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; } + +// Parse firmwarebug def (-F option). +// Return false on error. +bool parse_firmwarebug_def(const char * opt, firmwarebug_defs & firmwarebugs) +{ + if (!strcmp(opt, "none")) + firmwarebugs.set(BUG_NONE); + else if (!strcmp(opt, "nologdir")) + firmwarebugs.set(BUG_NOLOGDIR); + else if (!strcmp(opt, "samsung")) + firmwarebugs.set(BUG_SAMSUNG); + else if (!strcmp(opt, "samsung2")) + firmwarebugs.set(BUG_SAMSUNG2); + else if (!strcmp(opt, "samsung3")) + firmwarebugs.set(BUG_SAMSUNG3); + else if (!strcmp(opt, "xerrorlba")) + firmwarebugs.set(BUG_XERRORLBA); + else + return false; + return true; +} + +// Return a string of valid argument words for parse_firmwarebug_def() +const char * get_valid_firmwarebug_args() +{ + return "none, nologdir, samsung, samsung2, samsung3, xerrorlba"; +} + + // swap two bytes. Point to low address void swap2(char *location){ char tmp=*location; @@ -353,12 +319,19 @@ void swap8(char *location){ 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) @@ -391,26 +364,27 @@ static const char * const commandstrings[]={ }; -static const char * preg(const ata_register & r, char * buf) +static const char * preg(const ata_register & r, char (& buf)[8]) { if (!r.is_set()) //return "n/a "; return "...."; - sprintf(buf, "0x%02x", r.val()); return buf; + snprintf(buf, sizeof(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]; + char bufs[7][8]; pout("%s FR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, CMD=%s%s", prefix, preg(r.features, bufs[0]), preg(r.sector_count, bufs[1]), preg(r.lba_low, bufs[2]), preg(r.lba_mid, bufs[3]), preg(r.lba_high, bufs[4]), preg(r.device, bufs[5]), 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]; + char bufs[7][8]; pout("%sERR=%s, SC=%s, LL=%s, LM=%s, LH=%s, DEV=%s, STS=%s%s", prefix, preg(r.error, bufs[0]), preg(r.sector_count, bufs[1]), preg(r.lba_low, bufs[2]), preg(r.lba_mid, bufs[3]), preg(r.lba_high, bufs[4]), preg(r.device, bufs[5]), @@ -420,12 +394,19 @@ void print_regs(const char * prefix, const ata_out_regs & r, const char * suffix 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) (' ' <= p[n] && 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); } @@ -445,7 +426,7 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele 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 || @@ -477,7 +458,7 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele // 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]); @@ -556,19 +537,29 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele 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; + + int64_t start_usec = -1; + if (ata_debugmode) + start_usec = smi()->get_timer_usec(); + bool ok = device->ata_pass_through(in, out); - if (con->reportataioctl && out.out_regs.is_set()) + if (start_usec >= 0) { + int64_t duration_usec = smi()->get_timer_usec() - start_usec; + if (duration_usec >= 500) + pout(" [Duration: %.3fs]\n", duration_usec / 1000000.0); + } + + if (ata_debugmode && out.out_regs.is_set()) print_regs(" Output: ", out.out_regs); if (ok) switch (command) { @@ -576,8 +567,15 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele 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" @@ -590,19 +588,27 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele 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("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; @@ -610,11 +616,11 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele } // 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, @@ -624,7 +630,7 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele 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 @@ -632,42 +638,63 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele } } - 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] ; + + // Return if capacity unknown (ATAPI CD/DVD) + if (!(lba28 || lba48)) + return; - // LBA support? - if (!(capabilities_0 & 0x0200)) - return 0; // No + // 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 @@ -719,11 +746,12 @@ static void trim(char * out, const char * in) } // 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 @@ -731,9 +759,9 @@ void format_ata_string(char * out, const char * in, int n, bool fix_swap) 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); } @@ -756,8 +784,30 @@ int ataCheckPowerMode(ata_device * device) { return (int)result; } +// Issue a no-data ATA command with optional sector count register value +bool ata_nodata_command(ata_device * device, unsigned char command, + int sector_count /* = -1 */) +{ + ata_cmd_in in; + in.in_regs.command = command; + if (sector_count >= 0) + in.in_regs.sector_count = sector_count; + return device->ata_pass_through(in); +} +// Issue SET FEATURES command with optional sector count register value +bool ata_set_features(ata_device * device, unsigned char features, + int sector_count /* = -1 */) +{ + ata_cmd_in in; + in.in_regs.command = ATA_SET_FEATURES; + in.in_regs.features = features; + if (sector_count >= 0) + in.in_regs.sector_count = sector_count; + + return device->ata_pass_through(in); +} // Reads current Device Identity info (512 bytes) into buf. Returns 0 // if all OK. Returns -1 if no ATA Device identity can be @@ -765,23 +815,42 @@ int ataCheckPowerMode(ata_device * device) { // 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 char * raw_buf /* = 0 */) +{ 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)); + } + + // If requested, save raw data before endianness adjustments + if (raw_buf) + memcpy(raw_buf, buf, sizeof(*buf)); + #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++) @@ -798,7 +867,31 @@ int ataReadHDIdentity (ata_device * device, struct ata_identify_device *buf){ // 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); @@ -807,80 +900,43 @@ int ataReadHDIdentity (ata_device * device, struct ata_identify_device *buf){ return 0; } -// Returns ATA version as an integer, and a pointer to a string -// describing which revision. Note that Revision 0 of ATA-3 does NOT -// support SMART. For this one case we return -3 rather than +3 as -// 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; - } - - // The minor revision number has more information - try there first - if (*minor && (*minor<=MINOR_MAX)){ - int std = actual_ver[*minor]; - if (std) { - *description=minor_str[*minor]; - return std; - } - } +// 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 - // Try new ATA-8 minor revision numbers (Table 31 of T13/1699-D Revision 6) - // (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 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; - default: desc = 0; break; - } - if (desc) { - *description = desc; - return 8; - } - - // HDPARM has a very complicated algorithm from here on. Since SMART only - // exists on ATA-3 and later standards, let's punt on this. If you don't - // like it, please fix it. The code's in CVS. - int i; - for (i=15; i>0; i--) - if (major & (0x1<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); +} + +// Get nominal media rotation rate. +// Returns: 0 = not reported, 1 = SSD, >1 = HDD rpm, < 0 = -(Unknown value) +int ata_get_rotation_rate(const ata_identify_device * id) +{ + // Table 37 of T13/1699-D (ATA8-ACS) Revision 6a, September 6, 2008 + // Table A.31 of T13/2161-D (ACS-3) Revision 3b, August 25, 2012 + unsigned short word217 = id->words088_255[217-88]; + if (word217 == 0x0000 || word217 == 0xffff) + return 0; + else if (word217 == 0x0001) return 1; + else if (word217 > 0x0400) + return word217; else - return i; + return -(int)word217; } // returns 1 if SMART supported, 0 if SMART unsupported, -1 if can't tell @@ -918,7 +974,6 @@ int ataIsSmartEnabled(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"); return -1; } @@ -932,6 +987,7 @@ int ataReadSmartValues(ata_device * device, struct ata_smart_values *data){ swap2((char *)&(data->revnumber)); swap2((char *)&(data->total_time_to_complete_off_line)); swap2((char *)&(data->smart_capability)); + swapx(&data->extend_test_completion_time_w); for (i=0; ivendor_attributes+i; swap2((char *)&(x->flags)); @@ -962,12 +1018,11 @@ static void fixsamsungselftestlog(ata_smart_selftestlog * data) // Reads the Self Test Log (log #6) int ataReadSelfTestLog (ata_device * device, ata_smart_selftestlog * data, - unsigned char fix_firmwarebug) + firmwarebug_defs firmwarebugs) { // get data from device if (smartcommandhandler(device, READ_LOG, 0x06, (char *)data)){ - syserror("Error SMART Error Self-Test Log Read failed"); return -1; } @@ -976,7 +1031,7 @@ int ataReadSelfTestLog (ata_device * device, ata_smart_selftestlog * data, checksumwarning("SMART Self-Test Log Structure"); // fix firmware bugs in self-test log - if (fix_firmwarebug == FIX_SAMSUNG) + if (firmwarebugs.is_set(BUG_SAMSUNG)) fixsamsungselftestlog(data); // swap endian order if needed @@ -1107,7 +1162,6 @@ int ataReadSelectiveSelfTestLog(ata_device * device, struct ata_selective_self_t // get data from device if (smartcommandhandler(device, READ_LOG, 0x09, (char *)data)){ - syserror("Error SMART Read Selective Self-Test Log failed"); return -1; } @@ -1129,15 +1183,13 @@ int ataReadSelectiveSelfTestLog(ata_device * device, struct ata_selective_self_t swap2((char *)&(data->pendingtime)); } - if (data->logversion != 1) - pout("Note: selective self-test log revision number (%d) not 1 implies that no selective self-test has ever been run\n", data->logversion); - return 0; } // 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) { @@ -1149,6 +1201,7 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg struct ata_selective_self_test_log sstlog, *data=&sstlog; unsigned char *ptr=(unsigned char *)data; if (ataReadSelectiveSelfTestLog(device, data)) { + pout("SMART Read Selective Self-test Log failed: %s\n", device->get_errmsg()); pout("Since Read failed, will not attempt to WRITE Selective Self-test Log\n"); return -1; } @@ -1159,7 +1212,7 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg // Host is NOT allowed to write selective self-test log if a selective // self-test is in progress. if (0currentspan && data->currentspan<6 && ((sv->self_test_exec_status)>>4)==15) { - pout("Error SMART Selective or other Self-Test in progress.\n"); + pout("SMART Selective or other Self-test in progress\n"); return -4; } @@ -1181,6 +1234,17 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg 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; @@ -1281,9 +1345,9 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg // 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)); @@ -1293,7 +1357,7 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg // write new selective self-test log if (smartcommandhandler(device, WRITE_LOG, 0x09, (char *)data)){ - syserror("Error Write Selective Self-Test Log failed"); + pout("Write Selective Self-test Log failed: %s\n", device->get_errmsg()); return -3; } @@ -1335,12 +1399,11 @@ static void fixsamsungerrorlog2(ata_smart_errorlog * data) // Error Log is #2, and the Extended Comprehensive SMART Error log is // #3 int ataReadErrorLog (ata_device * device, ata_smart_errorlog *data, - unsigned char fix_firmwarebug) + firmwarebug_defs firmwarebugs) { // get data from device if (smartcommandhandler(device, READ_LOG, 0x01, (char *)data)){ - syserror("Error SMART Error Log Read failed"); return -1; } @@ -1350,9 +1413,9 @@ int ataReadErrorLog (ata_device * device, ata_smart_errorlog *data, // Some disks have the byte order reversed in some SMART Summary // Error log entries - if (fix_firmwarebug == FIX_SAMSUNG) + if (firmwarebugs.is_set(BUG_SAMSUNG)) fixsamsungerrorlog(data); - else if (fix_firmwarebug == FIX_SAMSUNG2) + else if (firmwarebugs.is_set(BUG_SAMSUNG2)) fixsamsungerrorlog2(data); // swap endian order if needed @@ -1376,9 +1439,34 @@ int ataReadErrorLog (ata_device * device, ata_smart_errorlog *data, return 0; } + +// Fix LBA byte ordering of Extended Comprehensive Error Log +// if little endian instead of ATA register ordering is provided +template +static inline void fix_exterrlog_lba_cmd(T & cmd) +{ + T org = cmd; + cmd.lba_mid_register_hi = org.lba_high_register; + cmd.lba_low_register_hi = org.lba_mid_register_hi; + cmd.lba_high_register = org.lba_mid_register; + cmd.lba_mid_register = org.lba_low_register_hi; +} + +static void fix_exterrlog_lba(ata_smart_exterrlog * log, unsigned nsectors) +{ + for (unsigned i = 0; i < nsectors; i++) { + for (int ei = 0; ei < 4; ei++) { + ata_smart_exterrlog_error_log & entry = log[i].error_logs[ei]; + fix_exterrlog_lba_cmd(entry.error); + for (int ci = 0; ci < 5; ci++) + fix_exterrlog_lba_cmd(entry.commands[ci]); + } + } +} + // Read Extended Comprehensive Error Log bool ataReadExtErrorLog(ata_device * device, ata_smart_exterrlog * log, - unsigned nsectors) + unsigned nsectors, firmwarebug_defs firmwarebugs) { if (!ataReadLogExt(device, 0x03, 0x00, 0, log, nsectors)) return false; @@ -1396,6 +1484,9 @@ bool ataReadExtErrorLog(ata_device * device, ata_smart_exterrlog * log, } } + if (firmwarebugs.is_set(BUG_XERRORLBA)) + fix_exterrlog_lba(log, nsectors); + return true; } @@ -1404,7 +1495,6 @@ int ataReadSmartThresholds (ata_device * device, struct ata_smart_thresholds_pvt // get data from device if (smartcommandhandler(device, READ_THRESHOLDS, 0, (char *)data)){ - syserror("Error SMART Thresholds Read failed"); return -1; } @@ -1421,7 +1511,6 @@ int ataReadSmartThresholds (ata_device * device, struct ata_smart_thresholds_pvt int ataEnableSmart (ata_device * device ){ if (smartcommandhandler(device, ENABLE, 0, NULL)){ - syserror("Error SMART Enable failed"); return -1; } return 0; @@ -1430,7 +1519,6 @@ int ataEnableSmart (ata_device * device ){ int ataDisableSmart (ata_device * device ){ if (smartcommandhandler(device, DISABLE, 0, NULL)){ - syserror("Error SMART Disable failed"); return -1; } return 0; @@ -1438,7 +1526,6 @@ int ataDisableSmart (ata_device * device ){ int ataEnableAutoSave(ata_device * device){ if (smartcommandhandler(device, AUTOSAVE, 241, NULL)){ - syserror("Error SMART Enable Auto-save failed"); return -1; } return 0; @@ -1447,7 +1534,6 @@ int ataEnableAutoSave(ata_device * device){ int ataDisableAutoSave(ata_device * device){ if (smartcommandhandler(device, AUTOSAVE, 0, NULL)){ - syserror("Error SMART Disable Auto-save failed"); return -1; } return 0; @@ -1461,7 +1547,6 @@ int ataEnableAutoOffline (ata_device * device){ /* timer hard coded to 4 hours */ if (smartcommandhandler(device, AUTO_OFFLINE, 248, NULL)){ - syserror("Error SMART Enable Automatic Offline failed"); return -1; } return 0; @@ -1472,7 +1557,6 @@ int ataEnableAutoOffline (ata_device * device){ int ataDisableAutoOffline (ata_device * device){ if (smartcommandhandler(device, AUTO_OFFLINE, 0, NULL)){ - syserror("Error SMART Disable Automatic Offline failed"); return -1; } return 0; @@ -1500,11 +1584,12 @@ int ataSmartStatus2(ata_device * device){ // This is the way to execute ALL tests: offline, short self-test, // extended self test, with and without captive mode, etc. // TODO: Move to ataprint.cpp ? -int ataSmartTest(ata_device * device, int testtype, const ata_selective_selftest_args & selargs, +int ataSmartTest(ata_device * device, int testtype, bool force, + const ata_selective_selftest_args & selargs, 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; @@ -1526,8 +1611,21 @@ int ataSmartTest(ata_device * device, int testtype, const ata_selective_selftest else if ((select=(testtype==SELECTIVE_SELF_TEST || testtype==SELECTIVE_CAPTIVE_SELF_TEST))) type="Selective self-test"; else - type="[Unrecognized] self-test"; - + type = 0; + + // Check whether another test is already running + if (type && (sv->self_test_exec_status >> 4) == 0xf) { + if (!force) { + pout("Can't start self-test without aborting current test (%d0%% remaining),\n" + "%srun 'smartctl -X' to abort test.\n", + sv->self_test_exec_status & 0x0f, + (!select ? "add '-t force' option to override, or " : "")); + return -1; + } + } + else + force = false; + // If doing a selective self-test, first use WRITE_LOG to write the // selective self-test log. ata_selective_selftest_args selargs_io = selargs; // filled with info about actual spans @@ -1539,9 +1637,11 @@ int ataSmartTest(ata_device * device, int testtype, const ata_selective_selftest // 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"); + snprintf(cmdmsg, sizeof(cmdmsg), "Abort SMART off-line mode self-test routine"); + else if (!type) + snprintf(cmdmsg, sizeof(cmdmsg), "SMART EXECUTE OFF-LINE IMMEDIATE subcommand 0x%02x", testtype); else - sprintf(cmdmsg,"Execute SMART %s routine immediately in %s mode",type,captive); + snprintf(cmdmsg, sizeof(cmdmsg), "Execute SMART %s routine immediately in %s mode", type, captive); pout("Sending command: \"%s\".\n",cmdmsg); if (select) { @@ -1554,21 +1654,21 @@ int ataSmartTest(ata_device * device, int testtype, const ata_selective_selftest } // 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%s.\n", (force ? " (previous test aborted)" : "")); + } return 0; } @@ -1583,7 +1683,12 @@ int TestTime(const ata_smart_values *data, int testtype) return (int) data->short_test_completion_time; case EXTEND_SELF_TEST: case EXTEND_CAPTIVE_SELF_TEST: - return (int) data->extend_test_completion_time; + if (data->extend_test_completion_time_b == 0xff + && data->extend_test_completion_time_w != 0x0000 + && data->extend_test_completion_time_w != 0xffff) + return data->extend_test_completion_time_w; // ATA-8 + else + return data->extend_test_completion_time_b; case CONVEYANCE_SELF_TEST: case CONVEYANCE_CAPTIVE_SELF_TEST: return (int) data->conveyance_test_completion_time; @@ -1705,8 +1810,10 @@ int isSupportSelectiveSelfTest(const ata_smart_values * data) // Get attribute state ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr, - const ata_smart_threshold_entry & thre, - const ata_vendor_attr_defs & defs) + 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; @@ -1717,27 +1824,35 @@ ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr, if (defs[attr.id].flags & ATTRFLAG_NO_NORMVAL) return ATTRSTATE_NO_NORMVAL; - // No threshold if thresholds cannot be read. - if (!thre.id && !thre.threshold) - return ATTRSTATE_NO_THRESHOLD; + // 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; + } + } + unsigned char threshold = thresholds[i].threshold; - // Bad threshold if id's don't match - if (attr.id != thre.id) - return ATTRSTATE_BAD_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 (!thre.threshold) + if (!threshold) return ATTRSTATE_OK; // Failed now if current value is below threshold - if (attr.current <= thre.threshold) + if (attr.current <= threshold) return ATTRSTATE_FAILED_NOW; - // Failed in the passed if worst value is below threshold - if (attr.worst <= thre.threshold) + // 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; @@ -1754,6 +1869,9 @@ static ata_attr_raw_format get_default_raw_format(unsigned char id) case 196: // Reallocated event count return RAWFMT_RAW16_OPT_RAW16; + case 9: // Power on hours + return RAWFMT_RAW24_OPT_RAW8; + case 190: // Temperature case 194: return RAWFMT_TEMPMINMAX; @@ -1767,24 +1885,44 @@ static ata_attr_raw_format get_default_raw_format(unsigned char id) uint64_t ata_get_attr_raw_value(const ata_smart_attribute & attr, const ata_vendor_attr_defs & defs) { - // Get 48 bit raw value - const unsigned char * raw = attr.raw; - uint64_t rawvalue; - rawvalue = raw[0] - | ( raw[1] << 8) - | ( raw[2] << 16) - | ((uint64_t)raw[3] << 24) - | ((uint64_t)raw[4] << 32) - | ((uint64_t)raw[5] << 40); - - if (defs[attr.id].flags & ATTRFLAG_NO_NORMVAL) { - // Some SSD vendors use bytes 3-10 from the Attribute - // Data Structure to store a 64-bit raw value. - rawvalue <<= 8; - rawvalue |= attr.worst; - rawvalue <<= 8; - rawvalue |= attr.current; + 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_RAW56: + case RAWFMT_HEX56: + case RAWFMT_RAW24_DIV_RAW32: + case RAWFMT_MSEC24_HOUR32: + byteorder = "r543210"; break; + default: + byteorder = "543210"; break; + } + } + + // 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; } + return rawvalue; } @@ -1793,11 +1931,17 @@ uint64_t ata_get_attr_raw_value(const ata_smart_attribute & attr, std::string ata_format_attr_raw_value(const ata_smart_attribute & attr, const ata_vendor_attr_defs & defs) { - // Get 48 bit or64 bit raw value + // Get 48 bit or 64 bit raw value uint64_t rawvalue = ata_get_attr_raw_value(attr, defs); - // Get 16 bit words - const unsigned char * raw = attr.raw; + // 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]; word[0] = raw[0] | (raw[1] << 8); word[1] = raw[2] | (raw[3] << 8); @@ -1821,6 +1965,8 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr, break; case RAWFMT_RAW48: + case RAWFMT_RAW56: + case RAWFMT_RAW64: s = strprintf("%"PRIu64, rawvalue); break; @@ -1828,8 +1974,8 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr, s = strprintf("0x%012"PRIx64, rawvalue); break; - case RAWFMT_RAW64: - s = strprintf("%"PRIu64, rawvalue); + case RAWFMT_HEX56: + s = strprintf("0x%014"PRIx64, rawvalue); break; case RAWFMT_HEX64: @@ -1839,7 +1985,7 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr, case RAWFMT_RAW16_OPT_RAW16: s = strprintf("%u", word[0]); if (word[1] || word[2]) - s += strprintf(" (%u, %u)", word[2], word[1]); + s += strprintf(" (%u %u)", word[2], word[1]); break; case RAWFMT_RAW16_OPT_AVG16: @@ -1848,10 +1994,20 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr, s += strprintf(" (Average %u)", word[1]); break; - case RAWFMT_RAW24_RAW24: - s = strprintf("%d/%d", - raw[0] | (raw[1]<<8) | (raw[2]<<16), - raw[3] | (raw[4]<<8) | (raw[5]<<16)); + case RAWFMT_RAW24_OPT_RAW8: + s = strprintf("%u", (unsigned)(rawvalue & 0x00ffffffULL)); + if (raw[3] || raw[4] || raw[5]) + s += strprintf(" (%d %d %d)", raw[5], raw[4], raw[3]); + 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: @@ -1885,26 +2041,49 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr, } break; + 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); + } + break; + case RAWFMT_TEMPMINMAX: // Temperature - 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; + { + // Search for possible min/max values + // 00 HH 00 LL 00 TT (Hitachi/IBM) + // 00 00 HH LL 00 TT (Maxtor, Samsung) + // 00 00 00 HH LL TT (WDC) + unsigned char lo = 0, hi = 0; + int cnt = 0; + for (int i = 1; i < 6; i++) { + if (raw[i]) + switch (cnt++) { + case 0: + lo = raw[i]; + break; + case 1: + if (raw[i] < lo) { + hi = lo; lo = raw[i]; + } + else + hi = raw[i]; + break; + } } - if (lo <= word[0] && word[0] <= hi) - s += strprintf(" (Lifetime Min/Max %u/%u)", lo, hi); + + unsigned char t = raw[0]; + if (cnt == 0) + s = strprintf("%d", t); + else if (cnt == 2 && 0 < lo && lo <= t && t <= hi && hi < 128) + s = strprintf("%d (Min/Max %d/%d)", t, lo, hi); else - s += strprintf(" (%d %d %d %d)", raw[5], raw[4], raw[3], raw[2]); + s = strprintf("%d (%d %d %d %d %d)", t, raw[5], raw[4], raw[3], raw[2], raw[1]); } break; @@ -1923,8 +2102,13 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr, // 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) +static const char * get_default_attr_name(unsigned char id, int rpm) { + bool hdd = (rpm > 1), ssd = (rpm == 1); + + static const char Unknown_HDD_Attribute[] = "Unknown_HDD_Attribute"; + static const char Unknown_SSD_Attribute[] = "Unknown_SSD_Attribute"; + switch (id) { case 1: return "Raw_Read_Error_Rate"; @@ -1937,36 +2121,48 @@ static const char * get_default_attr_name(unsigned char id) case 5: return "Reallocated_Sector_Ct"; case 6: + if (ssd) return Unknown_SSD_Attribute; return "Read_Channel_Margin"; case 7: + if (ssd) return Unknown_SSD_Attribute; return "Seek_Error_Rate"; case 8: + if (ssd) return Unknown_SSD_Attribute; return "Seek_Time_Performance"; case 9: return "Power_On_Hours"; case 10: + if (ssd) return Unknown_SSD_Attribute; return "Spin_Retry_Count"; case 11: + if (ssd) return Unknown_SSD_Attribute; return "Calibration_Retry_Count"; case 12: return "Power_Cycle_Count"; case 13: return "Read_Soft_Error_Rate"; case 175: + if (hdd) return Unknown_HDD_Attribute; return "Program_Fail_Count_Chip"; case 176: + if (hdd) return Unknown_HDD_Attribute; return "Erase_Fail_Count_Chip"; case 177: + if (hdd) return Unknown_HDD_Attribute; return "Wear_Leveling_Count"; case 178: + if (hdd) return Unknown_HDD_Attribute; return "Used_Rsvd_Blk_Cnt_Chip"; case 179: + if (hdd) return Unknown_HDD_Attribute; return "Used_Rsvd_Blk_Cnt_Tot"; case 180: + if (hdd) return Unknown_HDD_Attribute; return "Unused_Rsvd_Blk_Cnt_Tot"; case 181: return "Program_Fail_Cnt_Total"; case 182: + if (hdd) return Unknown_HDD_Attribute; return "Erase_Fail_Count_Total"; case 183: return "Runtime_Bad_Block"; @@ -1977,6 +2173,7 @@ static const char * get_default_attr_name(unsigned char id) case 188: return "Command_Timeout"; case 189: + if (ssd) return Unknown_SSD_Attribute; return "High_Fly_Writes"; case 190: // Western Digital uses this for temperature. @@ -1988,10 +2185,12 @@ static const char * get_default_attr_name(unsigned char id) // 55C sometime in the past. return "Airflow_Temperature_Cel"; case 191: + if (ssd) return Unknown_SSD_Attribute; return "G-Sense_Error_Rate"; case 192: return "Power-Off_Retract_Count"; case 193: + if (ssd) return Unknown_SSD_Attribute; return "Load_Cycle_Count"; case 194: return "Temperature_Celsius"; @@ -2007,11 +2206,14 @@ static const char * get_default_attr_name(unsigned char id) case 199: return "UDMA_CRC_Error_Count"; case 200: + if (ssd) return Unknown_SSD_Attribute; // Western Digital return "Multi_Zone_Error_Rate"; case 201: + if (ssd) return Unknown_SSD_Attribute; return "Soft_Read_Error_Rate"; case 202: + if (ssd) return Unknown_SSD_Attribute; // Fujitsu: "TA_Increase_Count" return "Data_Address_Mark_Errs"; case 203: @@ -2026,36 +2228,49 @@ static const char * get_default_attr_name(unsigned char id) return "Thermal_Asperity_Rate"; case 206: // Fujitsu + if (ssd) return Unknown_SSD_Attribute; return "Flying_Height"; case 207: // Maxtor + if (ssd) return Unknown_SSD_Attribute; return "Spin_High_Current"; case 208: // Maxtor + if (ssd) return Unknown_SSD_Attribute; return "Spin_Buzz"; case 209: // Maxtor + if (ssd) return Unknown_SSD_Attribute; return "Offline_Seek_Performnce"; case 220: + if (ssd) return Unknown_SSD_Attribute; return "Disk_Shift"; case 221: + if (ssd) return Unknown_SSD_Attribute; return "G-Sense_Error_Rate"; case 222: + if (ssd) return Unknown_SSD_Attribute; return "Loaded_Hours"; case 223: + if (ssd) return Unknown_SSD_Attribute; return "Load_Retry_Count"; case 224: + if (ssd) return Unknown_SSD_Attribute; return "Load_Friction"; case 225: + if (ssd) return Unknown_SSD_Attribute; return "Load_Cycle_Count"; case 226: + if (ssd) return Unknown_SSD_Attribute; return "Load-in_Time"; case 227: + if (ssd) return Unknown_SSD_Attribute; return "Torq-amp_Count"; case 228: return "Power-off_Retract_Count"; case 230: // seen in IBM DTPA-353750 + if (ssd) return Unknown_SSD_Attribute; return "Head_Amplitude"; case 231: return "Temperature_Celsius"; @@ -2064,8 +2279,10 @@ static const char * get_default_attr_name(unsigned char id) return "Available_Reservd_Space"; case 233: // seen in Intel X25-E SSD + if (hdd) return Unknown_HDD_Attribute; return "Media_Wearout_Indicator"; case 240: + if (ssd) return Unknown_SSD_Attribute; return "Head_Flying_Hours"; case 241: return "Total_LBAs_Written"; @@ -2074,6 +2291,7 @@ static const char * get_default_attr_name(unsigned char id) case 250: return "Read_Error_Retry_Rate"; case 254: + if (ssd) return Unknown_SSD_Attribute; return "Free_Fall_Sensor"; default: return "Unknown_Attribute"; @@ -2081,12 +2299,13 @@ static const char * get_default_attr_name(unsigned char id) } // Get attribute name -std::string ata_get_smart_attr_name(unsigned char id, const ata_vendor_attr_defs & defs) +std::string ata_get_smart_attr_name(unsigned char id, const ata_vendor_attr_defs & defs, + int rpm /* = 0 */) { if (!defs[id].name.empty()) return defs[id].name; else - return get_default_attr_name(id); + return get_default_attr_name(id, rpm); } // Find attribute index for attribute id, -1 if not found. @@ -2105,21 +2324,24 @@ int ata_find_attr_index(unsigned char id, const ata_smart_values & smartval) // non-default interpretations. If the Attribute does not exist, return 0 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}; + for (int i = 0; i < 4; i++) { + static const unsigned char ids[4] = {194, 190, 9, 220}; unsigned char id = ids[i]; const ata_attr_raw_format format = defs[id].raw_format; - if (!( (id == 194 && format == RAWFMT_DEFAULT) + if (!( ((id == 194 || id == 190) && format == RAWFMT_DEFAULT) || format == RAWFMT_TEMPMINMAX || format == RAWFMT_TEMP10X)) continue; int idx = ata_find_attr_index(id, *data); if (idx < 0) continue; 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 + unsigned temp; + // ignore possible min/max values in high words if (format == RAWFMT_TEMP10X) // -v N,temp10x - temp = (temp+5) / 10; - if (!(0 < temp && temp <= 255)) + temp = ((unsigned short)raw + 5) / 10; + else + temp = (unsigned char)raw; + if (!(0 < temp && temp < 128)) continue; return temp; } @@ -2134,7 +2356,7 @@ int ataReadSCTStatus(ata_device * device, ata_sct_status_response * sts) // 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("Read SCT Status failed: %s\n", device->get_errmsg()); return -1; } @@ -2152,7 +2374,7 @@ int ataReadSCTStatus(ata_device * device, ata_sct_status_response * sts) // Check format version if (!(sts->format_version == 2 || sts->format_version == 3)) { - pout("Error unknown SCT Status format version %u, should be 2 or 3.\n", sts->format_version); + pout("Unknown SCT Status format version %u, should be 2 or 3.\n", sts->format_version); return -1; } return 0; @@ -2180,16 +2402,23 @@ int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table * 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("Write SCT Data Table 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("Read SCT Data Table failed: %s\n", device->get_errmsg()); return -1; } @@ -2198,7 +2427,7 @@ int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table * 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("Unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n", sts->ext_status_code, sts->action_code, sts->function_code); return -1; } @@ -2208,12 +2437,8 @@ int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table * swapx(&tmh->format_version); swapx(&tmh->sampling_period); swapx(&tmh->interval); - } - - // Check format version - if (tmh->format_version != 2) { - pout("Error unknown SCT Temperature History Format Version (%u), should be 2.\n", tmh->format_version); - return -1; + swapx(&tmh->cb_index); + swapx(&tmh->cb_size); } return 0; } @@ -2242,9 +2467,18 @@ int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persisten 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("Write SCT Feature Control Command failed: %s\n", device->get_errmsg()); return -1; } @@ -2253,22 +2487,140 @@ int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persisten return -1; if (!(sts.ext_status_code == 0 && sts.action_code == 4 && sts.function_code == 1)) { - pout("Error unexcepted SCT status 0x%04x (action_code=%u, function_code=%u)\n", + pout("Unexpected SCT status 0x%04x (action_code=%u, function_code=%u)\n", + sts.ext_status_code, sts.action_code, sts.function_code); + 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("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("Unexpected 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("SMART WRITE LOG does not return COUNT and LBA_LOW register\n"); + return -1; + } + if ( out.out_regs.sector_count == in.in_regs.sector_count + && out.out_regs.lba_low == in.in_regs.lba_low ) { + // 0xe001 (5734.5s) - this is most likely a broken ATA pass-through implementation + pout("SMART WRITE LOG returns COUNT and LBA_LOW register unchanged\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; @@ -2282,30 +2634,26 @@ bool ataPrintSmartSelfTestEntry(unsigned testnum, unsigned char test_type, 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; @@ -2313,15 +2661,16 @@ bool ataPrintSmartSelfTestEntry(unsigned testnum, unsigned char test_type, } 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, "-"); + else { + msglba[0] = '-'; msglba[1] = 0; + } - 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. @@ -2329,11 +2678,11 @@ bool ataPrintSmartSelfTestEntry(unsigned testnum, unsigned char test_type, // bottom 8 bits: number of entries found where self-test showed an error // remaining bits: if nonzero, power on hours of last self-test where error was found int ataPrintSmartSelfTestlog(const ata_smart_selftestlog * data, bool allentries, - unsigned char fix_firmwarebug) + firmwarebug_defs firmwarebugs) { if (allentries) pout("SMART Self-test log structure revision number %d\n",(int)data->revnumber); - if ((data->revnumber!=0x0001) && allentries && fix_firmwarebug != FIX_SAMSUNG) + if (data->revnumber != 0x0001 && allentries && !firmwarebugs.is_set(BUG_SAMSUNG)) pout("Warning: ATA Specification requires self-test log structure revision number = 1\n"); if (data->mostrecenttest==0){ if (allentries) @@ -2342,7 +2691,8 @@ int ataPrintSmartSelfTestlog(const ata_smart_selftestlog * data, bool allentries } 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--) { @@ -2370,24 +2720,38 @@ int ataPrintSmartSelfTestlog(const ata_smart_selftestlog * data, bool allentries uint64_t lba48 = (log->lbafirstfailure < 0xffffffff ? log->lbafirstfailure : 0xffffffffffffULL); // Print entry - if (ataPrintSmartSelfTestEntry(testno, - log->selftestnumber, log->selfteststatus, - log->timestamp, lba48, !allentries, noheaderprinted)) { + int state = ataPrintSmartSelfTestEntry(testno, + log->selftestnumber, log->selfteststatus, + log->timestamp, lba48, !allentries, noheaderprinted); + if (state < 0) { // Self-test showed an error - retval++; + if (ext_ok_testno < 0) { + errcnt++; - // keep track of time of most recent error - if (!hours) - hours = log->timestamp; + // 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); } @@ -2532,9 +2896,7 @@ bool parsed_ata_device::open() ")"; // ) // 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;