]> git.proxmox.com Git - mirror_smartmontools-debian.git/blobdiff - atacmds.cpp
import smartmontools 7.0
[mirror_smartmontools-debian.git] / atacmds.cpp
index 629ff2e314b70a23f9e392764a0164c8e6900be5..e708e6bab857e007c26cdab1f8f8033060f7d484 100644 (file)
@@ -1,41 +1,32 @@
 /*
  * atacmds.cpp
  * 
- * Home page of code is: http://smartmontools.sourceforge.net
+ * Home page of code is: http://www.smartmontools.org
  *
- * Copyright (C) 2002-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
- * Copyright (C) 2008-13 Christian Franke <smartmontools-support@lists.sourceforge.net>
+ * Copyright (C) 2002-11 Bruce Allen
+ * Copyright (C) 2008-18 Christian Franke
  * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
  * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
  *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2, or (at your option)
- * any later version.
- *
- * You should have received a copy of the GNU General Public License
- * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
- *
- * This code was originally developed as a Senior Thesis by Michael Cornwell
- * at the Concurrent Systems Laboratory (now part of the Storage Systems
- * Research Center), Jack Baskin School of Engineering, University of
- * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
- * 
+ * SPDX-License-Identifier: GPL-2.0-or-later
  */
 
+#include "config.h"
+#define __STDC_FORMAT_MACROS 1 // enable PRI* for C++
+
+#include <inttypes.h>
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
 #include <stdlib.h>
 #include <ctype.h>
 
-#include "config.h"
-#include "int64.h"
 #include "atacmds.h"
+#include "knowndrives.h"  // get_default_attr_defs()
 #include "utility.h"
 #include "dev_ata_cmd_set.h" // for parsed_ata_device
 
-const char * atacmds_cpp_cvsid = "$Id: atacmds.cpp 3825 2013-07-06 21:38:25Z samm2 $"
+const char * atacmds_cpp_cvsid = "$Id: atacmds.cpp 4842 2018-12-02 16:07:26Z chrfranke $"
                                  ATACMDS_H_CVSID;
 
 // Print ATA debug messages?
@@ -51,7 +42,7 @@ bool dont_print_serial_number = false;
 
 // SMART RETURN STATUS yields SMART_CYL_HI,SMART_CYL_LOW to indicate drive
 // is healthy and SRET_STATUS_HI_EXCEEDED,SRET_STATUS_MID_EXCEEDED to
-// indicate that a threshhold exceeded condition has been detected.
+// indicate that a threshold exceeded condition has been detected.
 // Those values (byte pairs) are placed in ATA register "LBA 23:8".
 #define SRET_STATUS_HI_EXCEEDED 0x2C
 #define SRET_STATUS_MID_EXCEEDED 0xF4
