]> git.proxmox.com Git - mirror_smartmontools-debian.git/blobdiff - atacmds.cpp
import smartmontools 7.0
[mirror_smartmontools-debian.git] / atacmds.cpp
index b113373a40961254ecebacbb1dbedc6a0f438181..e708e6bab857e007c26cdab1f8f8033060f7d484 100644 (file)
 /*
  * atacmds.cpp
  * 
- * Home page of code is: http://smartmontools.sourceforge.net
+ * Home page of code is: http://www.smartmontools.org
  *
- * Copyright (C) 2002-8 Bruce Allen <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, write to the Free
- * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- * 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 "scsiata.h"
-#include "extern.h"
+#include "knowndrives.h"  // get_default_attr_defs()
 #include "utility.h"
+#include "dev_ata_cmd_set.h" // for parsed_ata_device
 
-const char *atacmds_c_cvsid="$Id: atacmds.cpp,v 1.190 2008/03/04 22:09:47 ballen4705 Exp $"
-ATACMDS_H_CVSID CONFIG_H_CVSID EXTERN_H_CVSID INT64_H_CVSID SCSIATA_H_CVSID UTILITY_H_CVSID;
-
-// to hold onto exit code for atexit routine
-extern int exitstatus;
-
-// for passing global control variables
-extern smartmonctrl *con;
-
-// 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
-const char *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       */
-};
+const char * atacmds_cpp_cvsid = "$Id: atacmds.cpp 4842 2018-12-02 16:07:26Z chrfranke $"
+                                 ATACMDS_H_CVSID;
 
-// 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
-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:        */
-};
+// Print ATA debug messages?
+unsigned char ata_debugmode = 0;
 
-// When you add additional items to this list, you should then:
-// 0 -- update this list
-// 1 -- modify the following function parse_attribute_def()
-// 2 -- if needed, modify ataPrintSmartAttribRawValue()
-// 3 -  if needed, modify ataPrintSmartAttribName()
-// 4 -- add #define PRESET_N_DESCRIPTION at top of knowndrives.c
-// 5 -- add drive in question into knowndrives[] table in knowndrives.c
-// 6 -- update smartctl.8
-// 7 -- update smartd.8
-// 8 -- do "make smartd.conf.5" to update smartd.conf.5
-// 9 -- update CHANGELOG file
-const char *vendorattributeargs[] = {
-  // 0  defs[9]=1
-  "9,minutes",
-  // 1  defs[9]=3
-  "9,seconds",
-  // 2  defs[9]=2
-  "9,temp",
-  // 3  defs[220]=1
-  "220,temp",
-  // 4  defs[*]=253
-  "N,raw8",
-  // 5  defs[*]=254
-  "N,raw16",
-  // 6  defs[*]=255
-  "N,raw48",
-  // 7  defs[200]=1
-  "200,writeerrorcount",
-  // 8  defs[9]=4
-  "9,halfminutes",
-  // 9  defs[194]=1
-  "194,10xCelsius",
-  // 10 defs[194]=2
-  "194,unknown",
-  // 11 defs[193]=1
-  "193,loadunload",
-  // 12 defs[201]=1
-  "201,detectedtacount",
-  // 13 defs[192]=1
-  "192,emergencyretractcyclect",
-  // 14 defs[198]=1
-  "198,offlinescanuncsectorct",
-  // NULL should always terminate the array
-  NULL
-};
+// Suppress serial number?
+// (also used in scsiprint.cpp)
+bool dont_print_serial_number = false;
+
+
+#define SMART_CYL_LOW  0x4F
+#define SMART_CYL_HI   0xC2
+
+// 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 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
+
+
+// Get ID and increase flag of current pending or offline
+// uncorrectable attribute.
+unsigned char get_unc_attr_id(bool offline, const ata_vendor_attr_defs & defs,
+                              bool & increase)
+{
+  unsigned char id = (!offline ? 197 : 198);
+  const ata_vendor_attr_defs::entry & def = defs[id];
+  if (def.flags & ATTRFLAG_INCREASING)
+    increase = true; // '-v 19[78],increasing' option
+  else if (def.name.empty() || (id == 198 && def.name == "Offline_Scan_UNC_SectCt"))
+    increase = false; // no or '-v 198,offlinescanuncsectorct' option
+  else
+    id = 0; // other '-v 19[78],...' option
+  return id;
+}
 
+#if 0 // TODO: never used
 // This are the meanings of the Self-test failure checkpoint byte.
 // This is in the self-test log at offset 4 bytes into the self-test
 // descriptor and in the SMART READ DATA structure at byte offset
@@ -209,282 +90,216 @@ const char *SelfTestFailureCodeName(unsigned char which){
     return NULL;
   }
 }
+#endif
 
-// This is a utility function for parsing pairs like "9,minutes" or
-// "220,temp", and putting the correct flag into the attributedefs
-// array.  Returns 1 if problem, 0 if pair has been recongized.
-int parse_attribute_def(char *pair, unsigned char **defsptr){
-  int i,j;
-  char temp[32];
-  unsigned char *defs;
-
-  // If array does not exist, allocate it
-  if (!*defsptr && !(*defsptr=(unsigned char *)calloc(MAX_ATTRIBUTE_NUM, 1))){
-    pout("Out of memory in parse_attribute_def\n");
-    EXIT(1);
-  }
-
-  defs=*defsptr;
 
-  // look along list and see if we find the pair
-  for (i=0; vendorattributeargs[i] && strcmp(pair, vendorattributeargs[i]); i++);
+// Table of raw print format names
+struct format_name_entry
+{
+  const char * name;
+  ata_attr_raw_format format;
+};
 
-  switch (i) {
-  case 0:
-    // attribute 9 is power on time in minutes
-    defs[9]=1;
-    return 0;
-  case 1:
-    // attribute 9 is power-on-time in seconds
-    defs[9]=3;
-    return 0;
-  case 2:
-    // attribute 9 is temperature in celsius
-    defs[9]=2;
-    return 0;
-  case 3:
-    // attribute 220 is temperature in celsius
-    defs[220]=1;
-    return 0;
-  case 4:
-    // print all attributes in raw 8-bit form
-    for (j=0; j<MAX_ATTRIBUTE_NUM; j++)
-      defs[j]=253;
-    return 0;
-  case 5:
-    // print all attributes in raw 16-bit form
-    for (j=0; j<MAX_ATTRIBUTE_NUM; j++)
-      defs[j]=254;
-    return 0;
-  case 6:
-    // print all attributes in raw 48-bit form
-    for (j=0; j<MAX_ATTRIBUTE_NUM; j++)
-      defs[j]=255;
-    return 0;
-  case 7:
-    // attribute 200 is write error count
-    defs[200]=1;
-    return 0;
-  case 8:
-    // attribute 9 increments once every 30 seconds (power on time
-    // measure)
-    defs[9]=4;
-    return 0;
-  case 9:
-    // attribute 194 is ten times disk temp in Celsius
-    defs[194]=1;
-    return 0;
-  case 10:
-    // attribute 194 is unknown
-    defs[194]=2;
-    return 0;
-  case 11:
-    // Hitachi : Attributes 193 has 2 values : 1 load, 1 normal unload
-    defs[193]=1;
-    return 0;
-  case 12:
-    // Fujitsu
-    defs[201]=1;
-    return 0;
-  case 13:
-    // Fujitsu
-    defs[192]=1;
-    return 0;
-  case 14:
-    // Fujitsu
-    defs[198]=1;
-    return 0;
-  default:
-    // pair not found
-    break;
-  }
-  // At this point, either the pair was not found, or it is of the
-  // form N,uninterpreted, in which case we need to parse N
-  j=sscanf(pair,"%d,%14s", &i, temp);
-  // if no match to pattern, unrecognized
-  if (j!=2 || i<0 || i >255)
-    return 1;
+const format_name_entry format_names[] = {
+  {"raw8"           , RAWFMT_RAW8},
+  {"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(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},
+};
 
-  // check for recognized strings
-  if (!strcmp(temp, "raw8")) {
-    defs[i]=253;
-    return 0;
-  }
-  
-  // check for recognized strings
-  if (!strcmp(temp, "raw16")) {
-    defs[i]=254;
-    return 0;
-  }
-  
-  // check for recognized strings
-  if (!strcmp(temp, "raw48")) {
-    defs[i]=255;
-    return 0;
-  }
-  // didn't recognize the string
-  return 1;
-}
+const unsigned num_format_names = sizeof(format_names)/sizeof(format_names[0]);
+
+// Table to map old to new '-v' option arguments
+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"},
+  {  "9,temp"                     , "9,tempminmax,Temperature_Celsius"},
+  {"192,emergencyretractcyclect"  , "192,raw48,Emerg_Retract_Cycle_Ct"},
+  {"193,loadunload"               , "193,raw24/raw24"},
+  {"194,10xCelsius"               , "194,temp10x,Temperature_Celsius_x10"},
+  {"194,unknown"                  , "194,raw48,Unknown_Attribute"},
+  {"197,increasing"               , "197,raw48+,Total_Pending_Sectors"}, // '+' sets flag
+  {"198,offlinescanuncsectorct"   , "198,raw48,Offline_Scan_UNC_SectCt"}, // see also get_unc_attr_id() above
+  {"198,increasing"               , "198,raw48+,Total_Offl_Uncorrectabl"}, // '+' sets flag
+  {"200,writeerrorcount"          , "200,raw48,Write_Error_Count"},
+  {"201,detectedtacount"          , "201,raw48,Detected_TA_Count"},
+  {"220,temp"                     , "220,tempminmax,Temperature_Celsius"},
+};
 
-// Structure used in sorting the array vendorattributeargs[].
-typedef struct vaa_pair_s {
-  const char *vaa;
-  const char *padded_vaa;
-} vaa_pair;
+const unsigned num_old_vendor_opts = sizeof(map_old_vendor_opts)/sizeof(map_old_vendor_opts[0]);
 