@@ -134,7 +125,7 @@ const format_name_entry format_names[] = {
 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] = {
+const char * const 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"},
@@ -170,21 +161,26 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
   // Parse option
   int len = strlen(opt);
   int id = 0, n1 = -1, n2 = -1;
-  char fmtname[32+1], attrname[32+1];
+  char fmtname[32+1], attrname[32+1], hddssd[3+1];
+  attrname[0] = hddssd[0] = 0;
+
   if (opt[0] == 'N') {
-    // "N,format"
+    // "N,format[,name]"
     if (!(   sscanf(opt, "N,%32[^,]%n,%32[^,]%n", fmtname, &n1, attrname, &n2) >= 1
           && (n1 == len || n2 == len)))
       return false;
   }
   else {
-    // "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)))
+    // "id,format[+][,name[,HDD|SSD]]"
+    int n3 = -1;
+    if (!(   sscanf(opt, "%d,%32[^,]%n,%32[^,]%n,%3[DHS]%n",
+                    &id, fmtname, &n1, attrname, &n2, hddssd, &n3) >= 2
+          && 1 <= id && id <= 255
+          && (    n1 == len || n2 == len
+                  // ",HDD|SSD" for DEFAULT settings only
+              || (n3 == len && priority == PRIOR_DEFAULT))))
       return false;
   }
-  if (n1 == len)
-    attrname[0] = 0;
 
   unsigned flags = 0;
   // For "-v 19[78],increasing" above
@@ -196,6 +192,10 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
   // Split "format[:byteorder]"
   char byteorder[8+1] = "";
   if (strchr(fmtname, ':')) {
+    if (priority == PRIOR_DEFAULT)
+      // TODO: Allow Byteorder in DEFAULT entry
+      return false;
+    n1 = n2 = -1;
     if (!(   sscanf(fmtname, "%*[^:]%n:%8[012345rvwz]%n", &n1, byteorder, &n2) >= 1
           && n2 == (int)strlen(fmtname)))
       return false;
@@ -219,6 +219,16 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
   if (!*byteorder && (format == RAWFMT_RAW64 || format == RAWFMT_HEX64))
     flags |= (ATTRFLAG_NO_NORMVAL|ATTRFLAG_NO_WORSTVAL);
 
+  // ",HDD|SSD" suffix for DEFAULT settings
+  if (hddssd[0]) {
+    if (!strcmp(hddssd, "HDD"))
+      flags |= ATTRFLAG_HDD_ONLY;
+    else if (!strcmp(hddssd, "SSD"))
+      flags |= ATTRFLAG_SSD_ONLY;
+    else
+      return false;
+  }
+
   if (!id) {
     // "N,format" -> set format for all entries
     for (i = 0; i < MAX_ATTRIBUTE_NUM; i++) {
@@ -247,7 +257,7 @@ bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
 
 
 // Return a multiline string containing a list of valid arguments for
-// parse_attribute_def().  The strings are preceeded by tabs and followed
+// parse_attribute_def().  The strings are preceded by tabs and followed
 // (except for the last) by newlines.
 std::string create_vendor_attribute_arg_list()
 {
@@ -319,6 +329,16 @@ void swap8(char *location){
   return;
 }
 
+// When using the overloaded swapx() function with member of packed ATA structs,
+// it is required to pass a possibly unaligned pointer as argument.
+// Clang++ 4.0 prints -Waddress-of-packed-member warning in this case.
+// The SWAPV() macro below is a replacement which prevents the use of such pointers.
+template <typename T>
+static T get_swapx_val(T x)
+  { swapx(&x); return x; }
+
+#define SWAPV(x)  ((x) = get_swapx_val(x))
+
 // Invalidate serial number and WWN and adjust checksum in IDENTIFY data
 static void invalidate_serno(ata_identify_device * id)
 {
@@ -332,17 +352,12 @@ static void invalidate_serno(ata_identify_device * id)
     sum += b[i]; sum -= b[i] = 0x00;
   }
 
-#ifndef __NetBSD__
-  bool must_swap = !!isbigendian();
-  if (must_swap)
-    swapx(id->words088_255+255-88);
-#endif
+  if (isbigendian())
+    SWAPV(id->words088_255[255-88]);
   if ((id->words088_255[255-88] & 0x00ff) == 0x00a5)
     id->words088_255[255-88] += sum << 8;
-#ifndef __NetBSD__
-  if (must_swap)
-    swapx(id->words088_255+255-88);
-#endif
+  if (isbigendian())
+    SWAPV(id->words088_255[255-88]);
 }
 
 static const char * const commandstrings[]={
@@ -518,6 +533,7 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele
         break;
       case STATUS_CHECK:
         in.out_needed.lba_high = in.out_needed.lba_mid = true; // Status returned here
+        /* FALLTHRU */
       case STATUS:
         in.in_regs.features = ATA_SMART_STATUS;
         break;
@@ -598,8 +614,7 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele
                  "probable SAT/USB truncation\n");
         }
         else if (!out.out_regs.is_set()) {
-          pout("SMART STATUS RETURN: incomplete response, ATA output registers missing\n");
-          device->set_err(ENOSYS);
+          device->set_err(ENOSYS, "Incomplete response, ATA output registers missing");
           retval = -1;
         }
         else {
@@ -608,7 +623,7 @@ int smartcommandhandler(ata_device * device, smart_command_set command, int sele
           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);
+          device->set_err(ENOSYS, "Invalid ATA output register values");
           retval = -1;
         }
         break;
@@ -617,7 +632,7 @@ 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 && dont_print_serial_number)
-    invalidate_serno((ata_identify_device *)data);
+    invalidate_serno( reinterpret_cast<ata_identify_device *>(data) );
 
   // If reporting is enabled, say what output was produced by the command
   if (ata_debugmode) {
@@ -748,20 +763,9 @@ static void trim(char * out, const char * in)
 // Convenience function for formatting strings from ata_identify_device
 void ata_format_id_string(char * out, const unsigned char * in, int n)
 {
-  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, (const char *)in, n);
-  else
-    swapbytes(tmp, (const char *)in, n);
+  swapbytes(tmp, (const char *)in, n);
   tmp[n] = '\0';
   trim(out, tmp);
 }
@@ -778,9 +782,6 @@ int ataCheckPowerMode(ata_device * device) {
   if ((smartcommandhandler(device, CHECK_POWER_MODE, 0, (char *)&result)))
     return -1;
 
-  if (result!=0 && result!=0x80 && result!=0xff)
-    pout("ataCheckPowerMode(): ATA CHECK POWER MODE returned unknown Sector Count Register value %02x\n", result);
-
   return (int)result;
 }
 
@@ -831,9 +832,9 @@ int ata_read_identity(ata_device * device, ata_identify_device * buf, bool fix_s
     packet = true;
   }
 
-  unsigned i;
   if (fix_swapped_id) {
     // Swap ID strings
+    unsigned i;
     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)
@@ -846,23 +847,17 @@ int ata_read_identity(ata_device * device, ata_identify_device * buf, bool fix_s
   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()){
-    
     // swap various capability words that are needed
+    unsigned i;
     for (i=0; i<33; i++)
       swap2((char *)(buf->words047_079+i));
-    
     for (i=80; i<=87; i++)
       swap2((char *)(rawshort+i));
-    
     for (i=0; i<168; i++)
       swap2((char *)(buf->words088_255+i));
   }
-#endif
   
   // If there is a checksum there, validate it
   if ((rawshort[255] & 0x00ff) == 0x00a5 && checksum(rawbyte))
@@ -987,7 +982,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);
+    SWAPV(data->extend_test_completion_time_w);
     for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++){
       struct ata_smart_attribute *x=data->vendor_attributes+i;
       swap2((char *)&(x->flags));
@@ -1074,15 +1069,45 @@ bool ataReadExtSelfTestLog(ata_device * device, ata_smart_extselftestlog * log,
   check_multi_sector_sum(log, nsectors, "SMART Extended Self-test Log Structure");
 
   if (isbigendian()) {
-    swapx(&log->log_desc_index);
+    SWAPV(log->log_desc_index);
     for (unsigned i = 0; i < nsectors; i++) {
       for (unsigned j = 0; j < 19; j++)
-        swapx(&log->log_descs[i].timestamp);
+        SWAPV(log->log_descs[i].timestamp);
     }
   }
   return true;
 }
 
+// Write GP Log page(s)
+bool ataWriteLogExt(ata_device * device, unsigned char logaddr,
+                    unsigned page, void * data, unsigned nsectors)
+{
+  ata_cmd_in in;
+  in.in_regs.command      = ATA_WRITE_LOG_EXT;
+  in.set_data_out(data, nsectors);
+  in.in_regs.lba_low      = logaddr;
+  in.in_regs.lba_mid_16   = page;
+  in.set_data_out(data, nsectors);
+
+  ata_cmd_out out;
+  if (!device->ata_pass_through(in, out)) { // TODO: Debug output
+    if (nsectors <= 1) {
+      pout("ATA_WRITE_LOG_EXT (addr=0x%02x, page=%u, n=%u) failed: %s\n",
+           logaddr, page, nsectors, device->get_errmsg());
+      return false;
+    }
+
+    // Recurse to retry with single sectors,
+    // multi-sector reads may not be supported by ioctl.
+    for (unsigned i = 0; i < nsectors; i++) {
+      if (!ataWriteLogExt(device, logaddr, page + i,
+                         (char *)data + 512*i, 1))
+        return false;
+    }
+  }
+
+  return true;
+}
 
 // Read GP Log page(s)
 bool ataReadLogExt(ata_device * device, unsigned char logaddr,
@@ -1151,7 +1176,7 @@ int ataReadLogDirectory(ata_device * device, ata_smart_log_directory * data, boo
 
   // swap endian order if needed
   if (isbigendian())
-    swapx(&data->logversion);
+    SWAPV(data->logversion);
 
   return 0;
 }
@@ -1222,7 +1247,7 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg
     int mode = args.span[i].mode;
     uint64_t start = args.span[i].start;
     uint64_t end   = args.span[i].end;
-    if (mode == SEL_CONT) {// redo or next dependig on last test status
+    if (mode == SEL_CONT) {// redo or next depending on last test status
       switch (sv->self_test_exec_status >> 4) {
         case 1: case 2: // Aborted/Interrupted by host
           pout("Continue Selective Self-Test: Redo last span\n");
@@ -1238,7 +1263,7 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg
     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
+      // Some drives do not preserve the selective self-test log across
       // 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;
@@ -1274,9 +1299,9 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg
             uint64_t spans = (num_sectors + oldsize-1) / oldsize;
             uint64_t newsize = (num_sectors + spans-1) / spans;
             uint64_t newstart = num_sectors - newsize, newend = num_sectors - 1;
-            pout("Span %d changed from %"PRIu64"-%"PRIu64" (%"PRIu64" sectors)\n",
+            pout("Span %d changed from %" PRIu64 "-%" PRIu64 " (%" PRIu64 " sectors)\n",
                  i, start, end, oldsize);
-            pout("                 to %"PRIu64"-%"PRIu64" (%"PRIu64" sectors) (%"PRIu64" spans)\n",
+            pout("                 to %" PRIu64 "-%" PRIu64 " (%" PRIu64 " sectors) (%" PRIu64 " spans)\n",
                  newstart, newend, newsize, spans);
             start = newstart; end = newend;
           }
@@ -1293,7 +1318,7 @@ int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_arg
       end = num_sectors - 1;
     }
     if (!(start <= end && end < num_sectors)) {
-      pout("Invalid selective self-test span %d: %"PRIu64"-%"PRIu64" (%"PRIu64" sectors)\n",
+      pout("Invalid selective self-test span %d: %" PRIu64 "-%" PRIu64 " (%" PRIu64 " sectors)\n",
         i, start, end, num_sectors);
       return -1;
     }
@@ -1466,21 +1491,22 @@ static void fix_exterrlog_lba(ata_smart_exterrlog * log, unsigned nsectors)
 
 // Read Extended Comprehensive Error Log
 bool ataReadExtErrorLog(ata_device * device, ata_smart_exterrlog * log,
-                        unsigned nsectors, firmwarebug_defs firmwarebugs)
+                        unsigned page, unsigned nsectors, firmwarebug_defs firmwarebugs)
 {
-  if (!ataReadLogExt(device, 0x03, 0x00, 0, log, nsectors))
+  if (!ataReadLogExt(device, 0x03, 0x00, page, log, nsectors))
     return false;
 
   check_multi_sector_sum(log, nsectors, "SMART Extended Comprehensive Error Log Structure");
 
   if (isbigendian()) {
-    swapx(&log->device_error_count);
-    swapx(&log->error_log_index);
-
+    SWAPV(log->device_error_count);
+    SWAPV(log->error_log_index);
     for (unsigned i = 0; i < nsectors; i++) {
-      for (unsigned j = 0; j < 4; j++)
-        swapx(&log->error_logs[i].commands[j].timestamp);
-      swapx(&log->error_logs[i].error.timestamp);
+      for (unsigned j = 0; j < 4; j++) {
+        for (unsigned k = 0; k < 5; k++)
+           SWAPV(log[i].error_logs[j].commands[k].timestamp);
+        SWAPV(log[i].error_logs[j].error.timestamp);
+      }
     }
   }
 
@@ -1648,7 +1674,7 @@ int ataSmartTest(ata_device * device, int testtype, bool force,
     int i;
     pout("SPAN         STARTING_LBA           ENDING_LBA\n");
     for (i = 0; i < selargs_io.num_spans; i++)
-      pout("   %d %20"PRId64" %20"PRId64"\n", i,
+      pout("   %d %20" PRId64 " %20" PRId64 "\n", i,
            selargs_io.span[i].start,
            selargs_io.span[i].end);
   }
@@ -1704,7 +1730,7 @@ int TestTime(const ata_smart_values *data, int testtype)
 // word 84 and 87.  Top two bits must match the pattern 01. BEFORE
 // ATA-6 these top two bits still had to match the pattern 01, but the
 // remaining bits were reserved (==0).
-int isSmartErrorLogCapable (const ata_smart_values * data, const ata_identify_device * identity)
+bool isSmartErrorLogCapable(const ata_smart_values * data, const ata_identify_device * identity)
 {
   unsigned short word84=identity->command_set_extension;
   unsigned short word87=identity->csf_default;
@@ -1712,18 +1738,18 @@ int isSmartErrorLogCapable (const ata_smart_values * data, const ata_identify_de
   int isata7=identity->major_rev_num & (0x01<<7);
 
   if ((isata6 || isata7) && (word84>>14) == 0x01 && (word84 & 0x01))
-    return 1;
+    return true;
   
   if ((isata6 || isata7) && (word87>>14) == 0x01 && (word87 & 0x01))
-    return 1;
+    return true;
   
   // otherwise we'll use the poorly documented capability bit
-  return data->errorlog_capability & 0x01;
+  return !!(data->errorlog_capability & 0x01);
 }
 
 // See previous function.  If the error log exists then the self-test
 // log should (must?) also exist.
-int isSmartTestLogCapable (const ata_smart_values * data, const ata_identify_device *identity)
+bool isSmartTestLogCapable(const ata_smart_values * data, const ata_identify_device *identity)
 {
   unsigned short word84=identity->command_set_extension;
   unsigned short word87=identity->csf_default;
@@ -1731,18 +1757,18 @@ int isSmartTestLogCapable (const ata_smart_values * data, const ata_identify_dev
   int isata7=identity->major_rev_num & (0x01<<7);
 
   if ((isata6 || isata7) && (word84>>14) == 0x01 && (word84 & 0x02))
-    return 1;
+    return true;
   
   if ((isata6 || isata7) && (word87>>14) == 0x01 && (word87 & 0x02))
-    return 1;
+    return true;
 
 
   // otherwise we'll use the poorly documented capability bit
-  return data->errorlog_capability & 0x01;
+  return !!(data->errorlog_capability & 0x01);
 }
 
 
-int isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
+bool isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
 {
   unsigned short word84=identity->command_set_extension;
   unsigned short word87=identity->csf_default;
@@ -1754,7 +1780,7 @@ int isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
   if ((word84>>14) == 0x01)
     // If bit 5 of word 84 is set to one, the device supports the
     // General Purpose Logging feature set.
-    return (word84 & (0x01 << 5));
+    return !!(word84 & (0x01 << 5));
   
   // If bit 14 of word 87 is set to one and bit 15 of word 87 is
   // cleared to zero, the contents of words (87:85) contain valid
@@ -1762,50 +1788,10 @@ int isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
   if ((word87>>14) == 0x01)
     // If bit 5 of word 87 is set to one, the device supports
     // the General Purpose Logging feature set.
-    return (word87 & (0x01 << 5));
+    return !!(word87 & (0x01 << 5));
 
   // not capable
-  return 0;
-}
-
-
-// SMART self-test capability is also indicated in bit 1 of DEVICE
-// IDENTIFY word 87 (if top two bits of word 87 match pattern 01).
-// However this was only introduced in ATA-6 (but self-test log was in
-// ATA-5).
-int isSupportExecuteOfflineImmediate(const ata_smart_values *data)
-{
-  return data->offline_data_collection_capability & 0x01;
-}
-
-// Note in the ATA-5 standard, the following bit is listed as "Vendor
-// Specific".  So it may not be reliable. The only use of this that I
-// have found is in IBM drives, where it is well-documented.  See for
-// example page 170, section 13.32.1.18 of the IBM Travelstar 40GNX
-// hard disk drive specifications page 164 Revision 1.1 22 Apr 2002.
-int isSupportAutomaticTimer(const ata_smart_values * data)
-{
-  return data->offline_data_collection_capability & 0x02;
-}
-int isSupportOfflineAbort(const ata_smart_values *data)
-{
-  return data->offline_data_collection_capability & 0x04;
-}
-int isSupportOfflineSurfaceScan(const ata_smart_values * data)
-{
-   return data->offline_data_collection_capability & 0x08;
-}
-int isSupportSelfTest (const ata_smart_values * data)
-{
-   return data->offline_data_collection_capability & 0x10;
-}
-int isSupportConveyanceSelfTest(const ata_smart_values * data)
-{
-   return data->offline_data_collection_capability & 0x20;
-}
-int isSupportSelectiveSelfTest(const ata_smart_values * data)
-{
-   return data->offline_data_collection_capability & 0x40;
+  return false;
 }
 
 // Get attribute state
@@ -1858,34 +1844,12 @@ ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr,
   return ATTRSTATE_OK;
 }
 
-// Get default raw value print format
-static ata_attr_raw_format get_default_raw_format(unsigned char id)
-{
-  switch (id) {
-  case 3:   // Spin-up time
-    return RAWFMT_RAW16_OPT_AVG16;
-
-  case 5:   // Reallocated sector count
-  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;
-
-  default:
-    return RAWFMT_RAW48;
-  }
-}
-
 // 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];
+  // TODO: Allow Byteorder in DEFAULT entry
 
   // Use default byteorder if not specified
   const char * byteorder = def.byteorder;
@@ -1926,6 +1890,33 @@ uint64_t ata_get_attr_raw_value(const ata_smart_attribute & attr,
   return rawvalue;
 }
 
+// Helper functions for RAWFMT_TEMPMINMAX
+static inline int check_temp_word(unsigned word)
+{
+  if (word <= 0x7f)
+    return 0x11; // >= 0, signed byte or word
+  if (word <= 0xff)
+    return 0x01; // < 0, signed byte
+  if (0xff80 <= word)
+    return 0x10; // < 0, signed word
+  return 0x00;
+}
+
+static bool check_temp_range(int t, unsigned char ut1, unsigned char ut2,
+                             int & lo, int & hi)
+{
+  int t1 = (signed char)ut1, t2 = (signed char)ut2;
+  if (t1 > t2) {
+    int tx = t1; t1 = t2; t2 = tx;
+  }
+
+  if (   -60 <= t1 && t1 <= t && t <= t2 && t2 <= 120
+      && !(t1 == -1 && t2 <= 0)                      ) {
+    lo = t1; hi = t2;
+    return true;
+  }
+  return false;
+}
 
 // Format attribute raw value.
 std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
@@ -1949,8 +1940,13 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
 
   // Get print format
   ata_attr_raw_format format = defs[attr.id].raw_format;
-  if (format == RAWFMT_DEFAULT)
-    format = get_default_raw_format(attr.id);
+  if (format == RAWFMT_DEFAULT) {
+     // Get format from DEFAULT entry
+     format = get_default_attr_defs()[attr.id].raw_format;
+     if (format == RAWFMT_DEFAULT)
+       // Unknown Attribute
+       format = RAWFMT_RAW48;
+  }
 
   // Print
   std::string s;
@@ -1967,19 +1963,19 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
   case RAWFMT_RAW48:
   case RAWFMT_RAW56:
   case RAWFMT_RAW64:
-    s = strprintf("%"PRIu64, rawvalue);
+    s = strprintf("%" PRIu64, rawvalue);
     break;
 
   case RAWFMT_HEX48:
-    s = strprintf("0x%012"PRIx64, rawvalue);
+    s = strprintf("0x%012" PRIx64, rawvalue);
     break;
 
   case RAWFMT_HEX56:
-    s = strprintf("0x%014"PRIx64, rawvalue);
+    s = strprintf("0x%014" PRIx64, rawvalue);
     break;
 
   case RAWFMT_HEX64:
-    s = strprintf("0x%016"PRIx64, rawvalue);
+    s = strprintf("0x%016" PRIx64, rawvalue);
     break;
 
   case RAWFMT_RAW16_OPT_RAW16:
@@ -2016,7 +2012,7 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
       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);
+      s = strprintf("%" PRIu64 "h+%02" PRIu64 "m", tmp1, tmp2);
       if (word[2])
         s += strprintf(" (%u)", word[2]);
     }
@@ -2028,7 +2024,7 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
       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);
+      s = strprintf("%" PRIu64 "h+%02" PRIu64 "m+%02" PRIu64 "s", hours, minutes, seconds);
     }
     break;
 
@@ -2037,7 +2033,7 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
       // 30-second counter
       int64_t hours = rawvalue/120;
       int64_t minutes = (rawvalue-120*hours)/2;
-      s += strprintf("%"PRIu64"h+%02"PRIu64"m", hours, minutes);
+      s += strprintf("%" PRIu64 "h+%02" PRIu64 "m", hours, minutes);
     }
     break;
 
@@ -2056,34 +2052,63 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
     // Temperature
     {
       // Search for possible min/max values
-      // 00 HH 00 LL 00 TT (Hitachi/IBM)
-      // 00 00 HH LL 00 TT (Maxtor, Samsung)
+      // [5][4][3][2][1][0] raw[]
+      // [ 2 ] [ 1 ] [ 0 ]  word[]
+      // xx HH xx LL xx TT (Hitachi/HGST)
+      // xx LL xx HH xx TT (Kingston SSDs)
+      // 00 00 HH LL xx TT (Maxtor, Samsung, Seagate, Toshiba)
       // 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;
-          }
+      // CC CC HH LL xx TT (WDC, CCCC=over temperature count)
+      // (xx = 00/ff, possibly sign extension of lower byte)
+
+      int t = (signed char)raw[0];
+      int lo = 0, hi = 0;
+
+      int tformat;
+      int ctw0 = check_temp_word(word[0]);
+      if (!word[2]) {
+        if (!word[1] && ctw0)
+          // 00 00 00 00 xx TT
+          tformat = 0;
+        else if (ctw0 && check_temp_range(t, raw[2], raw[3], lo, hi))
+          // 00 00 HL LH xx TT
+          tformat = 1;
+        else if (!raw[3] && check_temp_range(t, raw[1], raw[2], lo, hi))
+          // 00 00 00 HL LH TT
+          tformat = 2;
+        else
+          tformat = -1;
+      }
+      else if (ctw0) {
+        if (   (ctw0 & check_temp_word(word[1]) & check_temp_word(word[2])) != 0x00
+            && check_temp_range(t, raw[2], raw[4], lo, hi)                         )
+          // xx HL xx LH xx TT
+          tformat = 3;
+        else if (   word[2] < 0x7fff
+                 && check_temp_range(t, raw[2], raw[3], lo, hi)
+                 && hi >= 40                                   )
+          // CC CC HL LH xx TT
+          tformat = 4;
+        else
+          tformat = -2;
       }
-
-      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 %d %d)", t, raw[5], raw[4], raw[3], raw[2], raw[1]);
+        tformat = -3;
+
+      switch (tformat) {
+        case 0:
+          s = strprintf("%d", t);
+          break;
+        case 1: case 2: case 3:
+          s = strprintf("%d (Min/Max %d/%d)", t, lo, hi);
+          break;
+        case 4:
+          s = strprintf("%d (Min/Max %d/%d #%d)", t, lo, hi, word[2]);
+          break;
+        default:
+          s = strprintf("%d (%d %d %d %d %d)", raw[0], raw[5], raw[4], raw[3], raw[2], raw[1]);
+          break;
+      }
     }
     break;
 
@@ -2100,212 +2125,23 @@ std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
   return s;
 }
 