-// Returns a copy of s with all numbers of less than three digits padded with
-// leading zeros.  Returns NULL if there isn't enough memory available.  The
-// memory for the string is dynamically allocated and should be freed by the
-// caller.
-char *pad_numbers(const char *s)
+// Parse vendor attribute display def (-v option).
+// Return false on error.
+bool parse_attribute_def(const char * opt, ata_vendor_attr_defs & defs,
+                         ata_vendor_def_prior priority)
 {
-  char c, *t, *u;
-  const char *r;
-  int i, len, ndigits = 0;
-
-  // Allocate the maximum possible amount of memory needed.
-  if (!(t = (char *)malloc(strlen(s)*2+2)))
-    return NULL;
-
-  // Copy the string s to t, padding any numbers of less than three digits
-  // with leading zeros.  The string is copied backwards to simplify the code.
-  r = s + strlen(s);
-  u = t;
-  while (( r-- >= s)) {
-    if (isdigit((int)*r))
-      ndigits++;
-    else if (ndigits > 0) {
-      while (ndigits++ < 3)
-        *u++ = '0';
-      ndigits = 0;
+  // Map old -> new options
+  unsigned i;
+  for (i = 0; i < num_old_vendor_opts; i++) {
+    if (!strcmp(opt, map_old_vendor_opts[i][0])) {
+      opt = map_old_vendor_opts[i][1];
+      break;
     }
-    *u++ = *r;
   }
-  *u = '\0';
 
-  // Reverse the string in t.
-  len = strlen(t);
-  for (i = 0; i < len/2; i++) {
-    c          = t[i];
-    t[i]       = t[len-1-i];
-    t[len-1-i] = c;
+  // Parse option
+  int len = strlen(opt);
+  int id = 0, n1 = -1, n2 = -1;
+  char fmtname[32+1], attrname[32+1], hddssd[3+1];
+  attrname[0] = hddssd[0] = 0;
+
+  if (opt[0] == 'N') {
+    // "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[,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;
+  }
+
+  unsigned flags = 0;
+  // For "-v 19[78],increasing" above
+  if (fmtname[strlen(fmtname)-1] == '+') {
+    fmtname[strlen(fmtname)-1] = 0;
+    flags = ATTRFLAG_INCREASING;
+  }
+
+  // Split "format[:byteorder]"
+  char byteorder[8+1] = "";
+  if (strchr(fmtname, ':')) {
+    if (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;
+    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)
+      return false; // Not found
+    if (!strcmp(fmtname, format_names[i].name))
+      break;
   }
+  ata_attr_raw_format format = format_names[i].format;
 
-  return t;
-}
-
-// Comparison function for qsort().  Used by sort_vendorattributeargs().
-int compare_vaa_pairs(const void *a, const void *b)
-{
-  vaa_pair *p = (vaa_pair *)a;
-  vaa_pair *q = (vaa_pair *)b;
-
-  return strcmp(p->padded_vaa, q->padded_vaa);
-}
-
-// Returns a sorted list of vendorattributeargs or NULL if there is not enough
-// memory available.  The memory for the list is allocated dynamically and
-// should be freed by the caller.
-// To perform the sort, any numbers in the strings are padded out to three
-// digits by adding leading zeros.  For example,
-//
-//    "9,minutes"  becomes  "009,minutes"
-//    "N,raw16"    becomes  "N,raw016"
-//
-// and the original strings are paired with the padded strings.  The list of
-// pairs is then sorted by comparing the padded strings (using strcmp) and the
-// result is then the list of unpadded strings.
-//
-const char **sort_vendorattributeargs(void) {
-  const char **ps, **sorted_list = NULL;
-  vaa_pair *pairs, *pp;
-  int count, i;
-
-  // Figure out how many strings are in vendorattributeargs[] (not including
-  // the terminating NULL).
-  count = (sizeof vendorattributeargs) / sizeof(char *) - 1;
+  // 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);
 
-  // Construct a list of pairs of strings from vendorattributeargs[] and their
-  // padded equivalents.
-  if (!(pairs = (vaa_pair *)malloc(sizeof(vaa_pair) * count)))
-    goto END;
-  for (ps = vendorattributeargs, pp = pairs; *ps; ps++, pp++) {
-    pp->vaa = *ps;
-    if (!(pp->padded_vaa = pad_numbers(*ps)))
-      goto END;
+  // ",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++) {
+      if (defs[i].priority >= priority)
+        continue;
+      if (attrname[0])
+        defs[i].name = attrname;
+      defs[i].priority = priority;
+      defs[i].raw_format = format;
+      defs[i].flags = flags;
+      snprintf(defs[i].byteorder, sizeof(defs[i].byteorder), "%s", byteorder);
+    }
   }
-
-  // Sort the array of vaa_pair structures by comparing the padded strings
-  // using strcmp().
-  qsort(pairs, count, sizeof(vaa_pair), compare_vaa_pairs);
-
-  // Construct the sorted list of strings.
-  if (!(sorted_list = (const char **)malloc(sizeof vendorattributeargs)))
-    goto END;
-  for (ps = sorted_list, pp = pairs, i = 0; i < count; ps++, pp++, i++)
-    *ps = pp->vaa;
-  *ps = NULL;
-
-END:
-  if (pairs) {
-    for (i = 0; i < count; i++)
-      if (pairs[i].padded_vaa)
-        free((void *)pairs[i].padded_vaa);
-    free((void *)pairs);
+  else if (defs[id].priority <= priority) {
+    // "id,format[,name]"
+    if (attrname[0])
+      defs[id].name = attrname;
+    defs[id].raw_format = format;
+    defs[id].priority = priority;
+    defs[id].flags = flags;
+    snprintf(defs[id].byteorder, sizeof(defs[id].byteorder), "%s", byteorder);
   }
 
-  // If there was a problem creating the list then sorted_list should now
-  // contain NULL.
-  return sorted_list;
+  return true;
 }
 
-// Function to return a multiline string containing a list of the arguments in 
-// vendorattributeargs[].  The strings are preceeded by tabs and followed
+
+// Return a multiline string containing a list of valid arguments for
+// parse_attribute_def().  The strings are preceded by tabs and followed
 // (except for the last) by newlines.
-// This function allocates the required memory for the string and the caller
-// must use free() to free it.  It returns NULL if the required memory can't
-// be allocated.
-char *create_vendor_attribute_arg_list(void){
-  const char **ps, **sorted;
-  char *s;
-  int len;
-
-  // Get a sorted list of vendor attribute arguments.  If the sort fails
-  // (which should only happen if the system is really low on memory) then just
-  // use the unordered list.
-  if (!(sorted = (const char **) sort_vendorattributeargs()))
-    sorted = vendorattributeargs;
-
-  // Calculate the required number of characters
-  len = 1;                // At least one char ('\0')
-  for (ps = sorted; *ps != NULL; ps++) {
-    len += 1;             // For the tab
-    len += strlen(*ps);   // For the actual argument string
-    if (*(ps+1))
-      len++;              // For the newline if required
-  }
-
-  // Attempt to allocate memory for the string
-  if (!(s = (char *)malloc(len)))
-    return NULL;
+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[: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;
+}
 
-  // Construct the string
-  *s = '\0';
-  for (ps = sorted; *ps != NULL; ps++) {
-    strcat(s, "\t");
-    strcat(s, *ps);
-    if (*(ps+1))
-      strcat(s, "\n");
-  }
 
-  free((char **)sorted);
+// 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 pointer to the string
-  return s;
+// 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;
@@ -514,26 +329,38 @@ void swap8(char *location){
   return;
 }
 
-// Invalidate serial number and adjust checksum in IDENTIFY data
-static void invalidate_serno(ata_identify_device * id){
+// 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)
+{
   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';
   }
-#ifndef __NetBSD__
-  bool must_swap = !!isbigendian();
-  if (must_swap)
-    swapx(id->words088_255+255-88);
-#endif
+  unsigned char * b = (unsigned char *)id;
+  for (i = 2*108; i < 2*112; i++) { // words108-111: WWN
+    sum += b[i]; sum -= b[i] = 0x00;
+  }
+
+  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 char *commandstrings[]={
+static const char * const commandstrings[]={
   "SMART ENABLE",
   "SMART DISABLE",
   "SMART AUTOMATIC ATTRIBUTE SAVE",
@@ -551,26 +378,58 @@ static char *commandstrings[]={
   "WARNING (UNDEFINED COMMAND -- CONTACT DEVELOPERS AT " PACKAGE_BUGREPORT ")\n"
 };
 
+
+static const char * preg(const ata_register & r, char (& buf)[8])
+{
+  if (!r.is_set())
+    //return "n/a ";
+    return "....";
+  snprintf(buf, sizeof(buf), "0x%02x", r.val());
+  return buf;
+}
+
+static void print_regs(const char * prefix, const ata_in_regs & r, const char * suffix = "\n")
+{
+  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);
+}
+
+static void print_regs(const char * prefix, const ata_out_regs & r, const char * suffix = "\n")
+{
+  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]),
+    preg(r.status, bufs[6]), 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);
 }
 
-static int parsedev_command_interface(int fd, smart_command_set command, int select, char * data);
-
 // This function provides the pretty-print reporting for SMART
 // commands: it implements the various -r "reporting" options for ATA
 // ioctls.
-int smartcommandhandler(int device, smart_command_set command, int select, char *data){
-  int retval;
-
+int smartcommandhandler(ata_device * device, smart_command_set command, int select, char *data){
+  // TODO: Rework old stuff below
   // This conditional is true for commands that return data
   int getsdata=(command==PIDENTIFY || 
                 command==IDENTIFY || 
@@ -582,7 +441,7 @@ int smartcommandhandler(int device, smart_command_set command, int select, char
   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 || 
@@ -590,7 +449,7 @@ int smartcommandhandler(int device, smart_command_set command, int select, char
                          command==IMMEDIATE_OFFLINE ||
                          command==WRITE_LOG);
                   
-    pout("\nREPORT-IOCTL: DeviceFD=%d Command=%s", device, commandstrings[command]);
+    pout("\nREPORT-IOCTL: Device=%s Command=%s", device->get_dev_name(), commandstrings[command]);
     if (usesparam)
       pout(" InputParameter=%d\n", select);
     else
@@ -614,73 +473,301 @@ int smartcommandhandler(int device, smart_command_set command, int select, char
 
 
   // 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]);
 
-  // In case the command produces an error, we'll want to know what it is:
-  errno=0;
-  
   // now execute the command
-  switch (con->controller_type) {
-  case CONTROLLER_3WARE_678K:
-  case CONTROLLER_3WARE_678K_CHAR:
-  case CONTROLLER_3WARE_9000_CHAR:
-    retval=escalade_command_interface(device, con->controller_port-1, con->controller_type, command, select, data);
-    if (retval &&  con->controller_port<=0)
-      pout("WARNING: apparently missing '-d 3ware,N' disk specification\n");
-    break;
-  case CONTROLLER_MARVELL_SATA:
-    retval=marvell_command_interface(device, command, select, data);
-    break;
-  case CONTROLLER_SAT:
-    retval=sat_command_interface(device, command, select, data);
-    break;
-  case CONTROLLER_HPT:
-    retval=highpoint_command_interface(device, command, select, data);
-    break;
-  case CONTROLLER_PARSEDEV:
-    retval=parsedev_command_interface(device, command, select, data);
-    break;
-  default:
-    retval=ata_command_interface(device, command, select, data);
+  int retval = -1;
+  {
+    ata_cmd_in in;
+    // Set common register values
+    switch (command) {
+      default: // SMART commands
+        in.in_regs.command = ATA_SMART_CMD;
+        in.in_regs.lba_high = SMART_CYL_HI; in.in_regs.lba_mid = SMART_CYL_LOW;
+        break;
+      case IDENTIFY: case PIDENTIFY: case CHECK_POWER_MODE: // Non SMART commands
+        break;
+    }
+    // Set specific values
+    switch (command) {
+      case IDENTIFY:
+        in.in_regs.command = ATA_IDENTIFY_DEVICE;
+        in.set_data_in(data, 1);
+        break;
+      case PIDENTIFY:
+        in.in_regs.command = ATA_IDENTIFY_PACKET_DEVICE;
+        in.set_data_in(data, 1);
+        break;
+      case CHECK_POWER_MODE:
+        in.in_regs.command = ATA_CHECK_POWER_MODE;
+        in.out_needed.sector_count = true; // Powermode returned here
+        break;
+      case READ_VALUES:
+        in.in_regs.features = ATA_SMART_READ_VALUES;
+        in.set_data_in(data, 1);
+        break;
+      case READ_THRESHOLDS:
+        in.in_regs.features = ATA_SMART_READ_THRESHOLDS;
+        in.in_regs.lba_low = 1; // TODO: CORRECT ???
+        in.set_data_in(data, 1);
+        break;
+      case READ_LOG:
+        in.in_regs.features = ATA_SMART_READ_LOG_SECTOR;
+        in.in_regs.lba_low = select;
+        in.set_data_in(data, 1);
+        break;
+      case WRITE_LOG:
+        in.in_regs.features = ATA_SMART_WRITE_LOG_SECTOR;
+        in.in_regs.lba_low = select;
+        in.set_data_out(data, 1);
+        break;
+      case ENABLE:
+        in.in_regs.features = ATA_SMART_ENABLE;
+        in.in_regs.lba_low = 1; // TODO: CORRECT ???
+        break;
+      case DISABLE:
+        in.in_regs.features = ATA_SMART_DISABLE;
+        in.in_regs.lba_low = 1;  // TODO: CORRECT ???
+        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;
+      case AUTO_OFFLINE:
+        in.in_regs.features = ATA_SMART_AUTO_OFFLINE;
+        in.in_regs.sector_count = select;  // Caution: Non-DATA command!
+        break;
+      case AUTOSAVE:
+        in.in_regs.features = ATA_SMART_AUTOSAVE;
+        in.in_regs.sector_count = select;  // Caution: Non-DATA command!
+        break;
+      case IMMEDIATE_OFFLINE:
+        in.in_regs.features = ATA_SMART_IMMEDIATE_OFFLINE;
+        in.in_regs.lba_low = select;
+        break;
+      default:
+        pout("Unrecognized command %d in smartcommandhandler()\n"
+             "Please contact " PACKAGE_BUGREPORT "\n", command);
+        device->set_err(ENOSYS);
+        return -1;
+    }
+
+    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 (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) {
+      default:
+        retval = 0;
+        break;
+      case CHECK_POWER_MODE:
+        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"
+        if ((out.out_regs.lba_high == SMART_CYL_HI) &&
+            (out.out_regs.lba_mid == SMART_CYL_LOW))
+          retval = 0;
+        // These values mean "Bad SMART status"
+        else if ((out.out_regs.lba_high == SRET_STATUS_HI_EXCEEDED) &&
+                 (out.out_regs.lba_mid == SRET_STATUS_MID_EXCEEDED))
+          retval = 1;
+        else if (out.out_regs.lba_mid == SMART_CYL_LOW) {
+          retval = 0;
+          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 (ata_debugmode)
+            pout("SMART STATUS RETURN: half unhealthy response sequence, "
+                 "probable SAT/USB truncation\n");
+        }
+        else if (!out.out_regs.is_set()) {
+          device->set_err(ENOSYS, "Incomplete response, ATA output registers missing");
+          retval = -1;
+        }
+        else {
+          // We haven't gotten output that makes sense; print out some debugging info
+          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(ENOSYS, "Invalid ATA output register values");
+          retval = -1;
+        }
+        break;
+    }
   }
 
   // If requested, invalidate serial number before any printing is done
-  if ((command == IDENTIFY || command == PIDENTIFY) && !retval && con->dont_print_serial)
-    invalidate_serno((ata_identify_device *)data);
+  if ((command == IDENTIFY || command == PIDENTIFY) && !retval && dont_print_serial_number)
+    invalidate_serno( reinterpret_cast<ata_identify_device *>(data) );
 
   // If reporting is enabled, say what output was produced by the command
-  if (con->reportataioctl){
-    if (errno)
-      pout("REPORT-IOCTL: DeviceFD=%d Command=%s returned %d errno=%d [%s]\n", 
-           device, commandstrings[command], retval, errno, strerror(errno));
+  if (ata_debugmode) {
+    if (device->get_errno())
+      pout("REPORT-IOCTL: Device=%s Command=%s returned %d errno=%d [%s]\n",
+           device->get_dev_name(), commandstrings[command], retval,
+           device->get_errno(), device->get_errmsg());
     else
-      pout("REPORT-IOCTL: DeviceFD=%d Command=%s returned %d\n",
-           device, commandstrings[command], retval);
+      pout("REPORT-IOCTL: Device=%s Command=%s returned %d\n",
+           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
        prettyprint((unsigned char *)data, commandstrings[command]);
     }
   }
+
   return retval;
 }
 
+// Get capacity and sector sizes from IDENTIFY data
+void ata_get_size_info(const ata_identify_device * id, ata_size_info & sizes)
+{
+  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;
+
+  // Determine sector sizes
+  sizes.log_sector_size = sizes.phy_sector_size = 512;
+
+  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;
+
+    if (word106 & 0x2000)
+      // Physical sector size is multiple of logical sector size
+      sizes.phy_sector_size <<= (word106 & 0x0f);
+
+    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
 // bytes).  Returns zero if checksum is OK, nonzero if the checksum is
 // incorrect.  The size (512) is correct for all SMART structures.
-unsigned char checksum(unsigned char *buffer){
-  unsigned char sum=0;
+unsigned char checksum(const void * data)
+{
+  unsigned char sum = 0;
+  for (int i = 0; i < 512; i++)
+    sum += ((const unsigned char *)data)[i];
+  return sum;
+}
+
+// Copies n bytes (or n-1 if n is odd) from in to out, but swaps adjacents
+// bytes.
+static void swapbytes(char * out, const char * in, size_t n)
+{
+  for (size_t i = 0; i < n; i += 2) {
+    out[i]   = in[i+1];
+    out[i+1] = in[i];
+  }
+}
+
+// Copies in to out, but removes leading and trailing whitespace.
+static void trim(char * out, const char * in)
+{
+  // Find the first non-space character (maybe none).
+  int first = -1;
   int i;
-  
-  for (i=0; i<512; i++)
-    sum+=buffer[i];
+  for (i = 0; in[i]; i++)
+    if (!isspace((int)in[i])) {
+      first = i;
+      break;
+    }
 
-  return sum;
+  if (first == -1) {
+    // There are no non-space characters.
+    out[0] = '\0';
+    return;
+  }
+
+  // Find the last non-space character.
+  for (i = strlen(in)-1; i >= first && isspace((int)in[i]); i--)
+    ;
+  int last = i;
+
+  strncpy(out, in+first, last-first+1);
+  out[last-first+1] = '\0';
+}
+
+// Convenience function for formatting strings from ata_identify_device
+void ata_format_id_string(char * out, const unsigned char * in, int n)
+{
+  char tmp[65];
+  n = n > 64 ? 64 : n;
+  swapbytes(tmp, (const char *)in, n);
+  tmp[n] = '\0';
+  trim(out, tmp);
 }
 
 // returns -1 if command fails or the device is in Sleep mode, else
@@ -689,20 +776,39 @@ unsigned char checksum(unsigned char *buffer){
 //   80h device is in Idle mode.
 //   FFh device is in Active mode or Idle mode.
 
-int ataCheckPowerMode(int device) {
+int ataCheckPowerMode(ata_device * device) {
   unsigned char result;
 
   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;
 }
 
+// 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
@@ -710,40 +816,77 @@ int ataCheckPowerMode(int 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 (int 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;
   }
 
-#ifndef __NetBSD__
+  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)
+      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));
+
   // if machine is big-endian, swap byte order as needed
-  // NetBSD kernel delivers IDENTIFY data in host byte order
   if (isbigendian()){
-    int i;
-    
     // 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))
     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);
@@ -752,84 +895,48 @@ int ataReadHDIdentity (int 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, struct ata_identify_device *drive, unsigned short *minor){
-  unsigned short major;
-  int i;
+// Get World Wide Name (WWN) fields.
+// Return NAA field or -1 if WWN is unsupported.
+// Table 34 of T13/1699-D Revision 6a (ATA8-ACS), September 6, 2008.
+// (WWN was introduced in ATA/ATAPI-7 and is mandatory since ATA8-ACS Revision 3b)
+int ata_get_wwn(const ata_identify_device * id, unsigned & oui, uint64_t & unique_id)
+{
+  // Don't use word 84 to be compatible with some older ATA-7 disks
+  unsigned short word087 = id->csf_default;
+  if ((word087 & 0xc100) != 0x4100)
+    return -1; // word not valid or WWN support bit 8 not set
 
-  // 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
-  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;
-    }
-  }
+  unsigned short word108 = id->words088_255[108-88];
+  unsigned short word109 = id->words088_255[109-88];
+  unsigned short word110 = id->words088_255[110-88];
+  unsigned short word111 = id->words088_255[111-88];
 
-  // Try new ATA-8 minor revision numbers (Table 32 of T13/1699-D Revision 4c)
-  // (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 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.
-  for (i=15; i>0; i--)
-    if (major & (0x1<<i))
-      break;
-  
-  *description=NULL; 
-  if (i==0)
+  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
-int ataSmartSupport(struct ata_identify_device *drive){
+int ataSmartSupport(const ata_identify_device * drive)
+{
   unsigned short word82=drive->command_set_1;
   unsigned short word83=drive->command_set_2;
   
@@ -843,7 +950,8 @@ int ataSmartSupport(struct ata_identify_device *drive){
 }
 
 // returns 1 if SMART enabled, 0 if SMART disabled, -1 if can't tell
-int ataIsSmartEnabled(struct ata_identify_device *drive){
+int ataIsSmartEnabled(const ata_identify_device * drive)
+{
   unsigned short word85=drive->cfs_enable_1;
   unsigned short word87=drive->csf_default;
   
@@ -858,15 +966,14 @@ int ataIsSmartEnabled(struct ata_identify_device *drive){
 
 
 // Reads SMART attributes into *data
-int ataReadSmartValues(int device, struct ata_smart_values *data){      
+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;
   }
 
   // compute checksum
-  if (checksum((unsigned char *)data))
+  if (checksum(data))
     checksumwarning("SMART Attribute Data Structure");
   
   // swap endian order if needed
@@ -875,6 +982,7 @@ int ataReadSmartValues(int device, struct ata_smart_values *data){
     swap2((char *)&(data->revnumber));
     swap2((char *)&(data->total_time_to_complete_off_line));
     swap2((char *)&(data->smart_capability));
+    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));
@@ -887,9 +995,8 @@ int ataReadSmartValues(int device, struct ata_smart_values *data){
 
 // This corrects some quantities that are byte reversed in the SMART
 // SELF TEST LOG
-void fixsamsungselftestlog(struct ata_smart_selftestlog *data){
-  int i;
-  
+static void fixsamsungselftestlog(ata_smart_selftestlog * data)
+{
   // bytes 508/509 (numbered from 0) swapped (swap of self-test index
   // with one byte of reserved.
   swap2((char *)&(data->mostrecenttest));
@@ -898,27 +1005,28 @@ void fixsamsungselftestlog(struct ata_smart_selftestlog *data){
   // information about the TYPE of the self-test) is byte swapped with
   // Self-test execution status byte.  These are bytes N, N+1 in the
   // entries.
-  for (i=0; i<21; i++)
+  for (int i = 0; i < 21; i++)
     swap2((char *)&(data->selftest_struct[i].selftestnumber));
 
   return;
 }
 
 // Reads the Self Test Log (log #6)
-int ataReadSelfTestLog (int device, struct ata_smart_selftestlog *data){
+int ataReadSelfTestLog (ata_device * device, ata_smart_selftestlog * data,
+                        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;
   }
 
   // compute its checksum, and issue a warning if needed
-  if (checksum((unsigned char *)data))
+  if (checksum(data))
     checksumwarning("SMART Self-Test Log Structure");
   
   // fix firmware bugs in self-test log
-  if (con->fixfirmwarebug == FIX_SAMSUNG)
+  if (firmwarebugs.is_set(BUG_SAMSUNG))
     fixsamsungselftestlog(data);
 
   // swap endian order if needed
@@ -935,36 +1043,156 @@ int ataReadSelfTestLog (int device, struct ata_smart_selftestlog *data){
   return 0;
 }
 
+// Print checksum warning for multi sector log
+static void check_multi_sector_sum(const void * data, unsigned nsectors, const char * msg)
+{
+  unsigned errs = 0;
+  for (unsigned i = 0; i < nsectors; i++) {
+    if (checksum((const unsigned char *)data + i*512))
+      errs++;
+  }
+  if (errs > 0) {
+    if (nsectors == 1)
+      checksumwarning(msg);
+    else
+      checksumwarning(strprintf("%s (%u/%u)", msg, errs, nsectors).c_str());
+  }
+}
+
+// Read SMART Extended Self-test Log
+bool ataReadExtSelfTestLog(ata_device * device, ata_smart_extselftestlog * log,
+                           unsigned nsectors)
+{
+  if (!ataReadLogExt(device, 0x07, 0x00, 0, log, nsectors))
+    return false;
 
-// Reads the Log Directory (log #0).  Note: NO CHECKSUM!!
-int ataReadLogDirectory (int device, struct ata_smart_log_directory *data){     
-  
-  // get data from device
-  if (smartcommandhandler(device, READ_LOG, 0x00, (char *)data)){
-    return -1;
+  check_multi_sector_sum(log, nsectors, "SMART Extended Self-test Log Structure");
+
+  if (isbigendian()) {
+    SWAPV(log->log_desc_index);
+    for (unsigned i = 0; i < nsectors; i++) {
+      for (unsigned j = 0; j < 19; j++)
+        SWAPV(log->log_descs[i].timestamp);
+    }
   }
+  return true;
+}
 
-  // swap endian order if needed
-  if (isbigendian()){
-    swap2((char *)&(data->logversion));
+// 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 0;
+
+  return true;
 }
 
+// Read GP Log page(s)
+bool ataReadLogExt(ata_device * device, unsigned char logaddr,
+                   unsigned char features, unsigned page,
+                   void * data, unsigned nsectors)
+{
+  ata_cmd_in in;
+  in.in_regs.command      = ATA_READ_LOG_EXT;
+  in.in_regs.features     = features; // log specific
+  in.set_data_in_48bit(data, nsectors);
+  in.in_regs.lba_low      = logaddr;
+  in.in_regs.lba_mid_16   = page;
+
+  if (!device->ata_pass_through(in)) { // TODO: Debug output
+    if (nsectors <= 1) {
+      pout("ATA_READ_LOG_EXT (addr=0x%02x:0x%02x, page=%u, n=%u) failed: %s\n",
+           logaddr, features, page, nsectors, device->get_errmsg());
+      return false;
+    }
 
-// Reads the selective self-test log (log #9)
-int ataReadSelectiveSelfTestLog(int device, struct ata_selective_self_test_log *data){  
-  
-  // get data from device
-  if (smartcommandhandler(device, READ_LOG, 0x09, (char *)data)){
-    syserror("Error SMART Read Selective Self-Test Log failed");
-    return -1;
+    // Recurse to retry with single sectors,
+    // multi-sector reads may not be supported by ioctl.
+    for (unsigned i = 0; i < nsectors; i++) {
+      if (!ataReadLogExt(device, logaddr,
+                         features, page + i,
+                         (char *)data + 512*i, 1))
+        return false;
+    }
   }
-   
-  // compute its checksum, and issue a warning if needed
-  if (checksum((unsigned char *)data))
-    checksumwarning("SMART Selective Self-Test Log Structure");
+
+  return true;
+}
+
+// Read SMART Log page(s)
+bool ataReadSmartLog(ata_device * device, unsigned char logaddr,
+                     void * data, unsigned nsectors)
+{
+  ata_cmd_in in;
+  in.in_regs.command  = ATA_SMART_CMD;
+  in.in_regs.features = ATA_SMART_READ_LOG_SECTOR;
+  in.set_data_in(data, nsectors);
+  in.in_regs.lba_high = SMART_CYL_HI;
+  in.in_regs.lba_mid  = SMART_CYL_LOW;
+  in.in_regs.lba_low  = logaddr;
+
+  if (!device->ata_pass_through(in)) { // TODO: Debug output
+    pout("ATA_SMART_READ_LOG failed: %s\n", device->get_errmsg());
+    return false;
+  }
+  return true;
+}
+
+
+
+// Reads the SMART or GPL Log Directory (log #0)
+int ataReadLogDirectory(ata_device * device, ata_smart_log_directory * data, bool gpl)
+{
+  if (!gpl) { // SMART Log directory
+    if (smartcommandhandler(device, READ_LOG, 0x00, (char *)data))
+      return -1;
+  }
+  else { // GP Log directory
+    if (!ataReadLogExt(device, 0x00, 0x00, 0, data, 1))
+      return -1;
+  }
+
+  // swap endian order if needed
+  if (isbigendian())
+    SWAPV(data->logversion);
+
+  return 0;
+}
+
+
+// Reads the selective self-test log (log #9)
+int ataReadSelectiveSelfTestLog(ata_device * device, struct ata_selective_self_test_log *data){
+  
+  // get data from device
+  if (smartcommandhandler(device, READ_LOG, 0x09, (char *)data)){
+    return -1;
+  }
+   
+  // compute its checksum, and issue a warning if needed
+  if (checksum(data))
+    checksumwarning("SMART Selective Self-Test Log Structure");
   
   // swap endian order if needed
   if (isbigendian()){
@@ -980,15 +1208,14 @@ int ataReadSelectiveSelfTestLog(int device, struct ata_selective_self_test_log *
     swap2((char *)&(data->pendingtime));
   }
   
-  if (data->logversion != 1)
-    pout("SMART Selective Self-Test Log Data Structure Revision Number (%d) should be 1\n", data->logversion);
-  
   return 0;
 }
 
 // Writes the selective self-test log (log #9)
-int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64_t num_sectors){   
-
+int ataWriteSelectiveSelfTestLog(ata_device * device, ata_selective_selftest_args & args,
+                                 const ata_smart_values * sv, uint64_t num_sectors,
+                                 const ata_selective_selftest_args * prev_args)
+{
   // Disk size must be known
   if (!num_sectors) {
     pout("Disk size is unknown, unable to check selective self-test spans\n");
@@ -999,38 +1226,28 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
   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;
   }
   
-  // Fix logversion if needed
-  if (data->logversion !=1) {
-    if (!con->permissive) {
-      pout("Error SMART Selective Self-Test Log Data Structure Revision not recognized\n"
-           "Revision number should be 1 but is %d. To be safe, aborting WRITE LOG.\n"
-           "To fix revision number, add one '-T permissive' option.\n", data->logversion);
-      return -2;
-    }
-    con->permissive--;
-    pout("SMART Selective Self-Test Log Data Structure Revision should be 1 but is %d\n"
-         "'-T permissive' specified, now trying to fix it by WRITE LOG.\n", data->logversion);
-    data->logversion = 1;
-  }
+  // Set log version
+  data->logversion = 1;
 
   // Host is NOT allowed to write selective self-test log if a selective
   // self-test is in progress.
   if (0<data->currentspan && 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;
   }
 
   // Set start/end values based on old spans for special -t select,... options
   int i;
-  for (i=0; i<con->smartselectivenumspans; i++) {
-    char mode = con->smartselectivemode[i];
-    uint64_t start = con->smartselectivespan[i][0];
-    uint64_t end   = con->smartselectivespan[i][1];
-    if (mode == SEL_CONT) {// redo or next dependig on last test status
+  for (i = 0; i < args.num_spans; i++) {
+    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 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");
@@ -1042,6 +1259,17 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
           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 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;
+      data->span[i].end   = prev_args->span[i].end;
+    }
+
     switch (mode) {
       case SEL_RANGE: // -t select,START-END
         break;
@@ -1071,9 +1299,10 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
             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"
-                 "                 to %"PRIu64"-%"PRIu64" (%"PRIu64" sectors) (%"PRIu64" spans)\n",
-                i, start, end, oldsize, newstart, newend, newsize, spans);
+            pout("Span %d changed from %" PRIu64 "-%" PRIu64 " (%" PRIu64 " sectors)\n",
+                 i, start, end, oldsize);
+            pout("                 to %" PRIu64 "-%" PRIu64 " (%" PRIu64 " sectors) (%" PRIu64 " spans)\n",
+                 newstart, newend, newsize, spans);
             start = newstart; end = newend;
           }
         }
@@ -1089,13 +1318,14 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
       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;
     }
-    // Write back to allow ataSmartTest() to print the actual values
-    con->smartselectivespan[i][0] = start;
-    con->smartselectivespan[i][1] = end;
+    // Return the actual mode and range to caller.
+    args.span[i].mode  = mode;
+    args.span[i].start = start;
+    args.span[i].end   = end;
   }
 
   // Clear spans
@@ -1103,9 +1333,9 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
     memset(data->span+i, 0, sizeof(struct test_span));
   
   // Set spans for testing 
-  for (i=0; i<con->smartselectivenumspans; i++){
-    data->span[i].start = con->smartselectivespan[i][0];
-    data->span[i].end   = con->smartselectivespan[i][1];
+  for (i = 0; i < args.num_spans; i++){
+    data->span[i].start = args.span[i].start;
+    data->span[i].end   = args.span[i].end;
   }
 
   // host must initialize to zero before initiating selective self-test
@@ -1113,10 +1343,10 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
   data->currentspan=0;
   
   // Perform off-line scan after selective test?
-  if (1 == con->scanafterselect)
+  if (args.scan_after_select == 1)
     // NO
     data->flags &= ~SELECTIVE_FLAG_DOSCAN;
-  else if (2 == con->scanafterselect)
+  else if (args.scan_after_select == 2)
     // YES
     data->flags |= SELECTIVE_FLAG_DOSCAN;
   
@@ -1125,8 +1355,8 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
   data->flags &= ~(SELECTIVE_FLAG_PENDING);
 
   // modify pending time?
-  if (con->pendingtime)
-    data->pendingtime=(unsigned short)(con->pendingtime-1);
+  if (args.pending_time)
+    data->pendingtime = (unsigned short)(args.pending_time-1);
 
   // Set checksum to zero, then compute checksum
   data->checksum=0;
@@ -1140,9 +1370,9 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
   // 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));
@@ -1152,7 +1382,7 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
 
   // 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;
   }
 
@@ -1161,18 +1391,17 @@ int ataWriteSelectiveSelfTestLog(int device, struct ata_smart_values *sv, uint64
 
 // This corrects some quantities that are byte reversed in the SMART
 // ATA ERROR LOG.
-void fixsamsungerrorlog(struct ata_smart_errorlog *data){
-  int i,j;
-  
+static void fixsamsungerrorlog(ata_smart_errorlog * data)
+{
   // FIXED IN SAMSUNG -25 FIRMWARE???
   // Device error count in bytes 452-3
   swap2((char *)&(data->ata_error_count));
   
   // FIXED IN SAMSUNG -22a FIRMWARE
   // step through 5 error log data structures
-  for (i=0; i<5; i++){
+  for (int i = 0; i < 5; i++){
     // step through 5 command data structures
-    for (j=0; j<5; j++)
+    for (int j = 0; j < 5; j++)
       // Command data structure 4-byte millisec timestamp.  These are
       // bytes (N+8, N+9, N+10, N+11).
       swap4((char *)&(data->errorlog_struct[i].commands[j].timestamp));
@@ -1184,7 +1413,8 @@ void fixsamsungerrorlog(struct ata_smart_errorlog *data){
 }
 
 // NEEDED ONLY FOR SAMSUNG -22 (some) -23 AND -24?? FIRMWARE
-void fixsamsungerrorlog2(struct ata_smart_errorlog *data){
+static void fixsamsungerrorlog2(ata_smart_errorlog * data)
+{
   // Device error count in bytes 452-3
   swap2((char *)&(data->ata_error_count));
   return;
@@ -1193,23 +1423,24 @@ void fixsamsungerrorlog2(struct ata_smart_errorlog *data){
 // Reads the Summary SMART Error Log (log #1). The Comprehensive SMART
 // Error Log is #2, and the Extended Comprehensive SMART Error log is
 // #3
-int ataReadErrorLog (int device, struct ata_smart_errorlog *data){      
+int ataReadErrorLog (ata_device * device, ata_smart_errorlog *data,
+                     firmwarebug_defs firmwarebugs)
+{
   
   // get data from device
   if (smartcommandhandler(device, READ_LOG, 0x01, (char *)data)){
-    syserror("Error SMART Error Log Read failed");
     return -1;
   }
   
   // compute its checksum, and issue a warning if needed
-  if (checksum((unsigned char *)data))
+  if (checksum(data))
     checksumwarning("SMART ATA Error Log Structure");
   
   // Some disks have the byte order reversed in some SMART Summary
   // Error log entries
-  if (con->fixfirmwarebug == FIX_SAMSUNG)
+  if (firmwarebugs.is_set(BUG_SAMSUNG))
     fixsamsungerrorlog(data);
-  else if (con->fixfirmwarebug == FIX_SAMSUNG2)
+  else if (firmwarebugs.is_set(BUG_SAMSUNG2))
     fixsamsungerrorlog2(data);
 
   // swap endian order if needed
@@ -1233,16 +1464,68 @@ int ataReadErrorLog (int device, struct ata_smart_errorlog *data){
   return 0;
 }
 
-int ataReadSmartThresholds (int device, struct ata_smart_thresholds_pvt *data){
+
+// Fix LBA byte ordering of Extended Comprehensive Error Log
+// if little endian instead of ATA register ordering is provided
+template <class T>
+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 page, unsigned nsectors, firmwarebug_defs firmwarebugs)
+{
+  if (!ataReadLogExt(device, 0x03, 0x00, page, log, nsectors))
+    return false;
+
+  check_multi_sector_sum(log, nsectors, "SMART Extended Comprehensive Error Log Structure");
+
+  if (isbigendian()) {
+    SWAPV(log->device_error_count);
+    SWAPV(log->error_log_index);
+    for (unsigned i = 0; i < nsectors; i++) {
+      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);
+      }
+    }
+  }
+
+  if (firmwarebugs.is_set(BUG_XERRORLBA))
+    fix_exterrlog_lba(log, nsectors);
+
+  return true;
+}
+
+
+int ataReadSmartThresholds (ata_device * device, struct ata_smart_thresholds_pvt *data){
   
   // get data from device
   if (smartcommandhandler(device, READ_THRESHOLDS, 0, (char *)data)){
-    syserror("Error SMART Thresholds Read failed");
     return -1;
   }
   
   // compute its checksum, and issue a warning if needed
-  if (checksum((unsigned char *)data))
+  if (checksum(data))
     checksumwarning("SMART Attribute Thresholds Structure");
   
   // swap endian order if needed
@@ -1252,35 +1535,31 @@ int ataReadSmartThresholds (int device, struct ata_smart_thresholds_pvt *data){
   return 0;
 }
 
-int ataEnableSmart (int device ){       
+int ataEnableSmart (ata_device * device ){
   if (smartcommandhandler(device, ENABLE, 0, NULL)){
-    syserror("Error SMART Enable failed");
     return -1;
   }
   return 0;
 }
 
-int ataDisableSmart (int device ){      
+int ataDisableSmart (ata_device * device ){
   
   if (smartcommandhandler(device, DISABLE, 0, NULL)){
-    syserror("Error SMART Disable failed");
     return -1;
   }  
   return 0;
 }
 
-int ataEnableAutoSave(int device){  
+int ataEnableAutoSave(ata_device * device){
   if (smartcommandhandler(device, AUTOSAVE, 241, NULL)){
-    syserror("Error SMART Enable Auto-save failed");
     return -1;
   }
   return 0;
 }
 
-int ataDisableAutoSave(int device){
+int ataDisableAutoSave(ata_device * device){
   
   if (smartcommandhandler(device, AUTOSAVE, 0, NULL)){
-    syserror("Error SMART Disable Auto-save failed");
     return -1;
   }
   return 0;
@@ -1290,11 +1569,10 @@ int ataDisableAutoSave(int device){
 // marked "OBSOLETE". It is defined in SFF-8035i Revision 2, and most
 // vendors still support it for backwards compatibility. IBM documents
 // it for some drives.
-int ataEnableAutoOffline (int device ){ 
+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;
@@ -1302,10 +1580,9 @@ int ataEnableAutoOffline (int device ){
 
 // Another Obsolete Command.  See comments directly above, associated
 // with the corresponding Enable command.
-int ataDisableAutoOffline (int device ){        
+int ataDisableAutoOffline (ata_device * device){
   
   if (smartcommandhandler(device, AUTO_OFFLINE, 0, NULL)){
-    syserror("Error SMART Disable Automatic Offline failed");
     return -1;
   }
   return 0;
@@ -1315,7 +1592,7 @@ int ataDisableAutoOffline (int device ){
 // guaranteed to return 1, else zero.  Note that it should return 1
 // regardless of whether the disk's SMART status is 'healthy' or
 // 'failing'.
-int ataDoesSmartWork(int device){
+int ataDoesSmartWork(ata_device * device){
   int retval=smartcommandhandler(device, STATUS, 0, NULL);
 
   if (-1 == retval)
@@ -1326,16 +1603,19 @@ int ataDoesSmartWork(int device){
 
 // This function uses a different interface (DRIVE_TASK) than the
 // other commands in this file.
-int ataSmartStatus2(int device){
+int ataSmartStatus2(ata_device * device){
   return smartcommandhandler(device, STATUS_CHECK, 0, NULL);  
 }
 
 // This is the way to execute ALL tests: offline, short self-test,
 // extended self test, with and without captive mode, etc.
-int ataSmartTest(int device, int testtype, struct ata_smart_values *sv, uint64_t num_sectors)
+// TODO: Move to ataprint.cpp ?
+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],*type,*captive;
-  int errornum, cap, retval, select=0;
+  char cmdmsg[128]; const char *type, *captive;
+  int cap, retval, select=0;
 
   // Boolean, if set, says test is captive
   cap=testtype & CAPTIVE_MASK;
@@ -1357,11 +1637,25 @@ int ataSmartTest(int device, int testtype, struct ata_smart_values *sv, uint64_t
   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.
-  if (select && (retval=ataWriteSelectiveSelfTestLog(device, sv, num_sectors))) {
+  ata_selective_selftest_args selargs_io = selargs; // filled with info about actual spans
+  if (select && (retval = ataWriteSelectiveSelfTestLog(device, selargs_io, sv, num_sectors))) {
     if (retval==-4)
       pout("Can't start selective self-test without aborting current test: use '-X' option to smartctl.\n");
     return retval;
@@ -1369,41 +1663,44 @@ int ataSmartTest(int device, int testtype, struct ata_smart_values *sv, uint64_t
 
   //  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) {
     int i;
     pout("SPAN         STARTING_LBA           ENDING_LBA\n");
-    for (i = 0; i < con->smartselectivenumspans; i++)
-      pout("   %d %20"PRId64" %20"PRId64"\n", i,
-           con->smartselectivespan[i][0],
-           con->smartselectivespan[i][1]);
+    for (i = 0; i < selargs_io.num_spans; i++)
+      pout("   %d %20" PRId64 " %20" PRId64 "\n", i,
+           selargs_io.span[i].start,
+           selargs_io.span[i].end);
   }
   
   // 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;
 }
 
 /* Test Time Functions */
-int TestTime(struct ata_smart_values *data,int testtype){
+int TestTime(const ata_smart_values *data, int testtype)
+{
   switch (testtype){
   case OFFLINE_FULL_SCAN:
     return (int) data->total_time_to_complete_off_line;
@@ -1412,7 +1709,12 @@ int TestTime(struct 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;
@@ -1428,45 +1730,46 @@ int TestTime(struct 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 (struct ata_smart_values *data, struct 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;
   int isata6=identity->major_rev_num & (0x01<<6);
   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 (struct ata_smart_values *data, struct 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;
   int isata6=identity->major_rev_num & (0x01<<6);
   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(struct ata_identify_device *identity){
+bool isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
+{
   unsigned short word84=identity->command_set_extension;
   unsigned short word87=identity->csf_default;
 
@@ -1477,7 +1780,7 @@ int isGeneralPurposeLoggingCapable(struct 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
@@ -1485,599 +1788,396 @@ int isGeneralPurposeLoggingCapable(struct 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;
+  return false;
 }
 
+// Get attribute state
+ata_attr_state ata_get_attr_state(const ata_smart_attribute & attr,
+                                  int attridx,
+                                  const ata_smart_threshold_entry * thresholds,
+                                  const ata_vendor_attr_defs & defs,
+                                  unsigned char * threshval /* = 0 */)
+{
+  if (!attr.id)
+    return ATTRSTATE_NON_EXISTING;
+
+  // Normalized values (current,worst,threshold) not valid
+  // if specified by '-v' option.
+  // (Some SSD disks uses these bytes to store raw value).
+  if (defs[attr.id].flags & ATTRFLAG_NO_NORMVAL)
+    return ATTRSTATE_NO_NORMVAL;
+
+  // Normally threshold is at same index as attribute
+  int i = attridx;
+  if (thresholds[i].id != attr.id) {
+    // Find threshold id in table
+    for (i = 0; thresholds[i].id != attr.id; ) {
+      if (++i >= NUMBER_ATA_SMART_ATTRIBUTES)
+        // Threshold id missing or thresholds cannot be read
+        return ATTRSTATE_NO_THRESHOLD;
+    }
+  }
+  unsigned char threshold = thresholds[i].threshold;
 
-// 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(struct 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(struct ata_smart_values *data){
-   return data->offline_data_collection_capability & 0x02;
-}
-int isSupportOfflineAbort(struct ata_smart_values *data){
-   return data->offline_data_collection_capability & 0x04;
-}
-int isSupportOfflineSurfaceScan(struct ata_smart_values *data){
-   return data->offline_data_collection_capability & 0x08;
-}
-int isSupportSelfTest (struct ata_smart_values *data){
-   return data->offline_data_collection_capability & 0x10;
-}
-int isSupportConveyanceSelfTest(struct ata_smart_values *data){
-   return data->offline_data_collection_capability & 0x20;
-}
-int isSupportSelectiveSelfTest(struct ata_smart_values *data){
-   return data->offline_data_collection_capability & 0x40;
-}
+  // Return threshold if requested
+  if (threshval)
+    *threshval = threshold;
 
+  // Don't report a failed attribute if its threshold is 0.
+  // ATA-3 (X3T13/2008D Revision 7b) declares 0x00 as the "always passing"
+  // threshold (Later ATA versions declare all thresholds as "obsolete").
+  // In practice, threshold value 0 is often used for usage attributes.
+  if (!threshold)
+    return ATTRSTATE_OK;
 
+  // Failed now if current value is below threshold
+  if (attr.current <= threshold)
+    return ATTRSTATE_FAILED_NOW;
 
-// Loop over all valid attributes.  If they are prefailure attributes
-// and are at or below the threshold value, then return the ID of the
-// first failing attribute found.  Return 0 if all prefailure
-// attributes are in bounds.  The spec says "Bit 0
-// -Pre-failure/advisory - If the value of this bit equals zero, an
-// attribute value less than or equal to its corresponding attribute
-// threshold indicates an advisory condition where the usage or age of
-// the device has exceeded its intended design life period. If the
-// value of this bit equals one, an atribute value less than or equal
-// to its corresponding attribute threshold indicates a pre-failure
-// condition where imminent loss of data is being predicted."
+  // 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;
+}
 
-// onlyfailed=0 : are or were any age or prefailure attributes <= threshold
-// onlyfailed=1:  are any prefailure attributes <= threshold now
-int ataCheckSmart(struct ata_smart_values *data,
-                  struct ata_smart_thresholds_pvt *thresholds,
-                  int onlyfailed){
-  int i;
-  
-  // loop over all attributes
-  for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++){
-
-    // pointers to disk's values and vendor's thresholds
-    struct ata_smart_attribute *disk=data->vendor_attributes+i;
-    struct ata_smart_threshold_entry *thre=thresholds->thres_entries+i;
-    // consider only valid attributes
-    if (disk->id && thre->id){
-      int failednow,failedever;
-      
-      failednow =disk->current <= thre->threshold;
-      failedever=disk->worst   <= thre->threshold;
-      
-      if (!onlyfailed && failedever)
-        return disk->id;
-      
-      if (onlyfailed && failednow && ATTRIBUTE_FLAGS_PREFAILURE(disk->flags))
-        return disk->id;      
+// Get attribute 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;
+  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;
     }
   }
-  return 0;
-}
 
+  // 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;
+  }
 
-
-// This checks the n'th attribute in the attribute list, NOT the
-// attribute with id==n.  If the attribute does not exist, or the
-// attribute is > threshold, then returns zero.  If the attribute is
-// <= threshold (failing) then we the attribute number if it is a
-// prefail attribute.  Else we return minus the attribute number if it
-// is a usage attribute.
-int ataCheckAttribute(struct ata_smart_values *data,
-                      struct ata_smart_thresholds_pvt *thresholds,
-                      int n){
-  struct ata_smart_attribute *disk;
-  struct ata_smart_threshold_entry *thre;
-  
-  if (n<0 || n>=NUMBER_ATA_SMART_ATTRIBUTES || !data || !thresholds)
-    return 0;
-  
-  // pointers to disk's values and vendor's thresholds
-  disk=data->vendor_attributes+n;
-  thre=thresholds->thres_entries+n;
-
-  if (!disk || !thre)
-    return 0;
-  
-  // consider only valid attributes, check for failure
-  if (!disk->id || !thre->id || (disk->id != thre->id) || disk->current> thre->threshold)
-    return 0;
-  
-  // We have found a failed attribute.  Return positive or negative? 
-  if (ATTRIBUTE_FLAGS_PREFAILURE(disk->flags))
-    return disk->id;
-  else
-    return -1*(disk->id);
+  return rawvalue;
 }
 
-
-// Print temperature value and Min/Max value if present
-static void ataPrintTemperatureValue(char *out, const unsigned char *raw, const unsigned *word)
+// Helper functions for RAWFMT_TEMPMINMAX
+static inline int check_temp_word(unsigned word)
 {
-  out+=sprintf(out, "%u", word[0]);
-  if (!word[1] && !word[2])
-    return; // No Min/Max
-
-  unsigned lo = ~0, hi = ~0;
-  if (!raw[3]) {
-    // 00 HH 00 LL 00 TT (IBM)
-    hi = word[2]; lo = word[1];
-  }
-  else if (!word[2]) {
-    // 00 00 HH LL 00 TT (Maxtor)
-    hi = raw[3]; lo = raw[2];
-  }
-  if (lo > hi) {
-    unsigned t = lo; lo = hi; hi = t;
-  }
-  if (lo <= word[0] && word[0] <= hi)
-    sprintf(out, " (Lifetime Min/Max %u/%u)", lo, hi);
-  else
-    sprintf(out, " (%u %u %u %u)", raw[5], raw[4], raw[3], raw[2]);
+  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;
 }
 
-
-// This routine prints the raw value of an attribute as a text string
-// into out. It also returns this 48-bit number as a long long.  The
-// array defs[] contains non-zero values if particular attributes have
-// non-default interpretations.
-
-int64_t ataPrintSmartAttribRawValue(char *out, 
-                                    struct ata_smart_attribute *attribute,
-                                    unsigned char *defs){
-  int64_t rawvalue;
-  unsigned word[3];
-  int j;
-  unsigned char select;
-  
-  // convert the six individual bytes to a long long (8 byte) integer.
-  // This is the value that we'll eventually return.
-  rawvalue = 0;
-  for (j=0; j<6; j++) {
-    // This looks a bit roundabout, but is necessary.  Don't
-    // succumb to the temptation to use raw[j]<<(8*j) since under
-    // the normal rules this will be promoted to the native type.
-    // On a 32 bit machine this might then overflow.
-    int64_t temp;
-    temp = attribute->raw[j];
-    temp <<= 8*j;
-    rawvalue |= temp;
-  }
-
-  // convert quantities to three two-byte words
-  for (j=0; j<3; j++){
-    word[j] = attribute->raw[2*j+1];
-    word[j] <<= 8;
-    word[j] |= attribute->raw[2*j];
-  }
-  
-  // if no data array, Attributes have default interpretations
-  if (defs)
-    select=defs[attribute->id];
-  else
-    select=0;
-
-  // Print six one-byte quantities.
-  if (select==253){
-    for (j=0; j<5; j++)
-      out+=sprintf(out, "%d ", attribute->raw[5-j]);
-    out+=sprintf(out, "%d ", attribute->raw[0]);
-    return rawvalue;
-  } 
-  
-  // Print three two-byte quantities
-  if (select==254){
-    out+=sprintf(out, "%d %d %d", word[2], word[1], word[0]); 
-    return rawvalue;
-  } 
-  
-  // Print one six-byte quantity
-  if (select==255){
-    out+=sprintf(out, "%"PRIu64, rawvalue);
-    return rawvalue;
+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;
   }
 
-  // This switch statement is where we handle Raw attributes
-  // that are stored in an unusual vendor-specific format,
-  switch (attribute->id){
-    // Spin-up time
-  case 3:
-    out+=sprintf(out, "%d", word[0]);
-    // if second nonzero then it stores the average spin-up time
-    if (word[1])
-      out+=sprintf(out, " (Average %d)", word[1]);
-    break;
-    // Power on time
-  case 9:
-    if (select==1){
-      // minutes
-      int64_t tmp1=rawvalue/60;
-      int64_t tmp2=rawvalue%60;
-      out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
-    }
-    else if (select==3){
-      // seconds
-      int64_t hours=rawvalue/3600;
-      int64_t minutes=(rawvalue-3600*hours)/60;
-      int64_t seconds=rawvalue%60;
-      out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m+%02"PRIu64"s", hours, minutes, seconds);
-    }
-    else if (select==4){
-      // 30-second counter
-      int64_t tmp1=rawvalue/120;
-      int64_t tmp2=(rawvalue-120*tmp1)/2;
-      out+=sprintf(out, "%"PRIu64"h+%02"PRIu64"m", tmp1, tmp2);
-    }
-    else
-      // hours
-      out+=sprintf(out, "%"PRIu64, rawvalue);  //stored in hours
-    break;
-    // Temperature
-  case 190:
-    ataPrintTemperatureValue(out, attribute->raw, word);
-    break;
-   // Load unload cycles
-  case 193:
-    if (select==1){
-      // loadunload
-      long load  =attribute->raw[0] + (attribute->raw[1]<<8) + (attribute->raw[2]<<16);
-      long unload=attribute->raw[3] + (attribute->raw[4]<<8) + (attribute->raw[5]<<16);
-      out+=sprintf(out, "%lu/%lu", load, unload);
-    }
-    else
-      // associated
-      out+=sprintf(out, "%"PRIu64, rawvalue);
-    break;
-    // Temperature
-  case 194:
-    if (select==1){
-      // ten times temperature in Celsius
-      int deg=word[0]/10;
-      int tenths=word[0]%10;
-      out+=sprintf(out, "%d.%d", deg, tenths);
-    }
-    else if (select==2)
-      // unknown attribute
-      out+=sprintf(out, "%"PRIu64, rawvalue);
-    else
-      ataPrintTemperatureValue(out, attribute->raw, word);
-    break;
-  default:
-    out+=sprintf(out, "%"PRIu64, rawvalue);
+  if (   -60 <= t1 && t1 <= t && t <= t2 && t2 <= 120
+      && !(t1 == -1 && t2 <= 0)                      ) {
+    lo = t1; hi = t2;
+    return true;
   }
-  
-  // Return the full value
-  return rawvalue;
+  return false;
 }
 
-
-// Note some attribute names appear redundant because different
-// manufacturers use different attribute IDs for an attribute with the
-// same name.  The variable val should contain a non-zero value if a particular
-// attributes has a non-default interpretation.
-void ataPrintSmartAttribName(char *out, unsigned char id, unsigned char *definitions){
-  char *name;
-  unsigned char val;
-
-  // If no data array, use default interpretations
-  if (definitions)
-    val=definitions[id];
-  else
-    val=0;
-
-  switch (id){
-    
-  case 1:
-    name="Raw_Read_Error_Rate";
-    break;
-  case 2:
-    name="Throughput_Performance";
-    break;
-  case 3:
-    name="Spin_Up_Time";
-    break;
-  case 4:
-    name="Start_Stop_Count";
-    break;
-  case 5:
-    name="Reallocated_Sector_Ct";
-    break;
-  case 6:
-    name="Read_Channel_Margin";
-    break;
-  case 7:
-    name="Seek_Error_Rate";
-    break;
-  case 8:
-    name="Seek_Time_Performance";
-    break;
-  case 9:
-    switch (val) {
-    case 1:
-      name="Power_On_Minutes";
-      break;
-    case 2:
-      name="Temperature_Celsius";
-      break;
-    case 3:
-      name="Power_On_Seconds";
-      break;
-    case 4:
-      name="Power_On_Half_Minutes";
-      break;
-    default:
-      name="Power_On_Hours";
-      break;
-    }
+// Format attribute raw value.
+std::string ata_format_attr_raw_value(const ata_smart_attribute & attr,
+                                      const ata_vendor_attr_defs & defs)
+{
+  // Get 48 bit or 64 bit raw value
+  uint64_t rawvalue = ata_get_attr_raw_value(attr, defs);
+
+  // Split into bytes and words
+  unsigned char raw[6];
+  raw[0] = (unsigned char) rawvalue;
+  raw[1] = (unsigned char)(rawvalue >>  8);
+  raw[2] = (unsigned char)(rawvalue >> 16);
+  raw[3] = (unsigned char)(rawvalue >> 24);
+  raw[4] = (unsigned char)(rawvalue >> 32);
+  raw[5] = (unsigned char)(rawvalue >> 40);
+  unsigned word[3];
+  word[0] = raw[0] | (raw[1] << 8);
+  word[1] = raw[2] | (raw[3] << 8);
+  word[2] = raw[4] | (raw[5] << 8);
+
+  // Get print format
+  ata_attr_raw_format format = defs[attr.id].raw_format;
+  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;
+  switch (format) {
+  case RAWFMT_RAW8:
+    s = strprintf("%d %d %d %d %d %d",
+      raw[5], raw[4], raw[3], raw[2], raw[1], raw[0]);
     break;
-  case 10:
-    name="Spin_Retry_Count";
+
+  case RAWFMT_RAW16:
+    s = strprintf("%u %u %u", word[2], word[1], word[0]);
     break;
-  case 11:
-    name="Calibration_Retry_Count";
+
+  case RAWFMT_RAW48:
+  case RAWFMT_RAW56:
+  case RAWFMT_RAW64:
+    s = strprintf("%" PRIu64, rawvalue);
     break;
-  case 12:
-    name="Power_Cycle_Count";
+
+  case RAWFMT_HEX48:
+    s = strprintf("0x%012" PRIx64, rawvalue);
     break;
-  case 13:
-    name="Read_Soft_Error_Rate";
+
+  case RAWFMT_HEX56:
+    s = strprintf("0x%014" PRIx64, rawvalue);
     break;
-  case 187:
-    name="Reported_Uncorrect";
+
+  case RAWFMT_HEX64:
+    s = strprintf("0x%016" PRIx64, rawvalue);
     break;
-  case 189:
-    name="High_Fly_Writes";
+
+  case RAWFMT_RAW16_OPT_RAW16:
+    s = strprintf("%u", word[0]);
+    if (word[1] || word[2])
+      s += strprintf(" (%u %u)", word[2], word[1]);
     break;
-  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.
-    name="Airflow_Temperature_Cel";
+
+  case RAWFMT_RAW16_OPT_AVG16:
+    s = strprintf("%u", word[0]);
+    if (word[1])
+      s += strprintf(" (Average %u)", word[1]);
     break;
-  case 191:
-    name="G-Sense_Error_Rate";
+
+  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 192:
-    switch (val) {
-    case 1:
-      // Fujitsu
-      name="Emergency_Retract_Cycle_Ct";
-      break;
-    default:
-      name="Power-Off_Retract_Count";
-      break;
-    }
+
+  case RAWFMT_RAW24_DIV_RAW24:
+    s = strprintf("%u/%u",
+      (unsigned)(rawvalue >> 24), (unsigned)(rawvalue & 0x00ffffffULL));
     break;
-  case 193:
-    name="Load_Cycle_Count";
+
+  case RAWFMT_RAW24_DIV_RAW32:
+    s = strprintf("%u/%u",
+      (unsigned)(rawvalue >> 32), (unsigned)(rawvalue & 0xffffffffULL));
     break;
-  case 194:
-    switch (val){
-    case 1:
-      // Samsung SV1204H with RK100-13 firmware
-      name="Temperature_Celsius_x10";
-      break;
-    case 2:
-      // for disks with no temperature Attribute
-      name="Unknown_Attribute";
-      break;
-    default:
-      name="Temperature_Celsius";
-      break;
+
+  case RAWFMT_MIN2HOUR:
+    {
+      // minutes
+      int64_t temp = word[0]+(word[1]<<16);
+      int64_t tmp1 = temp/60;
+      int64_t tmp2 = temp%60;
+      s = strprintf("%" PRIu64 "h+%02" PRIu64 "m", tmp1, tmp2);
+      if (word[2])
+        s += strprintf(" (%u)", word[2]);
     }
     break;
-  case 195:
-    // Fujitsu name="ECC_On_The_Fly_Count";
-    name="Hardware_ECC_Recovered";
-    break;
-  case 196:
-    name="Reallocated_Event_Count";
-    break;
-  case 197:
-    name="Current_Pending_Sector";
-    break;
-  case 198:
-    switch (val){
-    case 1:
-      // Fujitsu
-      name="Off-line_Scan_UNC_Sector_Ct";
-      break;
-    default:
-      name="Offline_Uncorrectable";
-      break;
+
+  case RAWFMT_SEC2HOUR:
+    {
+      // seconds
+      int64_t hours = rawvalue/3600;
+      int64_t minutes = (rawvalue-3600*hours)/60;
+      int64_t seconds = rawvalue%60;
+      s = strprintf("%" PRIu64 "h+%02" PRIu64 "m+%02" PRIu64 "s", hours, minutes, seconds);
     }
     break;
-  case 199:
-    name="UDMA_CRC_Error_Count";
-    break;
-  case 200:
-    switch (val) {
-    case 1:
-      // Fujitsu MHS2020AT
-      name="Write_Error_Count";
-      break;
-    default:
-      // Western Digital
-      name="Multi_Zone_Error_Rate";
-      break;
+
+  case RAWFMT_HALFMIN2HOUR:
+    {
+      // 30-second counter
+      int64_t hours = rawvalue/120;
+      int64_t minutes = (rawvalue-120*hours)/2;
+      s += strprintf("%" PRIu64 "h+%02" PRIu64 "m", hours, minutes);
     }
     break;
-  case 201:
-    switch (val) {
-    case 1:
-      // Fujitsu
-      name="Detected_TA_Count";
-      break;
-    default:
-      name="Soft_Read_Error_Rate";
-      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 202:
-    // Fujitsu
-    name="TA_Increase_Count";
-    // Maxtor: Data Address Mark Errors
-    break;
-  case 203:
-    // Fujitsu
-    name="Run_Out_Cancel";
-    // Maxtor: ECC Errors
-    break;
-  case 204:
-    // Fujitsu
-    name="Shock_Count_Write_Opern";
-    // Maxtor: Soft ECC Correction
-    break;
-  case 205:
-    // Fujitsu
-    name="Shock_Rate_Write_Opern";
-    // Maxtor: Thermal Aspirates
-    break;
-  case 206:
-    // Fujitsu
-    name="Flying_Height";
-    break;
-  case 207:
-    // Maxtor
-    name="Spin_High_Current";
-    break;
-  case 208:
-    // Maxtor
-    name="Spin_Buzz";
-    break;
-  case 209:
-    // Maxtor
-    name="Offline_Seek_Performnce";
-    break;
-  case 220:
-    switch (val) {
-    case 1:
-      name="Temperature_Celsius";
-      break;
-    default:
-      name="Disk_Shift";
-      break;
+
+  case RAWFMT_TEMPMINMAX:
+    // Temperature
+    {
+      // Search for possible min/max values
+      // [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)
+      // 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;
+      }
+      else
+        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;
-  case 221:
-    name="G-Sense_Error_Rate";
-    break;
-  case 222:
-    name="Loaded_Hours";
-    break;
-  case 223:
-    name="Load_Retry_Count";
-    break;
-  case 224:
-    name="Load_Friction";
-    break;
-  case 225:
-    name="Load_Cycle_Count";
-    break;
-  case 226:
-    name="Load-in_Time";
-    break;
-  case 227:
-    name="Torq-amp_Count";
-    break;
-  case 228:
-    name="Power-off_Retract_Count";
-    break;
-  case 230:
-    // seen in IBM DTPA-353750
-    name="Head_Amplitude";
-    break;
-  case 231:
-    name="Temperature_Celsius";
-    break;
-  case 240:
-    name="Head_Flying_Hours";
-    break;
-  case 250:
-    name="Read_Error_Retry_Rate";
+
+  case RAWFMT_TEMP10X:
+    // ten times temperature in Celsius
+    s = strprintf("%d.%d", word[0]/10, word[0]%10);
     break;
+
   default:
-    name="Unknown_Attribute";
+    s = "?"; // Should not happen
     break;
   }
-  sprintf(out,"%3hu %s",(short int)id,name);
-  return;
-}
 
-// Returns raw value of Attribute with ID==id. This will be in the
-// range 0 to 2^48-1 inclusive.  If the Attribute does not exist,
-// return -1.
-int64_t ATAReturnAttributeRawValue(unsigned char id, struct ata_smart_values *data) {
-  int i;
+  return s;
+}
 
-  // valid Attribute IDs are in the range 1 to 255 inclusive.
-  if (!id || !data)
+// 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 {
+     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.
+int ata_find_attr_index(unsigned char id, const ata_smart_values & smartval)
+{
+  if (!id)
     return -1;
-  
-  // loop over Attributes to see if there is one with the desired ID
-  for (i=0; i<NUMBER_ATA_SMART_ATTRIBUTES; i++) {
-    struct ata_smart_attribute *ap = data->vendor_attributes + i;
-    if (ap->id == id) {
-      // we've found the desired Attribute.  Return its value
-      int64_t rawvalue=0;
-      int j;
-
-      for (j=0; j<6; j++) {
-       // This looks a bit roundabout, but is necessary.  Don't
-       // succumb to the temptation to use raw[j]<<(8*j) since under
-       // the normal rules this will be promoted to the native type.
-       // On a 32 bit machine this might then overflow.
-       int64_t temp;
-       temp = ap->raw[j];
-       temp <<= 8*j;
-       rawvalue |= temp;
-      } // loop over j
-      return rawvalue;
-    } // found desired Attribute
-  } // loop over Attributes
-  
-  // fall-through: no such Attribute found
+  for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
+    if (smartval.vendor_attributes[i].id == id)
+      return i;
+  }
   return -1;
 }
 
 // Return Temperature Attribute raw value selected according to possible
 // non-default interpretations. If the Attribute does not exist, return 0
-unsigned char ATAReturnTemperatureValue(/*const*/ struct ata_smart_values *data, const unsigned char *defs){
-  int i;
-  for (i = 0; i < 3; i++) {
-    static const unsigned char ids[3] = {194, 9, 220};
+unsigned char ata_return_temperature_value(const ata_smart_values * data, const ata_vendor_attr_defs & defs)
+{
+  for (int i = 0; i < 4; i++) {
+    static const unsigned char ids[4] = {194, 190, 9, 220};
     unsigned char id = ids[i];
-    unsigned char select = (defs ? defs[id] : 0);
-    int64_t raw; unsigned temp;
-    if (!(   (id == 194 && select <= 1)   // ! -v 194,unknown
-          || (id == 9 && select == 2)     // -v 9,temp
-          || (id == 220 && select == 1))) // -v 220,temp
+    const ata_attr_raw_format format = defs[id].raw_format;
+    if (!(   ((id == 194 || id == 190) && format == RAWFMT_DEFAULT)
+          || format == RAWFMT_TEMPMINMAX || format == RAWFMT_TEMP10X))
       continue;
-    raw = ATAReturnAttributeRawValue(id, data);
-    if (raw < 0)
+    int idx = ata_find_attr_index(id, *data);
+    if (idx < 0)
       continue;
-    temp = (unsigned short)raw; // ignore possible min/max values in high words
-    if (id == 194 && select == 1) // -v 194,10xCelsius
-      temp = (temp+5) / 10;
-    if (!(0 < temp && temp <= 255))
+    uint64_t raw = ata_get_attr_raw_value(data->vendor_attributes[idx], defs);
+    unsigned temp;
+    // ignore possible min/max values in high words
+    if (format == RAWFMT_TEMP10X) // -v N,temp10x
+      temp = ((unsigned short)raw + 5) / 10;
+    else
+      temp = (unsigned char)raw;
+    if (!(0 < temp && temp < 128))
       continue;
     return temp;
   }
@@ -2085,43 +2185,44 @@ unsigned char ATAReturnTemperatureValue(/*const*/ struct ata_smart_values *data,
   return 0;
 }
 
+
 // Read SCT Status
-int ataReadSCTStatus(int device, ata_sct_status_response * sts)
+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;
   }
 
   // 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
   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;
 }
 
-// Read SCT Temperature History Table and Status
-int ataReadSCTTempHist(int device, ata_sct_temperature_history_table * tmh,
+// 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) {
@@ -2137,16 +2238,23 @@ int ataReadSCTTempHist(int device, ata_sct_temperature_history_table * tmh,
   cmd.function_code = 1; // Read table
   cmd.table_id      = 2; // Temperature History Table
 
+  // swap endian order if needed
+  if (isbigendian()) {
+    SWAPV(cmd.action_code);
+    SWAPV(cmd.function_code);
+    SWAPV(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;
   }
 
@@ -2155,28 +2263,106 @@ int ataReadSCTTempHist(int device, ata_sct_temperature_history_table * tmh,
     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;
   }
 
   // swap endian order if needed
   if (isbigendian()){
-    swapx(&tmh->format_version);
-    swapx(&tmh->sampling_period);
-    swapx(&tmh->interval);
+    SWAPV(tmh->format_version);
+    SWAPV(tmh->sampling_period);
+    SWAPV(tmh->interval);
+    SWAPV(tmh->cb_index);
+    SWAPV(tmh->cb_size);
   }
+  return 0;
+}
 
-  // Check format version
-  if (tmh->format_version != 2) {
-    pout("Error unknown SCT Temperature History Format Version (%u), should be 2.\n", tmh->format_version);
+// 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;
+  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 Feature 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;
   }
-  return 0;
+
+  ata_sct_feature_control_command cmd; memset(&cmd, 0, sizeof(cmd));
+  // 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  = feature_code;
+  cmd.state         = state;
+  cmd.option_flags  = (persistent ? 0x01 : 0x00);
+
+  // swap endian order if needed
+  if (isbigendian()) {
+    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
+  // 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) Feature Control Command failed: %s\n",
+      (!set ? 'G' : 'S'), device->get_errmsg());
+    return -1;
+  }
+  state = out.out_regs.sector_count | (out.out_regs.lba_low << 8);
+
+  // re-read and check SCT status
+  if (ataReadSCTStatus(device, &sts))
+    return -1;
+
+  if (!(sts.ext_status_code == 0 && sts.action_code == 4 && 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;
+  }
+  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(int device, unsigned interval, bool persistent)
+int ataSetSCTTempInterval(ata_device * device, unsigned interval, bool persistent)
 {
   // Check initial status
   ata_sct_status_response sts;
@@ -2199,9 +2385,18 @@ int ataSetSCTTempInterval(int device, unsigned interval, bool persistent)
   cmd.state         = interval;
   cmd.option_flags  = (persistent ? 0x01 : 0x00);
 
+  // swap endian order if needed
+  if (isbigendian()) {
+    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
   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;
   }
 
@@ -2210,33 +2405,154 @@ int ataSetSCTTempInterval(int device, unsigned interval, bool persistent)
     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()) {
+    SWAPV(cmd.action_code);
+    SWAPV(cmd.function_code);
+    SWAPV(cmd.selection_code);
+    SWAPV(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);
+}
+
 
 /////////////////////////////////////////////////////////////////////////////
 // Pseudo-device to parse "smartctl -r ataioctl,2 ..." output and simulate
 // an ATA device with same behaviour
 
-// Table of parsed commands, return value, data
-struct parsed_ata_command
-{ 
-  smart_command_set command;
-  int select;
-  int retval, errval;
-  char * data;
-};
+namespace {
+
+class parsed_ata_device
+: public /*implements*/ ata_device_with_command_set
+{
+public:
+  parsed_ata_device(smart_interface * intf, const char * dev_name);
+
+  virtual ~parsed_ata_device() throw();
+
+  virtual bool is_open() const;
+
+  virtual bool open();
+
+  virtual bool close();
 
-const int max_num_parsed_commands = 32;
-static parsed_ata_command parsed_command_table[max_num_parsed_commands];
-static int num_parsed_commands;
-static int next_replay_command;
-static bool replay_out_of_sync;
+  virtual bool ata_identify_is_cached() const;
 
+protected:
+  virtual int ata_command_interface(smart_command_set command, int select, char * data);
+
+private:
+  // Table of parsed commands, return value, data
+  struct parsed_ata_command
+  {
+    smart_command_set command;
+    int select;
+    int retval, errval;
+    char * data;
+  };
+
+  enum { max_num_commands = 32 };
+  parsed_ata_command m_command_table[max_num_commands];
+
+  int m_num_commands;
+  int m_next_replay_command;
+  bool m_replay_out_of_sync;
+  bool m_ata_identify_is_cached;
+};
 
 static const char * nextline(const char * s, int & lineno)
 {
@@ -2257,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;
@@ -2269,20 +2586,39 @@ 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;
   return atoi(src + srcmatch.rm_so);
 }
 
+parsed_ata_device::parsed_ata_device(smart_interface * intf, const char * dev_name)
+: smart_device(intf, dev_name, "ata", ""),
+  m_num_commands(0),
+  m_next_replay_command(0),
+  m_replay_out_of_sync(false),
+  m_ata_identify_is_cached(false)
+{
+  memset(m_command_table, 0, sizeof(m_command_table));
+}
+
+parsed_ata_device::~parsed_ata_device() throw()
+{
+  parsed_ata_device::close();
+}
+
+bool parsed_ata_device::is_open() const
+{
+  return (m_num_commands > 0);
+}
 
 // Parse stdin and build command table
-int parsedev_open(const char * pathname)
+bool parsed_ata_device::open()
 {
-  if (strcmp(pathname, "-")) {
-    errno = EINVAL; return -1;
-  }
+  const char * pathname = get_dev_name();
+  if (strcmp(pathname, "-"))
+    return set_err(EINVAL);
   pathname = "<stdin>";
   // Fill buffer
   char buffer[64*1024];
@@ -2293,20 +2629,16 @@ int parsedev_open(const char * pathname)
       break;
     size += nr;
   }
-  if (size <= 0) {
-    pout("%s: Unexpected EOF\n", pathname);
-    errno = ENOENT; return -1;
-  }
-  if (size >= (int)sizeof(buffer)) {
-    pout("%s: Buffer overflow\n", pathname);
-    errno = EIO; return -1;
-  }
+  if (size <= 0)
+    return set_err(ENOENT, "%s: Unexpected EOF", pathname);
+  if (size >= (int)sizeof(buffer))
+    return set_err(EIO, "%s: Buffer overflow", pathname);
   buffer[size] = 0;
 
   // Regex to match output from "-r ataioctl,2"
   static const char pattern[] = "^"
   "(" // (1
-    "REPORT-IOCTL: DeviceFD=[0-9]+ Command=([A-Z ]*[A-Z])" // (2)
+    "REPORT-IOCTL: DeviceF?D?=[^ ]+ Command=([A-Z ]*[A-Z])" // (2)
     "(" // (3
       "( InputParameter=([0-9]+))?" // (4 (5))
     "|"
@@ -2315,24 +2647,23 @@ int parsedev_open(const char * pathname)
     "[\r\n]" // EOL match necessary to match optional parts above
   "|"
     "===== \\[([A-Z ]*[A-Z])\\] DATA START " // (10)
+  "|"
+    "    *(En|Dis)abled status cached by OS, " // (11)
   ")"; // )
 
   // Compile regex
-  regex_t rex;
-  if (compileregex(&rex, pattern, REG_EXTENDED)) {
-    errno = EIO; return -1;
-  }
+  const regular_expression regex(pattern);
 
   // Parse buffer
   const char * errmsg = 0;
   int i = -1, state = 0, lineno = 1;
   for (const char * line = buffer; *line; line = nextline(line, lineno)) {
     // Match line
-    if (!(line[0] == 'R' || line[0] == '='))
+    if (!(line[0] == 'R' || line[0] == '=' || line[0] == ' '))
       continue;
-    const int nmatch = 1+10;
-    regmatch_t match[nmatch];
-    if (regexec(&rex, line, nmatch, match, 0))
+    const int nmatch = 1+11;
+    regular_expression::match_range match[nmatch];
+    if (!regex.execute(line, nmatch, match))
       continue;
 
     char cmdname[40];
@@ -2346,27 +2677,27 @@ int parsedev_open(const char * pathname)
         if (!(state == 0 || state == 2)) {
           errmsg = "Missing REPORT-IOCTL result"; break;
         }
-        if (++i >= max_num_parsed_commands) {
+        if (++i >= max_num_commands) {
           errmsg = "Too many ATA commands"; break;
         }
-        parsed_command_table[i].command = (smart_command_set)nc;
-        parsed_command_table[i].select = matchtoi(line, match[5], 0); // "InputParameter=%d"
+        m_command_table[i].command = (smart_command_set)nc;
+        m_command_table[i].select = matchtoi(line, match[5], 0); // "InputParameter=%d"
         state = 1;
       }
       else {
         // End of command
-        if (!(state == 1 && (int)parsed_command_table[i].command == nc)) {
+        if (!(state == 1 && (int)m_command_table[i].command == nc)) {
           errmsg = "Missing REPORT-IOCTL start"; break;
         }
-        parsed_command_table[i].retval = matchtoi(line, match[7], -1); // "returned %d"
-        parsed_command_table[i].errval = matchtoi(line, match[9], 0); // "errno=%d"
+        m_command_table[i].retval = matchtoi(line, match[7], -1); // "returned %d"
+        m_command_table[i].errval = matchtoi(line, match[9], 0); // "errno=%d"
         state = 2;
       }
     }
     else if (matchcpy(cmdname, sizeof(cmdname), line, match[10])) { // "===== [%s] DATA START "
       // Start of sector hexdump
       int nc = name2command(cmdname);
-      if (!(state == (nc == WRITE_LOG ? 1 : 2) && (int)parsed_command_table[i].command == nc)) {
+      if (!(state == (nc == WRITE_LOG ? 1 : 2) && (int)m_command_table[i].command == nc)) {
           errmsg = "Unexpected DATA START"; break;
       }
       line = nextline(line, lineno);
@@ -2391,10 +2722,13 @@ int parsedev_open(const char * pathname)
         free(data);
         errmsg = "Incomplete sector hex dump"; break;
       }
-      parsed_command_table[i].data = data;
+      m_command_table[i].data = data;
       if (nc != WRITE_LOG)
         state = 0;
     }
+    else if (match[11].rm_so > 0) { // "(En|Dis)abled status cached by OS"
+      m_ata_identify_is_cached = true;
+    }
   }
 
   if (!(state == 0 || state == 2))
@@ -2403,58 +2737,66 @@ int parsedev_open(const char * pathname)
   if (!errmsg && i < 0)
     errmsg = "No information found";
 
-  num_parsed_commands = i+1;
-  next_replay_command = 0;
-  replay_out_of_sync = false;
+  m_num_commands = i+1;
+  m_next_replay_command = 0;
+  m_replay_out_of_sync = false;
 
   if (errmsg) {
-    pout("%s(%d): Syntax error: %s\n", pathname, lineno, errmsg);
-    errno = EIO;
-    parsedev_close(0);
-    return -1;
+    close();
+    return set_err(EIO, "%s(%d): Syntax error: %s", pathname, lineno, errmsg);
   }
-  return 0;
+  return true;
 }
 
 // Report warnings and free command table 
-void parsedev_close(int /*fd*/)
+bool parsed_ata_device::close()
 {
-  if (replay_out_of_sync)
+  if (m_replay_out_of_sync)
       pout("REPLAY-IOCTL: Warning: commands replayed out of sync\n");
-  else if (next_replay_command != 0)
-      pout("REPLAY-IOCTL: Warning: %d command(s) not replayed\n", num_parsed_commands-next_replay_command);
+  else if (m_next_replay_command != 0)
+      pout("REPLAY-IOCTL: Warning: %d command(s) not replayed\n", m_num_commands-m_next_replay_command);
 
-  for (int i = 0; i < num_parsed_commands; i++) {
-    if (parsed_command_table[i].data) {
-      free(parsed_command_table[i].data); parsed_command_table[i].data = 0;
+  for (int i = 0; i < m_num_commands; i++) {
+    if (m_command_table[i].data) {
+      free(m_command_table[i].data); m_command_table[i].data = 0;
     }
   }
-  num_parsed_commands = 0;
+  m_num_commands = 0;
+  m_next_replay_command = 0;
+  m_replay_out_of_sync = false;
+  return true;
+}
+
+
+bool parsed_ata_device::ata_identify_is_cached() const
+{
+  return m_ata_identify_is_cached;
 }
 
+
 // Simulate ATA command from command table
-static int parsedev_command_interface(int /*fd*/, smart_command_set command, int select, char * data)
+int parsed_ata_device::ata_command_interface(smart_command_set command, int select, char * data)
 {
-  // Find command, try round-robin of out of sync
-  int i = next_replay_command;
+  // Find command, try round-robin if out of sync
+  int i = m_next_replay_command;
   for (int j = 0; ; j++) {
-    if (j >= num_parsed_commands) {
+    if (j >= m_num_commands) {
       pout("REPLAY-IOCTL: Warning: Command not found\n");
       errno = ENOSYS;
       return -1;
     }
-    if (parsed_command_table[i].command == command && parsed_command_table[i].select == select)
+    if (m_command_table[i].command == command && m_command_table[i].select == select)
       break;
-    if (!replay_out_of_sync) {
-      replay_out_of_sync = true;
+    if (!m_replay_out_of_sync) {
+      m_replay_out_of_sync = true;
       pout("REPLAY-IOCTL: Warning: Command #%d is out of sync\n", i+1);
     }
-    if (++i >= num_parsed_commands)
+    if (++i >= m_num_commands)
       i = 0;
   }
-  next_replay_command = i;
-  if (++next_replay_command >= num_parsed_commands)
-    next_replay_command = 0;
+  m_next_replay_command = i;
+  if (++m_next_replay_command >= m_num_commands)
+    m_next_replay_command = 0;
 
   // Return command data
   switch (command) {
@@ -2463,11 +2805,11 @@ static int parsedev_command_interface(int /*fd*/, smart_command_set command, int
     case READ_VALUES:
     case READ_THRESHOLDS:
     case READ_LOG:
-      if (parsed_command_table[i].data)
-        memcpy(data, parsed_command_table[i].data, 512);
+      if (m_command_table[i].data)
+        memcpy(data, m_command_table[i].data, 512);
       break;
     case WRITE_LOG:
-      if (!(parsed_command_table[i].data && !memcmp(data, parsed_command_table[i].data, 512)))
+      if (!(m_command_table[i].data && !memcmp(data, m_command_table[i].data, 512)))
         pout("REPLAY-IOCTL: Warning: WRITE LOG data does not match\n");
       break;
     case CHECK_POWER_MODE:
@@ -2476,7 +2818,14 @@ static int parsedev_command_interface(int /*fd*/, smart_command_set command, int
       break;
   }
 
-  if (parsed_command_table[i].errval)
-    errno = parsed_command_table[i].errval;
-  return parsed_command_table[i].retval;
+  if (m_command_table[i].errval)
+    errno = m_command_table[i].errval;
+  return m_command_table[i].retval;
+}
+
+} // namespace
+
+ata_device * get_parsed_ata_device(smart_interface * intf, const char * dev_name)
+{
+  return new parsed_ata_device(intf, dev_name);
 }