-// 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, 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";
-  case 2:
-    return "Throughput_Performance";
-  case 3:
-    return "Spin_Up_Time";
-  case 4:
-    return "Start_Stop_Count";
-  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";
-  case 184:
-    return "End-to-End_Error";
-  case 187:
-    return "Reported_Uncorrect";
-  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.
-    // It's identical to Attribute 194 except that it
-    // has a failure threshold set to correspond to the
-    // max allowed operating temperature of the drive, which 
-    // is typically 55C.  So if this attribute has failed
-    // in the past, it indicates that the drive temp exceeded
-    // 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";
-  case 195:
-    // Fujitsu: "ECC_On_The_Fly_Count";
-    return "Hardware_ECC_Recovered";
-  case 196:
-    return "Reallocated_Event_Count";
-  case 197:
-    return "Current_Pending_Sector";
-  case 198:
-    return "Offline_Uncorrectable";
-  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:
-    // Fujitsu
-    return "Run_Out_Cancel";
-    // Maxtor: ECC Errors
-  case 204:
-    // Fujitsu: "Shock_Count_Write_Opern"
-    return "Soft_ECC_Correction";
-  case 205:
-    // Fujitsu: "Shock_Rate_Write_Opern"
-    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";
-  case 232:
-    // seen in Intel X25-E SSD
-    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";
-  case 242:
-    return "Total_LBAs_Read";
-  case 250:
-    return "Read_Error_Retry_Rate";
-  case 254:
-    if (ssd) return Unknown_SSD_Attribute;
-    return "Free_Fall_Sensor";
-  default:
-    return "Unknown_Attribute";
-  }
-}
-
 // Get attribute name
 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, rpm);
+  else {
+     const ata_vendor_attr_defs::entry & def = get_default_attr_defs()[id];
+     if (def.name.empty())
+       return "Unknown_Attribute";
+     else if ((def.flags & ATTRFLAG_HDD_ONLY) && rpm == 1)
+       return "Unknown_SSD_Attribute";
+     else if ((def.flags & ATTRFLAG_SSD_ONLY) && rpm > 1)
+       return "Unknown_HDD_Attribute";
+     else
+       return def.name;
+  }
 }
 
 // Find attribute index for attribute id, -1 if not found.
@@ -2362,14 +2198,16 @@ int ataReadSCTStatus(ata_device * device, ata_sct_status_response * sts)
 
   // swap endian order if needed
   if (isbigendian()){
-    swapx(&sts->format_version);
-    swapx(&sts->sct_version);
-    swapx(&sts->sct_spec);
-    swapx(&sts->ext_status_code);
-    swapx(&sts->action_code);
-    swapx(&sts->function_code);
-    swapx(&sts->over_limit_count);
-    swapx(&sts->under_limit_count);
+    SWAPV(sts->format_version);
+    SWAPV(sts->sct_version);
+    SWAPV(sts->sct_spec);
+    SWAPV(sts->ext_status_code);
+    SWAPV(sts->action_code);
+    SWAPV(sts->function_code);
+    SWAPV(sts->over_limit_count);
+    SWAPV(sts->under_limit_count);
+    SWAPV(sts->smart_status);
+    SWAPV(sts->min_erc_time);
   }
 
   // Check format version
@@ -2380,13 +2218,11 @@ int ataReadSCTStatus(ata_device * device, ata_sct_status_response * sts)
   return 0;
 }
 
-// Read SCT Temperature History Table and Status
+// Read SCT Temperature History Table
 int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table * tmh,
                        ata_sct_status_response * sts)
 {
-  // Check initial status
-  if (ataReadSCTStatus(device, sts))
-    return -1;
+  // Initial SCT status must be provided by caller
 
   // Do nothing if other SCT command is executing
   if (sts->ext_status_code == 0xffff) {
@@ -2404,9 +2240,9 @@ int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table *
 
   // swap endian order if needed
   if (isbigendian()) {
-    swapx(&cmd.action_code);
-    swapx(&cmd.function_code);
-    swapx(&cmd.table_id);
+    SWAPV(cmd.action_code);
+    SWAPV(cmd.function_code);
+    SWAPV(cmd.table_id);
   }
 
   // write command via SMART log page 0xe0
@@ -2434,17 +2270,19 @@ int ataReadSCTTempHist(ata_device * device, ata_sct_temperature_history_table *
 
   // swap endian order if needed
   if (isbigendian()){
-    swapx(&tmh->format_version);
-    swapx(&tmh->sampling_period);
-    swapx(&tmh->interval);
-    swapx(&tmh->cb_index);
-    swapx(&tmh->cb_size);
+    SWAPV(tmh->format_version);
+    SWAPV(tmh->sampling_period);
+    SWAPV(tmh->interval);
+    SWAPV(tmh->cb_index);
+    SWAPV(tmh->cb_size);
   }
   return 0;
 }
 
-// Get/Set Write Cache Reordering
-int ataGetSetSCTWriteCacheReordering(ata_device * device, bool enable, bool persistent, bool set)
+// Common function for Get/Set SCT Feature Control:
+// Write Cache, Write Cache Reordering, etc.
+static int ataGetSetSCTFeatureControl(ata_device * device, unsigned short feature_code,
+                                      unsigned short state, bool persistent, bool set)
 {
   // Check initial status
   ata_sct_status_response sts;
@@ -2463,17 +2301,17 @@ int ataGetSetSCTWriteCacheReordering(ata_device * device, bool enable, bool pers
   // CAUTION: DO NOT CHANGE THIS VALUE (SOME ACTION CODES MAY ERASE DISK)
   cmd.action_code   = 4; // Feature Control command
   cmd.function_code  = (set ? 1 : 2); // 1=Set, 2=Get
-  cmd.feature_code  = 2; //  Enable/Disable Write Cache Reordering 
-  cmd.state         = (enable ? 1 : 2); // 1 enable, 2 disable
+  cmd.feature_code  = feature_code;
+  cmd.state         = state;
   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);
+    SWAPV(cmd.action_code);
+    SWAPV(cmd.function_code);
+    SWAPV(cmd.feature_code);
+    SWAPV(cmd.state);
+    SWAPV(cmd.option_flags);
   }
 
   // write command via SMART log page 0xe0
@@ -2491,11 +2329,11 @@ int ataGetSetSCTWriteCacheReordering(ata_device * device, bool enable, bool pers
 
   ata_cmd_out out;
   if (!device->ata_pass_through(in, out)) {
-    pout("Write SCT (%cet) XXX Error Recovery Control Command failed: %s\n",
+    pout("Write SCT (%cet) Feature Control Command failed: %s\n",
       (!set ? 'G' : 'S'), device->get_errmsg());
     return -1;
   }
-  int state = out.out_regs.sector_count | (out.out_regs.lba_low << 8);
+  state = out.out_regs.sector_count | (out.out_regs.lba_low << 8);
 
   // re-read and check SCT status
   if (ataReadSCTStatus(device, &sts))
@@ -2509,6 +2347,19 @@ int ataGetSetSCTWriteCacheReordering(ata_device * device, bool enable, bool pers
   return state;
 }
 
+// Get/Set Write Cache Reordering
+int ataGetSetSCTWriteCacheReordering(ata_device * device, bool enable, bool persistent, bool set)
+{
+  return ataGetSetSCTFeatureControl(device, 2 /* Enable/Disable Write Cache Reordering */,
+                                    (enable ? 1 : 2), persistent, set);
+}
+
+// Get/Set Write Cache (force enable, force disable,
+int ataGetSetSCTWriteCache(ata_device * device, unsigned short state, bool persistent, bool set)
+{
+  return ataGetSetSCTFeatureControl(device, 1 /* Enable/Disable Write Cache */,
+                                    state, persistent, set);
+}
 
 // Set SCT Temperature Logging Interval
 int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persistent)
@@ -2536,11 +2387,11 @@ int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persisten
 
   // 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);
+    SWAPV(cmd.action_code);
+    SWAPV(cmd.function_code);
+    SWAPV(cmd.feature_code);
+    SWAPV(cmd.state);
+    SWAPV(cmd.option_flags);
   }
 
   // write command via SMART log page 0xe0
@@ -2588,10 +2439,10 @@ static int ataGetSetSCTErrorRecoveryControltime(ata_device * device, unsigned ty
 
   // swap endian order if needed
   if (isbigendian()) {
-    swapx(&cmd.action_code);
-    swapx(&cmd.function_code);
-    swapx(&cmd.selection_code);
-    swapx(&cmd.time_limit);
+    SWAPV(cmd.action_code);
+    SWAPV(cmd.function_code);
+    SWAPV(cmd.selection_code);
+    SWAPV(cmd.time_limit);
   }
 
   // write command via SMART log page 0xe0
@@ -2659,169 +2510,6 @@ int ataSetSCTErrorRecoveryControltime(ata_device * device, unsigned type, unsign
 }
 
 
-// Print one self-test log entry.
-// 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 0x02: msgtest = "Extended offline";   break;
-    case 0x03: msgtest = "Conveyance offline"; break;
-    case 0x04: msgtest = "Selective offline";  break;
-    case 0x7f: msgtest = "Abort offline test"; break;
-    case 0x81: msgtest = "Short captive";      break;
-    case 0x82: msgtest = "Extended captive";   break;
-    case 0x83: msgtest = "Conveyance captive"; break;
-    case 0x84: msgtest = "Selective captive";  break;
-    default:
-      if ((0x40 <= test_type && test_type <= 0x7e) || 0x90 <= test_type)
-        msgtest = strprintf("Vendor (0x%02x)", test_type);
-      else
-        msgtest = strprintf("Reserved (0x%02x)", test_type);
-  }
-
-  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";        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 = strprintf("Unknown status (0x%x)", test_status >> 4);
-  }
-
-  // Print header once
-  if (print_header) {
-    print_header = false;
-    pout("Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error\n");
-  }
-
-  char msglba[32];
-  if (retval < 0 && failing_lba < 0xffffffffffffULL)
-    snprintf(msglba, sizeof(msglba), "%"PRIu64, failing_lba);
-  else {
-    msglba[0] = '-'; msglba[1] = 0;
-  }
-
-  pout("#%2u  %-19s %-29s %1d0%%  %8u         %s\n", testnum,
-       msgtest.c_str(), msgstat.c_str(), test_status & 0x0f, timestamp, msglba);
-
-  return retval;
-}
-
-// Print Smart self-test log, used by smartctl and smartd.
-// return value is:
-// 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,
-                             firmwarebug_defs firmwarebugs)
-{
-  if (allentries)
-    pout("SMART Self-test log structure revision number %d\n",(int)data->revnumber);
-  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)
-      pout("No self-tests have been logged.  [To run self-tests, use: smartctl -t]\n\n");
-    return 0;
-  }
-
-  bool noheaderprinted = true;
-  int errcnt = 0, hours = 0, igncnt = 0;
-  int testno = 0, ext_ok_testno = -1;
-
-  // print log
-  for (int i = 20; i >= 0; i--) {
-    // log is a circular buffer
-    int j = (i+data->mostrecenttest)%21;
-    const ata_smart_selftestlog_struct * log = data->selftest_struct+j;
-
-    if (nonempty(log, sizeof(*log))) {
-      // count entry based on non-empty structures -- needed for
-      // Seagate only -- other vendors don't have blank entries 'in
-      // the middle'
-      testno++;
-
-      // T13/1321D revision 1c: (Data structure Rev #1)
-
-      //The failing LBA shall be the LBA of the uncorrectable sector
-      //that caused the test to fail. If the device encountered more
-      //than one uncorrectable sector during the test, this field
-      //shall indicate the LBA of the first uncorrectable sector
-      //encountered. If the test passed or the test failed for some
-      //reason other than an uncorrectable sector, the value of this
-      //field is undefined.
-
-      // This is true in ALL ATA-5 specs
-      uint64_t lba48 = (log->lbafirstfailure < 0xffffffff ? log->lbafirstfailure : 0xffffffffffffULL);
-
-      // Print entry
-      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 (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");
-
-  return ((hours << 8) | errcnt);
-}
-
-
 /////////////////////////////////////////////////////////////////////////////
 // Pseudo-device to parse "smartctl -r ataioctl,2 ..." output and simulate
 // an ATA device with same behaviour
@@ -2885,7 +2573,8 @@ static int name2command(const char * s)
   return -1;
 }
 
-static bool matchcpy(char * dest, size_t size, const char * src, const regmatch_t & srcmatch)
+static bool matchcpy(char * dest, size_t size, const char * src,
+  const regular_expression::match_range & srcmatch)
 {
   if (srcmatch.rm_so < 0)
     return false;
@@ -2897,7 +2586,7 @@ static bool matchcpy(char * dest, size_t size, const char * src, const regmatch_
   return true;
 }
 
-static inline int matchtoi(const char * src, const regmatch_t & srcmatch, int defval)
+static inline int matchtoi(const char * src, const regular_expression::match_range & srcmatch, int defval)
 {
   if (srcmatch.rm_so < 0)
     return defval;
@@ -2916,7 +2605,7 @@ parsed_ata_device::parsed_ata_device(smart_interface * intf, const char * dev_na
 
 parsed_ata_device::~parsed_ata_device() throw()
 {
-  close();
+  parsed_ata_device::close();
 }
 
 bool parsed_ata_device::is_open() const
@@ -2963,7 +2652,7 @@ bool parsed_ata_device::open()
   ")"; // )
 
   // Compile regex
-  const regular_expression regex(pattern, REG_EXTENDED);
+  const regular_expression regex(pattern);
 
   // Parse buffer
   const char * errmsg = 0;
@@ -2973,7 +2662,7 @@ bool parsed_ata_device::open()
     if (!(line[0] == 'R' || line[0] == '=' || line[0] == ' '))
       continue;
     const int nmatch = 1+11;
-    regmatch_t match[nmatch];
+    regular_expression::match_range match[nmatch];
     if (!regex.execute(line, nmatch, match))
       continue;