]> git.proxmox.com Git - mirror_smartmontools-debian.git/blobdiff - os_linux.cpp
import smartmontools 7.0
[mirror_smartmontools-debian.git] / os_linux.cpp
index 20f66b9bbcb72068fd5d97b60fc4db8bab6b843f..cfa1a518d064b9356f465bd2f2ce48eba1e4ec78 100644 (file)
@@ -1,25 +1,32 @@
 /*
  *  os_linux.cpp
  *
- * Home page of code is: http://smartmontools.sourceforge.net
+ * Home page of code is: http://www.smartmontools.org
  *
- * Copyright (C) 2003-10 Bruce Allen <smartmontools-support@lists.sourceforge.net>
- * Copyright (C) 2003-10 Doug Gilbert <dougg@torque.net>
- * Copyright (C) 2008    Hank Wu <hank@areca.com.tw>
- * Copyright (C) 2008    Oliver Bock <brevilo@users.sourceforge.net>
- * Copyright (C) 2008-10 Christian Franke <smartmontools-support@lists.sourceforge.net>
- * Copyright (C) 2008    Jordan Hargrave <jordan_hargrave@dell.com>
+ * Copyright (C) 2003-11 Bruce Allen
+ * Copyright (C) 2003-11 Doug Gilbert <dgilbert@interlog.com>
+ * Copyright (C) 2008-18 Christian Franke
  *
- *  Parts of this file are derived from code that was
+ * Original AACRaid code:
+ *  Copyright (C) 2014    Raghava Aditya <raghava.aditya@pmcs.com>
+ *
+ * Original Areca code:
+ *  Copyright (C) 2008-12 Hank Wu <hank@areca.com.tw>
+ *  Copyright (C) 2008    Oliver Bock <brevilo@users.sourceforge.net>
+ *
+ * Original MegaRAID code:
+ *  Copyright (C) 2008    Jordan Hargrave <jordan_hargrave@dell.com>
+ *
+ * 3ware code was derived from code that was:
  *
  *  Written By: Adam Radford <linux@3ware.com>
  *  Modifications By: Joel Jacobson <linux@3ware.com>
- *                   Arnaldo Carvalho de Melo <acme@conectiva.com.br>
+ *                    Arnaldo Carvalho de Melo <acme@conectiva.com.br>
  *                    Brad Strand <linux@3ware.com>
  *
  *  Copyright (C) 1999-2003 3ware Inc.
  *
- *  Kernel compatablity By:     Andre Hedrick <andre@suse.com>
+ *  Kernel compatibility By:    Andre Hedrick <andre@suse.com>
  *  Non-Copyright (C) 2000      Andre Hedrick <andre@suse.com>
  *
  * Other ars of this file are derived from code that was
  * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
  * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
  *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2, or (at your option)
- * any later version.
- *
- * You should have received a copy of the GNU General Public License
- * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
- *
- * This code was originally developed as a Senior Thesis by Michael Cornwell
- * at the Concurrent Systems Laboratory (now part of the Storage Systems
- * Research Center), Jack Baskin School of Engineering, University of
- * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
- *
+ * SPDX-License-Identifier: GPL-2.0-or-later
  */
 
 // This file contains the linux-specific IOCTL parts of
 #include <scsi/scsi.h>
 #include <scsi/scsi_ioctl.h>
 #include <scsi/sg.h>
+#include <linux/bsg.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/ioctl.h>
 #include <sys/stat.h>
-#include <sys/file.h>
+#include <sys/utsname.h>
 #include <unistd.h>
+#include <stddef.h>  // for offsetof()
 #include <sys/uio.h>
 #include <sys/types.h>
-#ifndef makedev // old versions of types.h do not include sysmacros.h
+#include <dirent.h>
+#ifdef HAVE_SYS_SYSMACROS_H
+// glibc 2.25: The inclusion of <sys/sysmacros.h> by <sys/types.h> is
+// deprecated.  A warning is printed if major(), minor() or makedev()
+// is used but <sys/sysmacros.h> is not included.
 #include <sys/sysmacros.h>
 #endif
-#ifdef WITH_SELINUX
+#ifdef HAVE_LIBSELINUX
 #include <selinux/selinux.h>
 #endif
 
-#include "int64.h"
 #include "atacmds.h"
-#include "extern.h"
 #include "os_linux.h"
 #include "scsicmds.h"
 #include "utility.h"
-#include "extern.h"
 #include "cciss.h"
 #include "megaraid.h"
+#include "aacraid.h"
+#include "nvmecmds.h"
 
 #include "dev_interface.h"
 #include "dev_ata_cmd_set.h"
+#include "dev_areca.h"
+
+// "include/uapi/linux/nvme_ioctl.h" from Linux kernel sources
+#include "linux_nvme_ioctl.h" // nvme_passthru_cmd, NVME_IOCTL_ADMIN_CMD
 
 #ifndef ENOTSUP
 #define ENOTSUP ENOSYS
 
 #define ARGUSED(x) ((void)(x))
 
-const char *os_XXXX_c_cvsid="$Id: os_linux.cpp 3052 2010-01-28 19:51:24Z chrfranke $" \
-ATACMDS_H_CVSID CONFIG_H_CVSID INT64_H_CVSID OS_LINUX_H_CVSID SCSICMDS_H_CVSID UTILITY_H_CVSID;
-
-/* for passing global control variables */
-// (con->reportscsiioctl only)
-extern smartmonctrl *con;
-
+const char * os_linux_cpp_cvsid = "$Id: os_linux.cpp 4854 2018-12-11 20:32:29Z chrfranke $"
+  OS_LINUX_H_CVSID;
+extern unsigned char failuretest_permissive;
 
 namespace os_linux { // No need to publish anything, name provided for Doxygen
 
@@ -126,13 +126,15 @@ protected:
   int get_fd() const
     { return m_fd; }
 
+  void set_fd(int fd)
+    { m_fd = fd; }
+
 private:
   int m_fd; ///< filedesc, -1 if not open.
   int m_flags; ///< Flags for ::open()
   int m_retry_flags; ///< Flags to retry ::open(), -1 if no retry
 };
 
-
 linux_smart_device::~linux_smart_device() throw()
 {
   if (m_fd >= 0)
@@ -187,24 +189,25 @@ bool linux_smart_device::close()
 // examples for smartctl
 static const char  smartctl_examples[] =
                  "=================================================== SMARTCTL EXAMPLES =====\n\n"
-                 "  smartctl --all /dev/hda                    (Prints all SMART information)\n\n"
-                 "  smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda\n"
+                 "  smartctl --all /dev/sda                    (Prints all SMART information)\n\n"
+                 "  smartctl --smart=on --offlineauto=on --saveauto=on /dev/sda\n"
                  "                                              (Enables SMART on first disk)\n\n"
-                 "  smartctl --test=long /dev/hda          (Executes extended disk self-test)\n\n"
-                 "  smartctl --attributes --log=selftest --quietmode=errorsonly /dev/hda\n"
+                 "  smartctl --test=long /dev/sda          (Executes extended disk self-test)\n\n"
+                 "  smartctl --attributes --log=selftest --quietmode=errorsonly /dev/sda\n"
                  "                                      (Prints Self-Test & Attribute errors)\n"
                  "  smartctl --all --device=3ware,2 /dev/sda\n"
                  "  smartctl --all --device=3ware,2 /dev/twe0\n"
                  "  smartctl --all --device=3ware,2 /dev/twa0\n"
+                 "  smartctl --all --device=3ware,2 /dev/twl0\n"
                  "          (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
                  "  smartctl --all --device=hpt,1/1/3 /dev/sda\n"
                  "          (Prints all SMART info for the SATA disk attached to the 3rd PMPort\n"
                  "           of the 1st channel on the 1st HighPoint RAID controller)\n"
-                 "  smartctl --all --device=areca,3 /dev/sg2\n"
-                 "          (Prints all SMART info for 3rd ATA disk on Areca RAID controller)\n"
+                 "  smartctl --all --device=areca,3/1 /dev/sg2\n"
+                 "          (Prints all SMART info for 3rd ATA disk of the 1st enclosure\n"
+                 "           on Areca RAID controller)\n"
   ;
 
-
 /////////////////////////////////////////////////////////////////////////////
 /// Linux ATA support
 
@@ -245,7 +248,6 @@ linux_ata_device::linux_ata_device(smart_interface * intf, const char * dev_name
 //   0 if the command succeeded and disk SMART status is "OK"
 //   1 if the command succeeded and disk SMART status is "FAILING"
 
-
 #define BUFFER_LENGTH (4+512)
 
 int linux_ata_device::ata_command_interface(smart_command_set command, int select, char * data)
@@ -349,7 +351,6 @@ int linux_ata_device::ata_command_interface(smart_command_set command, int selec
     unsigned char task[sizeof(ide_task_request_t)+512];
     ide_task_request_t *reqtask=(ide_task_request_t *) task;
     task_struct_t      *taskfile=(task_struct_t *) reqtask->io_ports;
-    int retval;
 
     memset(task,      0, sizeof(task));
 
@@ -370,9 +371,9 @@ int linux_ata_device::ata_command_interface(smart_command_set command, int selec
     // copy user data into the task request structure
     memcpy(task+sizeof(ide_task_request_t), data, 512);
 
-    if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASKFILE, task))) {
-      if (retval==-EINVAL)
-        pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
+    if (ioctl(get_fd(), HDIO_DRIVE_TASKFILE, task)) {
+      if (errno==EINVAL)
+        pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASK_IOCTL set\n");
       return -1;
     }
     return 0;
@@ -381,8 +382,6 @@ int linux_ata_device::ata_command_interface(smart_command_set command, int selec
   // There are two different types of ioctls().  The HDIO_DRIVE_TASK
   // one is this:
   if (command==STATUS_CHECK || command==AUTOSAVE || command==AUTO_OFFLINE){
-    int retval;
-
     // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
     // have to read the IDE driver source code.  Sigh.
     // buff[0]: ATA COMMAND CODE REGISTER
@@ -398,8 +397,8 @@ int linux_ata_device::ata_command_interface(smart_command_set command, int selec
     buff[4]=normal_lo;
     buff[5]=normal_hi;
 
-    if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASK, buff))) {
-      if (retval==-EINVAL) {
+    if (ioctl(get_fd(), HDIO_DRIVE_TASK, buff)) {
+      if (errno==EINVAL) {
         pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
         pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
       }
@@ -503,28 +502,48 @@ int linux_ata_device::ata_command_interface(smart_command_set command, int selec
 #define SCSI_IOCTL_SEND_COMMAND 1
 #endif
 
-#define SG_IO_PRESENT_UNKNOWN 0
-#define SG_IO_PRESENT_YES 1
-#define SG_IO_PRESENT_NO 2
+#define SG_IO_USE_DETECT 0
+#define SG_IO_UNSUPP 1
+#define SG_IO_USE_V3 3
+#define SG_IO_USE_V4 4
 
 static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
-                         int unknown);
+                         int sgio_ver);
 static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report);
 
-static int sg_io_state = SG_IO_PRESENT_UNKNOWN;
+static int sg_io_state = SG_IO_USE_DETECT;
 
 /* Preferred implementation for issuing SCSI commands in linux. This
  * function uses the SG_IO ioctl. Return 0 if command issued successfully
  * (various status values should still be checked). If the SCSI command
  * cannot be issued then a negative errno value is returned. */
 static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
-                         int unknown)
+                         int sg_io_ver)
 {
 #ifndef SG_IO
     ARGUSED(dev_fd); ARGUSED(iop); ARGUSED(report);
     return -ENOTTY;
 #else
-    struct sg_io_hdr io_hdr;
+
+    /* we are filling structures for both versions, but using only one requested */
+    struct sg_io_hdr io_hdr_v3;
+    struct sg_io_v4  io_hdr_v4;
+
+#ifdef SCSI_CDB_CHECK
+    bool ok = is_scsi_cdb(iop->cmnd, iop->cmnd_len);
+    if (! ok) {
+       int n = iop->cmnd_len;
+       const unsigned char * ucp = iop->cmnd;
+
+       pout(">>>>>>>> %s: cdb seems invalid, opcode=0x%x, len=%d, cdb:\n",
+            __func__, ((n > 0) ? ucp[0] : 0), n);
+        if (n > 0) {
+           if (n > 16)
+               pout("  <<truncating to first 16 bytes>>\n");
+           dStrHex((const uint8_t *)ucp, ((n > 16) ? 16 : n), 1);
+       }
+     }
+#endif
 
     if (report > 0) {
         int k, j;
@@ -533,6 +552,7 @@ static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
         char buff[256];
         const int sz = (int)sizeof(buff);
 
+        pout(">>>> do_scsi_cmnd_io: sg_io_ver=%d\n", sg_io_ver);
         np = scsi_get_opcode_name(ucp[0]);
         j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
         for (k = 0; k < (int)iop->cmnd_len; ++k)
@@ -541,57 +561,120 @@ static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
             (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
             int trunc = (iop->dxfer_len > 256) ? 1 : 0;
 
-            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
-                          "data, len=%d%s:\n", (int)iop->dxfer_len,
-                          (trunc ? " [only first 256 bytes shown]" : ""));
-            dStrHex((const char *)iop->dxferp,
-                    (trunc ? 256 : iop->dxfer_len) , 1);
+            snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
+                     "data, len=%d%s:\n", (int)iop->dxfer_len,
+                     (trunc ? " [only first 256 bytes shown]" : ""));
+            dStrHex(iop->dxferp, (trunc ? 256 : iop->dxfer_len) , 1);
         }
         else
-            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
+            snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
         pout("%s", buff);
     }
-    memset(&io_hdr, 0, sizeof(struct sg_io_hdr));
-    io_hdr.interface_id = 'S';
-    io_hdr.cmd_len = iop->cmnd_len;
-    io_hdr.mx_sb_len = iop->max_sense_len;
-    io_hdr.dxfer_len = iop->dxfer_len;
-    io_hdr.dxferp = iop->dxferp;
-    io_hdr.cmdp = iop->cmnd;
-    io_hdr.sbp = iop->sensep;
+    memset(&io_hdr_v3, 0, sizeof(struct sg_io_hdr));
+    memset(&io_hdr_v4, 0, sizeof(struct sg_io_v4));
+
+    io_hdr_v3.interface_id =       'S';
+    io_hdr_v3.cmd_len =            iop->cmnd_len;
+    io_hdr_v3.mx_sb_len =          iop->max_sense_len;
+    io_hdr_v3.dxfer_len =          iop->dxfer_len;
+    io_hdr_v3.dxferp =             iop->dxferp;
+    io_hdr_v3.cmdp =               iop->cmnd;
+    io_hdr_v3.sbp =                iop->sensep;
     /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
        defaults to 60 seconds. */
-    io_hdr.timeout = ((0 == iop->timeout) ? 60 : iop->timeout) * 1000;
+    io_hdr_v3.timeout =         ((0 == iop->timeout) ? 60 : iop->timeout) * 1000;
+
+    io_hdr_v4.guard =              'Q';
+    io_hdr_v4.request_len =        iop->cmnd_len;
+    io_hdr_v4.request =            __u64(iop->cmnd);
+    io_hdr_v4.max_response_len =   iop->max_sense_len;
+    io_hdr_v4.response =           __u64(iop->sensep);
+    io_hdr_v4.timeout =            ((0 == iop->timeout) ? 60 : iop->timeout) * 1000; // msec
+
     switch (iop->dxfer_dir) {
         case DXFER_NONE:
-            io_hdr.dxfer_direction = SG_DXFER_NONE;
+            io_hdr_v3.dxfer_direction = SG_DXFER_NONE;
             break;
         case DXFER_FROM_DEVICE:
-            io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
+            io_hdr_v3.dxfer_direction = SG_DXFER_FROM_DEV;
+            io_hdr_v4.din_xfer_len =    iop->dxfer_len;
+            io_hdr_v4.din_xferp =       __u64(iop->dxferp);
             break;
         case DXFER_TO_DEVICE:
-            io_hdr.dxfer_direction = SG_DXFER_TO_DEV;
+            io_hdr_v3.dxfer_direction = SG_DXFER_TO_DEV;
+            io_hdr_v4.dout_xfer_len =   iop->dxfer_len;
+            io_hdr_v4.dout_xferp =      __u64(iop->dxferp);
             break;
         default:
             pout("do_scsi_cmnd_io: bad dxfer_dir\n");
             return -EINVAL;
     }
+
     iop->resp_sense_len = 0;
     iop->scsi_status = 0;
     iop->resid = 0;
-    if (ioctl(dev_fd, SG_IO, &io_hdr) < 0) {
-        if (report && (! unknown))
-            pout("  SG_IO ioctl failed, errno=%d [%s]\n", errno,
-                 strerror(errno));
+
+    void * io_hdr = NULL;
+
+    switch (sg_io_ver) {
+      case SG_IO_USE_V3:
+          io_hdr = &io_hdr_v3;
+          break;
+      case SG_IO_USE_V4:
+          io_hdr = &io_hdr_v4;
+          break;
+      default:
+          // should never be reached
+          errno = EOPNOTSUPP;
+          return -errno;
+    }
+
+    if (ioctl(dev_fd, SG_IO, io_hdr) < 0) {
+        if (report)
+            pout("  SG_IO ioctl failed, errno=%d [%s], SG_IO_V%d\n", errno,
+                 strerror(errno), sg_io_ver);
         return -errno;
     }
-    iop->resid = io_hdr.resid;
-    iop->scsi_status = io_hdr.status;
+
+    unsigned int sg_driver_status = 0,  sg_transport_status = 0, sg_info = 0,
+        sg_duration = 0;
+
+    if (sg_io_ver == SG_IO_USE_V3) {
+        iop->resid =            io_hdr_v3.resid;
+        iop->scsi_status =      io_hdr_v3.status;
+        sg_driver_status =      io_hdr_v3.driver_status;
+        sg_transport_status =   io_hdr_v3.host_status;
+        sg_info =               io_hdr_v3.info;
+        iop->resp_sense_len =   io_hdr_v3.sb_len_wr;
+        sg_duration =           io_hdr_v3.duration;
+    }
+
+    if (sg_io_ver == SG_IO_USE_V4) {
+       switch (iop->dxfer_dir) {
+           case DXFER_NONE:
+               iop->resid = 0;
+               break;
+           case DXFER_FROM_DEVICE:
+               iop->resid = io_hdr_v4.din_resid;
+               break;
+           case DXFER_TO_DEVICE:
+               iop->resid = io_hdr_v4.dout_resid;
+               break;
+       }
+       iop->scsi_status =       io_hdr_v4.device_status;
+       sg_driver_status =       io_hdr_v4.driver_status;
+       sg_transport_status =    io_hdr_v4.transport_status;
+       sg_info =                io_hdr_v4.info;
+       iop->resp_sense_len =    io_hdr_v4.response_len;
+       sg_duration =            io_hdr_v4.duration;
+    }
+
     if (report > 0) {
-        pout("  scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
-             "  info=0x%x  duration=%d milliseconds  resid=%d\n", io_hdr.status,
-             io_hdr.host_status, io_hdr.driver_status, io_hdr.info,
-             io_hdr.duration, io_hdr.resid);
+        pout("  scsi_status=0x%x, sg_transport_status=0x%x, sg_driver_status=0x%x\n"
+             "  sg_info=0x%x  sg_duration=%d milliseconds  resid=%d\n", iop->scsi_status,
+             sg_transport_status, sg_driver_status, sg_info,
+             sg_duration, iop->resid);
+
         if (report > 1) {
             if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
                 int trunc, len;
@@ -601,25 +684,24 @@ static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
                 if (len > 0) {
                     pout("  Incoming data, len=%d%s:\n", len,
                          (trunc ? " [only first 256 bytes shown]" : ""));
-                    dStrHex((const char*)iop->dxferp, (trunc ? 256 : len),
-                            1);
+                    dStrHex(iop->dxferp, (trunc ? 256 : len), 1);
                 } else
                     pout("  Incoming data trimmed to nothing by resid\n");
             }
         }
     }
 
-    if (io_hdr.info | SG_INFO_CHECK) { /* error or warning */
-        int masked_driver_status = (LSCSI_DRIVER_MASK & io_hdr.driver_status);
+    if (sg_info & SG_INFO_CHECK) { /* error or warning */
+        int masked_driver_status = (LSCSI_DRIVER_MASK & sg_driver_status);
 
-        if (0 != io_hdr.host_status) {
-            if ((LSCSI_DID_NO_CONNECT == io_hdr.host_status) ||
-                (LSCSI_DID_BUS_BUSY == io_hdr.host_status) ||
-                (LSCSI_DID_TIME_OUT == io_hdr.host_status))
+        if (0 != sg_transport_status) {
+            if ((LSCSI_DID_NO_CONNECT == sg_transport_status) ||
+                (LSCSI_DID_BUS_BUSY == sg_transport_status) ||
+                (LSCSI_DID_TIME_OUT == sg_transport_status))
                 return -ETIMEDOUT;
             else
                /* Check for DID_ERROR - workaround for aacraid driver quirk */
-               if (LSCSI_DID_ERROR != io_hdr.host_status) {
+               if (LSCSI_DID_ERROR != sg_transport_status) {
                        return -EIO; /* catch all if not DID_ERR */
                }
         }
@@ -631,17 +713,16 @@ static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
         }
         if (LSCSI_DRIVER_SENSE == masked_driver_status)
             iop->scsi_status = SCSI_STATUS_CHECK_CONDITION;
-        iop->resp_sense_len = io_hdr.sb_len_wr;
         if ((SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) &&
             iop->sensep && (iop->resp_sense_len > 0)) {
             if (report > 1) {
                 pout("  >>> Sense buffer, len=%d:\n",
                      (int)iop->resp_sense_len);
-                dStrHex((const char *)iop->sensep, iop->resp_sense_len , 1);
+                dStrHex(iop->sensep, iop->resp_sense_len , 1);
             }
         }
         if (report) {
-            if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) {
+            if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status && iop->sensep) {
                 if ((iop->sensep[0] & 0x7f) > 0x71)
                     pout("  status=%x: [desc] sense_key=%x asc=%x ascq=%x\n",
                          iop->scsi_status, iop->sensep[1] & 0xf,
@@ -663,7 +744,7 @@ struct linux_ioctl_send_command
 {
     int inbufsize;
     int outbufsize;
-    UINT8 buff[MAX_DXFER_LEN + 16];
+    uint8_t buff[MAX_DXFER_LEN + 16];
 };
 
 /* The Linux SCSI_IOCTL_SEND_COMMAND ioctl is primitive and it doesn't
@@ -689,18 +770,16 @@ static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
         j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
         for (k = 0; k < (int)iop->cmnd_len; ++k)
             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
-        if ((report > 1) &&
-            (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
+        if ((report > 1) && (DXFER_TO_DEVICE == iop->dxfer_dir)) {
             int trunc = (iop->dxfer_len > 256) ? 1 : 0;
 
-            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
-                          "data, len=%d%s:\n", (int)iop->dxfer_len,
-                          (trunc ? " [only first 256 bytes shown]" : ""));
-            dStrHex((const char *)iop->dxferp,
-                    (trunc ? 256 : iop->dxfer_len) , 1);
+            snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
+                     "data, len=%d%s:\n", (int)iop->dxfer_len,
+                     (trunc ? " [only first 256 bytes shown]" : ""));
+            dStrHex(iop->dxferp, (trunc ? 256 : iop->dxfer_len) , 1);
         }
         else
-            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
+            snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
         pout("%s", buff);
     }
     switch (iop->dxfer_dir) {
@@ -745,8 +824,7 @@ static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
 
                 pout("  Incoming data, len=%d%s:\n", (int)iop->dxfer_len,
                      (trunc ? " [only first 256 bytes shown]" : ""));
-                dStrHex((const char*)iop->dxferp,
-                        (trunc ? 256 : iop->dxfer_len) , 1);
+                dStrHex(iop->dxferp, (trunc ? 256 : iop->dxfer_len) , 1);
             }
         }
         return 0;
@@ -762,7 +840,7 @@ static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
         iop->resp_sense_len = len;
         if (report > 1) {
             pout("  >>> Sense buffer, len=%d:\n", (int)len);
-            dStrHex((const char *)wrk.buff, len , 1);
+            dStrHex(wrk.buff, len , 1);
         }
     }
     if (report) {
@@ -801,22 +879,33 @@ static int do_normal_scsi_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop,
      * other than ENODEV (no device) or permission then assume
      * SCSI_IOCTL_SEND_COMMAND is the only option. */
     switch (sg_io_state) {
-    case SG_IO_PRESENT_UNKNOWN:
+    case SG_IO_USE_DETECT:
         /* ignore report argument */
-        if (0 == (res = sg_io_cmnd_io(dev_fd, iop, report, 1))) {
-            sg_io_state = SG_IO_PRESENT_YES;
+        /* Try SG_IO V3 first */
+        if (0 == (res = sg_io_cmnd_io(dev_fd, iop, report, SG_IO_USE_V3))) {
+            sg_io_state = SG_IO_USE_V3;
+            return 0;
+        } else if ((-ENODEV == res) || (-EACCES == res) || (-EPERM == res))
+            return res;         /* wait until we see a device */
+        /* See if we can use SG_IO V4 * */
+        if (0 == (res = sg_io_cmnd_io(dev_fd, iop, report, SG_IO_USE_V4))) {
+            sg_io_state = SG_IO_USE_V4;
             return 0;
         } else if ((-ENODEV == res) || (-EACCES == res) || (-EPERM == res))
             return res;         /* wait until we see a device */
-        sg_io_state = SG_IO_PRESENT_NO;
-        /* drop through by design */
-    case SG_IO_PRESENT_NO:
+        /* fallback to the SCSI_IOCTL_SEND_COMMAND */
+        sg_io_state = SG_IO_UNSUPP;
+        /* FALLTHRU */
+    case SG_IO_UNSUPP:
+        /* deprecated SCSI_IOCTL_SEND_COMMAND ioctl */
         return sisc_cmnd_io(dev_fd, iop, report);
-    case SG_IO_PRESENT_YES:
-        return sg_io_cmnd_io(dev_fd, iop, report, 0);
+    case SG_IO_USE_V3:
+    case SG_IO_USE_V4:
+        /* use SG_IO V3 or V4 ioctl, depending on availabiliy */
+        return sg_io_cmnd_io(dev_fd, iop, report, sg_io_state);
     default:
         pout(">>>> do_scsi_cmnd_io: bad sg_io_state=%d\n", sg_io_state);
-        sg_io_state = SG_IO_PRESENT_UNKNOWN;
+        sg_io_state = SG_IO_USE_DETECT;
         return -EIO;    /* report error and reset state */
     }
 }
@@ -852,15 +941,250 @@ linux_scsi_device::linux_scsi_device(smart_interface * intf,
 {
 }
 
-
 bool linux_scsi_device::scsi_pass_through(scsi_cmnd_io * iop)
 {
-  int status = do_normal_scsi_cmnd_io(get_fd(), iop, con->reportscsiioctl);
+  int status = do_normal_scsi_cmnd_io(get_fd(), iop, scsi_debugmode);
   if (status < 0)
       return set_err(-status);
   return true;
 }
 
+/////////////////////////////////////////////////////////////////////////////
+/// PMC AacRAID support
+
+class linux_aacraid_device
+:public   scsi_device,
+ public /*extends */   linux_smart_device
+{
+public:
+  linux_aacraid_device(smart_interface *intf, const char *dev_name,
+    unsigned int host, unsigned int channel, unsigned int device);
+
+  virtual ~linux_aacraid_device() throw();
+
+  virtual bool open();
+
+  virtual bool scsi_pass_through(scsi_cmnd_io *iop);
+
+private:
+  //Device Host number
+  int aHost;
+
+  //Channel(Lun) of the device
+  int aLun;
+
+  //Id of the device
+  int aId;
+
+};
+
+linux_aacraid_device::linux_aacraid_device(smart_interface *intf,
+  const char *dev_name, unsigned int host, unsigned int channel, unsigned int device)
+   : smart_device(intf,dev_name,"aacraid","aacraid"),
+     linux_smart_device(O_RDWR|O_NONBLOCK),
+     aHost(host), aLun(channel), aId(device)
+{
+  set_info().info_name = strprintf("%s [aacraid_disk_%02d_%02d_%d]",dev_name,aHost,aLun,aId);
+  set_info().dev_type  = strprintf("aacraid,%d,%d,%d",aHost,aLun,aId);
+}
+
+linux_aacraid_device::~linux_aacraid_device() throw()
+{
+}
+
+bool linux_aacraid_device::open()
+{
+  //Create the character device name based on the host number
+  //Required for get stats from disks connected to different controllers
+  char dev_name[128];
+  snprintf(dev_name, sizeof(dev_name), "/dev/aac%d", aHost);
+
+  //Initial open of dev name to check if it exsists
+  int afd = ::open(dev_name,O_RDWR);
+
+  if(afd < 0 && errno == ENOENT) {
+
+    FILE *fp = fopen("/proc/devices","r");
+    if(NULL == fp)
+      return set_err(errno,"cannot open /proc/devices:%s",
+                     strerror(errno));
+
+    char line[256];
+    int mjr = -1;
+
+    while(fgets(line,sizeof(line),fp) !=NULL) {
+      int nc = -1;
+      if(sscanf(line,"%d aac%n",&mjr,&nc) == 1
+                && nc > 0 && '\n' == line[nc])
+        break;
+      mjr = -1;
+    }
+
+    //work with /proc/devices is done
+    fclose(fp);
+
+    if (mjr < 0)
+      return set_err(ENOENT, "aac entry not found in /proc/devices");
+
+    //Create misc device file in /dev/ used for communication with driver
+    if(mknod(dev_name,S_IFCHR,makedev(mjr,aHost)))
+      return set_err(errno,"cannot create %s:%s",dev_name,strerror(errno));
+
+    afd = ::open(dev_name,O_RDWR);
+  }
+
+  if(afd < 0)
+    return set_err(errno,"cannot open %s:%s",dev_name,strerror(errno));
+
+  set_fd(afd);
+  return true;
+}
+
+bool linux_aacraid_device::scsi_pass_through(scsi_cmnd_io *iop)
+{
+  int report = scsi_debugmode;
+
+  if (report > 0) {
+    int k, j;
+    const unsigned char * ucp = iop->cmnd;
+    const char * np;
+    char buff[256];
+    const int sz = (int)sizeof(buff);
+
+    np = scsi_get_opcode_name(ucp[0]);
+    j  = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
+    for (k = 0; k < (int)iop->cmnd_len; ++k)
+      j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
+    if ((report > 1) &&
+        (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
+        int trunc = (iop->dxfer_len > 256) ? 1 : 0;
+
+        snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
+                 "data, len=%d%s:\n", (int)iop->dxfer_len,
+                 (trunc ? " [only first 256 bytes shown]" : ""));
+        dStrHex(iop->dxferp, (trunc ? 256 : iop->dxfer_len) , 1);
+    }
+    else
+      snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
+
+    pout("%s", buff);
+  }
+
+
+  //return test commands
+  if (iop->cmnd[0] == 0x00)
+    return true;
+
+  user_aac_reply *pReply;
+
+  #ifdef ENVIRONMENT64
+    // Create user 64 bit request
+    user_aac_srb64  *pSrb;
+    uint8_t aBuff[sizeof(user_aac_srb64) + sizeof(user_aac_reply)] = {0,};
+
+    pSrb    = (user_aac_srb64*)aBuff;
+    pSrb->count = sizeof(user_aac_srb64) - sizeof(user_sgentry64);
+
+ #elif defined(ENVIRONMENT32)
+    //Create user 32 bit request
+    user_aac_srb32  *pSrb;
+    uint8_t aBuff[sizeof(user_aac_srb32) + sizeof(user_aac_reply)] = {0,};
+
+    pSrb    = (user_aac_srb32*)aBuff;
+    pSrb->count = sizeof(user_aac_srb32) - sizeof(user_sgentry32);
+ #endif
+
+  pSrb->function = SRB_FUNCTION_EXECUTE_SCSI;
+  //channel is 0 always
+  pSrb->channel  = 0;
+  pSrb->id       = aId;
+  pSrb->lun      = aLun;
+  pSrb->timeout  = 0;
+
+  pSrb->retry_limit = 0;
+  pSrb->cdb_size    = iop->cmnd_len;
+
+  switch(iop->dxfer_dir) {
+    case DXFER_NONE:
+      pSrb->flags = SRB_NoDataXfer;
+      break;
+    case DXFER_FROM_DEVICE:
+      pSrb->flags = SRB_DataIn;
+      break;
+    case DXFER_TO_DEVICE:
+      pSrb->flags = SRB_DataOut;
+      break;
+    default:
+      pout("aacraid: bad dxfer_dir\n");
+      return set_err(EINVAL, "aacraid: bad dxfer_dir\n");
+  }
+
+  if(iop->dxfer_len > 0) {
+
+    #ifdef ENVIRONMENT64
+      pSrb->sg64.count = 1;
+      pSrb->sg64.sg64[0].addr64.lo32 = ((intptr_t)iop->dxferp) &
+                                         0x00000000ffffffff;
+      pSrb->sg64.sg64[0].addr64.hi32 = ((intptr_t)iop->dxferp) >> 32;
+
+      pSrb->sg64.sg64[0].length = (uint32_t)iop->dxfer_len;
+      pSrb->count += pSrb->sg64.count * sizeof(user_sgentry64);
+    #elif defined(ENVIRONMENT32)
+      pSrb->sg32.count = 1;
+      pSrb->sg32.sg32[0].addr32 = (intptr_t)iop->dxferp;
+
+      pSrb->sg32.sg32[0].length = (uint32_t)iop->dxfer_len;
+      pSrb->count += pSrb->sg32.count * sizeof(user_sgentry32);
+    #endif
+
+  }
+
+  pReply  = (user_aac_reply*)(aBuff+pSrb->count);
+
+  memcpy(pSrb->cdb,iop->cmnd,iop->cmnd_len);
+
+  int rc = 0;
+  errno = 0;
+  rc = ioctl(get_fd(),FSACTL_SEND_RAW_SRB,pSrb);
+
+  if (rc != 0)
+    return set_err(errno, "aacraid send_raw_srb: %d.%d = %s",
+                  aLun, aId, strerror(errno));
+
+/* see kernel aacraid.h and MSDN SCSI_REQUEST_BLOCK documentation */
+#define SRB_STATUS_SUCCESS            0x1
+#define SRB_STATUS_ERROR              0x4
+#define SRB_STATUS_NO_DEVICE         0x08
+#define SRB_STATUS_SELECTION_TIMEOUT 0x0a
+#define SRB_STATUS_AUTOSENSE_VALID   0x80
+
+  iop->scsi_status = pReply->scsi_status;
+
+  if (pReply->srb_status == (SRB_STATUS_AUTOSENSE_VALID | SRB_STATUS_ERROR)
+      && iop->scsi_status == SCSI_STATUS_CHECK_CONDITION) {
+    memcpy(iop->sensep, pReply->sense_data, pReply->sense_data_size);
+    iop->resp_sense_len = pReply->sense_data_size;
+    return true; /* request completed with sense data */
+  }
+
+  switch (pReply->srb_status & 0x3f) {
+
+    case SRB_STATUS_SUCCESS:
+      return true; /* request completed successfully */
+
+    case SRB_STATUS_NO_DEVICE:
+      return set_err(EIO, "aacraid: Device %d %d does not exist", aLun, aId);
+
+    case SRB_STATUS_SELECTION_TIMEOUT:
+      return set_err(EIO, "aacraid: Device %d %d not responding", aLun, aId);
+
+    default:
+      return set_err(EIO, "aacraid result: %d.%d = 0x%x",
+                    aLun, aId, pReply->srb_status);
+  }
+}
+
+
 /////////////////////////////////////////////////////////////////////////////
 /// LSI MegaRAID support
 
@@ -870,7 +1194,7 @@ class linux_megaraid_device
 {
 public:
   linux_megaraid_device(smart_interface *intf, const char *name, 
-    unsigned int bus, unsigned int tgt);
+    unsigned int tgt);
 
   virtual ~linux_megaraid_device() throw();
 
@@ -878,31 +1202,31 @@ public:
 
   virtual bool open();
   virtual bool close();
+
   virtual bool scsi_pass_through(scsi_cmnd_io *iop);
 
 private:
   unsigned int m_disknum;
-  unsigned int m_busnum;
   unsigned int m_hba;
   int m_fd;
 
   bool (linux_megaraid_device::*pt_cmd)(int cdblen, void *cdb, int dataLen, void *data,
-    int senseLen, void *sense, int report);
+    int senseLen, void *sense, int report, int direction);
   bool megasas_cmd(int cdbLen, void *cdb, int dataLen, void *data,
-    int senseLen, void *sense, int report);
+    int senseLen, void *sense, int report, int direction);
   bool megadev_cmd(int cdbLen, void *cdb, int dataLen, void *data,
-    int senseLen, void *sense, int report);
+    int senseLen, void *sense, int report, int direction);
 };
 
 linux_megaraid_device::linux_megaraid_device(smart_interface *intf,
-  const char *dev_name, unsigned int bus, unsigned int tgt)
+  const char *dev_name, unsigned int tgt)
  : smart_device(intf, dev_name, "megaraid", "megaraid"),
    linux_smart_device(O_RDWR | O_NONBLOCK),
-   m_disknum(tgt), m_busnum(bus), m_hba(0),
+   m_disknum(tgt), m_hba(0),
    m_fd(-1), pt_cmd(0)
 {
   set_info().info_name = strprintf("%s [megaraid_disk_%02d]", dev_name, m_disknum);
+  set_info().dev_type = strprintf("megaraid,%d", tgt);
 }
 
 linux_megaraid_device::~linux_megaraid_device() throw()
@@ -913,7 +1237,7 @@ linux_megaraid_device::~linux_megaraid_device() throw()
 
 smart_device * linux_megaraid_device::autodetect_open()
 {
-  int report = con->reportscsiioctl; 
+  int report = scsi_debugmode;
 
   // Open device
   if (!open())
@@ -938,14 +1262,13 @@ smart_device * linux_megaraid_device::autodetect_open()
       return this;
 
   if (report)
-    printf("Got MegaRAID inquiry.. %s\n", req_buff+8);
+    pout("Got MegaRAID inquiry.. %s\n", req_buff+8);
 
   // Use INQUIRY to detect type
   {
-    // SAT or USB ?
+    // SAT?
     ata_device * newdev = smi()->autodetect_sat_device(this, req_buff, len);
-    if (newdev)
-      // NOTE: 'this' is now owned by '*newdev'
+    if (newdev) // NOTE: 'this' is now owned by '*newdev'
       return newdev;
   }
 
@@ -953,48 +1276,49 @@ smart_device * linux_megaraid_device::autodetect_open()
   return this;
 }
 
-
 bool linux_megaraid_device::open()
 {
   char line[128];
-  int   mjr, n1;
-  FILE *fp;
-  int report = con->reportscsiioctl; 
+  int   mjr;
+  int report = scsi_debugmode;
 
-  if (!linux_smart_device::open())
-    return false;
-
-  /* Get device HBA */
-  struct sg_scsi_id sgid;
-  if (ioctl(get_fd(), SG_GET_SCSI_ID, &sgid) == 0) {
-    m_hba = sgid.host_no;
-  }
-  else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER, &m_hba) != 0) {
-    int err = errno;
+  if (sscanf(get_dev_name(), "/dev/bus/%u", &m_hba) == 0) {
+    if (!linux_smart_device::open())
+      return false;
+    /* Get device HBA */
+    struct sg_scsi_id sgid;
+    if (ioctl(get_fd(), SG_GET_SCSI_ID, &sgid) == 0) {
+      m_hba = sgid.host_no;
+    }
+    else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER, &m_hba) != 0) {
+      int err = errno;
+      linux_smart_device::close();
+      return set_err(err, "can't get bus number");
+    } // we don't need this device anymore
     linux_smart_device::close();
-    return set_err(err, "can't get bus number");
   }
-
   /* Perform mknod of device ioctl node */
-  fp = fopen("/proc/devices", "r");
-  while (fgets(line, sizeof(line), fp) != NULL) {
-       n1=0;
-       if (sscanf(line, "%d megaraid_sas_ioctl%n", &mjr, &n1) == 1 && n1 == 22) {
-          n1=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR, makedev(mjr, 0));
-          if(report > 0)
-            printf("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1 >= 0 ? 0 : errno);
-          if (n1 >= 0 || errno == EEXIST)
-             break;
-       }
-       else if (sscanf(line, "%d megadev%n", &mjr, &n1) == 1 && n1 == 11) {
-          n1=mknod("/dev/megadev0", S_IFCHR, makedev(mjr, 0));
-          if(report > 0)
-            printf("Creating /dev/megadev0 = %d\n", n1 >= 0 ? 0 : errno);
-          if (n1 >= 0 || errno == EEXIST)
-             break;
-       }
+  FILE * fp = fopen("/proc/devices", "r");
+  if (fp) {
+    while (fgets(line, sizeof(line), fp) != NULL) {
+      int n1 = 0;
+      if (sscanf(line, "%d megaraid_sas_ioctl%n", &mjr, &n1) == 1 && n1 == 22) {
+        n1=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR, makedev(mjr, 0));
+        if(report > 0)
+          pout("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1 >= 0 ? 0 : errno);
+        if (n1 >= 0 || errno == EEXIST)
+          break;
+      }
+      else if (sscanf(line, "%d megadev%n", &mjr, &n1) == 1 && n1 == 11) {
+        n1=mknod("/dev/megadev0", S_IFCHR, makedev(mjr, 0));
+        if(report > 0)
+          pout("Creating /dev/megadev0 = %d\n", n1 >= 0 ? 0 : errno);
+        if (n1 >= 0 || errno == EEXIST)
+          break;
+      }
+    }
+    fclose(fp);
   }
-  fclose(fp);
 
   /* Open Device IOCTL node */
   if ((m_fd = ::open("/dev/megaraid_sas_ioctl_node", O_RDWR)) >= 0) {
@@ -1008,7 +1332,7 @@ bool linux_megaraid_device::open()
     linux_smart_device::close();
     return set_err(err, "cannot open /dev/megaraid_sas_ioctl_node or /dev/megadev0");
   }
-
+  set_fd(m_fd);
   return true;
 }
 
@@ -1017,12 +1341,13 @@ bool linux_megaraid_device::close()
   if (m_fd >= 0)
     ::close(m_fd);
   m_fd = -1; m_hba = 0; pt_cmd = 0;
-  return linux_smart_device::close();
+  set_fd(m_fd);
+  return true;
 }
 
 bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io *iop)
 {
-  int report = con->reportscsiioctl; 
+  int report = scsi_debugmode;
 
   if (report > 0) {
         int k, j;
@@ -1039,54 +1364,51 @@ bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io *iop)
             (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
             int trunc = (iop->dxfer_len > 256) ? 1 : 0;
 
-            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
-                          "data, len=%d%s:\n", (int)iop->dxfer_len,
-                          (trunc ? " [only first 256 bytes shown]" : ""));
-            dStrHex((const char *)iop->dxferp,
-                    (trunc ? 256 : iop->dxfer_len) , 1);
+            snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
+                     "data, len=%d%s:\n", (int)iop->dxfer_len,
+                     (trunc ? " [only first 256 bytes shown]" : ""));
+            dStrHex(iop->dxferp, (trunc ? 256 : iop->dxfer_len) , 1);
         }
         else
-            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
+            snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
         pout("%s", buff);
   }
 
-  /* Controller rejects Enable SMART and Test Unit Ready */
+  // Controller rejects Test Unit Ready
   if (iop->cmnd[0] == 0x00)
     return true;
-  if (iop->cmnd[0] == 0x85 && iop->cmnd[1] == 0x06) {
-    if(report > 0)
-      pout("Rejecting SMART/ATA command to controller\n");
-    // Emulate SMART STATUS CHECK drive reply
-    // smartctl fail to work without this
-    if(iop->cmnd[2]==0x2c) {
-      iop->resp_sense_len=22; // copied from real response
-      iop->sensep[0]=0x72; // descriptor format
-      iop->sensep[7]=0x0e; // additional length
-      iop->sensep[8]=0x09; // description pointer
-      iop->sensep[17]=0x4f; // low cylinder GOOD smart status
-      iop->sensep[19]=0xc2; // high cylinder GOOD smart status
-    }
-    return true;
-  }
 
+  if (iop->cmnd[0] == SAT_ATA_PASSTHROUGH_12 || iop->cmnd[0] == SAT_ATA_PASSTHROUGH_16) { 
+    // Controller does not return ATA output registers in SAT sense data
+    if (iop->cmnd[2] & (1 << 5)) // chk_cond
+      return set_err(ENOSYS, "ATA return descriptor not supported by controller firmware");
+  }
+  // SMART WRITE LOG SECTOR causing media errors
+  if ((iop->cmnd[0] == SAT_ATA_PASSTHROUGH_16 // SAT16 WRITE LOG
+      && iop->cmnd[14] == ATA_SMART_CMD && iop->cmnd[3]==0 && iop->cmnd[4] == ATA_SMART_WRITE_LOG_SECTOR) ||
+      (iop->cmnd[0] == SAT_ATA_PASSTHROUGH_12 // SAT12 WRITE LOG
+       && iop->cmnd[9] == ATA_SMART_CMD && iop->cmnd[3] == ATA_SMART_WRITE_LOG_SECTOR)) 
+  {
+    if(!failuretest_permissive)
+       return set_err(ENOSYS, "SMART WRITE LOG SECTOR may cause problems, try with -T permissive to force"); 
+  }
   if (pt_cmd == NULL)
     return false;
-  return (this->*pt_cmd)(iop->cmnd_len, iop->cmnd, 
+  return (this->*pt_cmd)(iop->cmnd_len, iop->cmnd,
     iop->dxfer_len, iop->dxferp,
-    iop->max_sense_len, iop->sensep, report);
+    iop->max_sense_len, iop->sensep, report, iop->dxfer_dir);
 }
 
 /* Issue passthrough scsi command to PERC5/6 controllers */
 bool linux_megaraid_device::megasas_cmd(int cdbLen, void *cdb, 
   int dataLen, void *data,
-  int /*senseLen*/, void * /*sense*/, int /*report*/)
+  int /*senseLen*/, void * /*sense*/, int /*report*/, int dxfer_dir)
 {
   struct megasas_pthru_frame   *pthru;
   struct megasas_iocpacket     uio;
-  int rc;
 
   memset(&uio, 0, sizeof(uio));
-  pthru = (struct megasas_pthru_frame *)uio.frame.raw;
+  pthru = &uio.frame.pthru;
   pthru->cmd = MFI_CMD_PD_SCSI_IO;
   pthru->cmd_status = 0xFF;
   pthru->scsi_status = 0x0;
@@ -1094,22 +1416,39 @@ bool linux_megaraid_device::megasas_cmd(int cdbLen, void *cdb,
   pthru->lun = 0;
   pthru->cdb_len = cdbLen;
   pthru->timeout = 0;
-  pthru->flags = MFI_FRAME_DIR_READ;
-  pthru->sge_count = 1;
-  pthru->data_xfer_len = dataLen;
-  pthru->sgl.sge32[0].phys_addr = (intptr_t)data;
-  pthru->sgl.sge32[0].length = (uint32_t)dataLen;
+  switch (dxfer_dir) {
+    case DXFER_NONE:
+      pthru->flags = MFI_FRAME_DIR_NONE;
+      break;
+    case DXFER_FROM_DEVICE:
+      pthru->flags = MFI_FRAME_DIR_READ;
+      break;
+    case DXFER_TO_DEVICE:
+      pthru->flags = MFI_FRAME_DIR_WRITE;
+      break;
+    default:
+      pout("megasas_cmd: bad dxfer_dir\n");
+      return set_err(EINVAL, "megasas_cmd: bad dxfer_dir\n");
+  }
+
+  if (dataLen > 0) {
+    pthru->sge_count = 1;
+    pthru->data_xfer_len = dataLen;
+    pthru->sgl.sge32[0].phys_addr = (intptr_t)data;
+    pthru->sgl.sge32[0].length = (uint32_t)dataLen;
+  }
   memcpy(pthru->cdb, cdb, cdbLen);
 
   uio.host_no = m_hba;
-  uio.sge_count = 1;
-  uio.sgl_off = offsetof(struct megasas_pthru_frame, sgl);
-  uio.sgl[0].iov_base = data;
-  uio.sgl[0].iov_len = dataLen;
+  if (dataLen > 0) {
+    uio.sge_count = 1;
+    uio.sgl_off = offsetof(struct megasas_pthru_frame, sgl);
+    uio.sgl[0].iov_base = data;
+    uio.sgl[0].iov_len = dataLen;
+  }
 
-  rc = 0;
   errno = 0;
-  rc = ioctl(m_fd, MEGASAS_IOC_FIRMWARE, &uio);
+  int rc = ioctl(m_fd, MEGASAS_IOC_FIRMWARE, &uio);
   if (pthru->cmd_status || rc != 0) {
     if (pthru->cmd_status == 12) {
       return set_err(EIO, "megasas_cmd: Device %d does not exist\n", m_disknum);
@@ -1124,14 +1463,11 @@ bool linux_megaraid_device::megasas_cmd(int cdbLen, void *cdb,
 /* Issue passthrough scsi commands to PERC2/3/4 controllers */
 bool linux_megaraid_device::megadev_cmd(int cdbLen, void *cdb, 
   int dataLen, void *data,
-  int senseLen, void *sense, int /*report*/)
+  int /*senseLen*/, void * /*sense*/, int /*report*/, int /* dir */)
 {
   struct uioctl_t uio;
   int rc;
 
-  sense = NULL;
-  senseLen = 0;
-
   /* Don't issue to the controller */
   if (m_disknum == 7)
     return false;
@@ -1197,7 +1533,7 @@ linux_cciss_device::linux_cciss_device(smart_interface * intf,
 
 bool linux_cciss_device::scsi_pass_through(scsi_cmnd_io * iop)
 {
-  int status = cciss_io_interface(get_fd(), m_disknum, iop, con->reportscsiioctl);
+  int status = cciss_io_interface(get_fd(), m_disknum, iop, scsi_debugmode);
   if (status < 0)
       return set_err(-status);
   return true;
@@ -1216,7 +1552,8 @@ public:
   enum escalade_type_t {
     AMCC_3WARE_678K,
     AMCC_3WARE_678K_CHAR,
-    AMCC_3WARE_9000_CHAR
+    AMCC_3WARE_9000_CHAR,
+    AMCC_3WARE_9700_CHAR
   };
 
   linux_escalade_device(smart_interface * intf, const char * dev_name,
@@ -1244,7 +1581,8 @@ linux_escalade_device::linux_escalade_device(smart_interface * intf, const char
 #define MAJOR_STRING_LENGTH 3
 #define DEVICE_STRING_LENGTH 32
 #define NODE_STRING_LENGTH 16
-int setup_3ware_nodes(const char *nodename, const char *driver_name) {
+static int setup_3ware_nodes(const char *nodename, const char *driver_name)
+{
   int              tw_major      = 0;
   int              index         = 0;
   char             majorstring[MAJOR_STRING_LENGTH+1];
@@ -1253,14 +1591,13 @@ int setup_3ware_nodes(const char *nodename, const char *driver_name) {
   struct stat      stat_buf;
   FILE             *file;
   int              retval = 0;
-#ifdef WITH_SELINUX
+#ifdef HAVE_LIBSELINUX
   security_context_t orig_context = NULL;
   security_context_t node_context = NULL;
   int                selinux_enabled  = is_selinux_enabled();
   int                selinux_enforced = security_getenforce();
 #endif
 
-
   /* First try to open up /proc/devices */
   if (!(file = fopen("/proc/devices", "r"))) {
     pout("Error opening /proc/devices to check/create 3ware device nodes\n");
@@ -1284,7 +1621,7 @@ int setup_3ware_nodes(const char *nodename, const char *driver_name) {
     pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename, driver_name);
     return 2;
   }
-#ifdef WITH_SELINUX
+#ifdef HAVE_LIBSELINUX
   /* Prepare a database of contexts for files in /dev
    * and save the current context */
   if (selinux_enabled) {
@@ -1292,16 +1629,17 @@ int setup_3ware_nodes(const char *nodename, const char *driver_name) {
       pout("Error initializing contexts database for /dev");
     if (getfscreatecon(&orig_context) < 0) {
       pout("Error retrieving original SELinux fscreate context");
-      if (selinux_enforced)
+      if (selinux_enforced) {
         matchpathcon_fini();
         return 6;
       }
+    }
   }
 #endif
   /* Now check if nodes are correct */
   for (index=0; index<16; index++) {
-    sprintf(nodestring, "/dev/%s%d", nodename, index);
-#ifdef WITH_SELINUX
+    snprintf(nodestring, sizeof(nodestring), "/dev/%s%d", nodename, index);
+#ifdef HAVE_LIBSELINUX
     /* Get context of the node and set it as the default */
     if (selinux_enabled) {
       if (matchpathcon(nodestring, S_IRUSR | S_IWUSR, &node_context) < 0) {
@@ -1330,7 +1668,7 @@ int setup_3ware_nodes(const char *nodename, const char *driver_name) {
         retval = 3;
         break;
       } else {
-#ifdef WITH_SELINUX
+#ifdef HAVE_LIBSELINUX
        if (selinux_enabled && node_context) {
          freecon(node_context);
          node_context = NULL;
@@ -1362,7 +1700,7 @@ int setup_3ware_nodes(const char *nodename, const char *driver_name) {
         break;
       }
     }
-#ifdef WITH_SELINUX
+#ifdef HAVE_LIBSELINUX
     if (selinux_enabled && node_context) {
       freecon(node_context);
       node_context = NULL;
@@ -1370,7 +1708,7 @@ int setup_3ware_nodes(const char *nodename, const char *driver_name) {
 #endif
   }
 
-#ifdef WITH_SELINUX
+#ifdef HAVE_LIBSELINUX
   if (selinux_enabled) {
     if(setfscreatecon(orig_context) < 0) {
       pout("Error re-setting original fscreate context");
@@ -1389,12 +1727,17 @@ int setup_3ware_nodes(const char *nodename, const char *driver_name) {
 
 bool linux_escalade_device::open()
 {
-  if (m_escalade_type == AMCC_3WARE_9000_CHAR || m_escalade_type == AMCC_3WARE_678K_CHAR) {
+  if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR ||
+      m_escalade_type == AMCC_3WARE_678K_CHAR) {
     // the device nodes for these controllers are dynamically assigned,
     // so we need to check that they exist with the correct major
     // numbers and if not, create them
-    const char * node   = (m_escalade_type == AMCC_3WARE_9000_CHAR ? "twa"    : "twe"    );
-    const char * driver = (m_escalade_type == AMCC_3WARE_9000_CHAR ? "3w-9xxx": "3w-xxxx");
+    const char * node   = (m_escalade_type == AMCC_3WARE_9700_CHAR ? "twl"     :
+                           m_escalade_type == AMCC_3WARE_9000_CHAR ? "twa"     :
+                                                                     "twe"      );
+    const char * driver = (m_escalade_type == AMCC_3WARE_9700_CHAR ? "3w-sas"  :
+                           m_escalade_type == AMCC_3WARE_9000_CHAR ? "3w-9xxx" :
+                                                                     "3w-xxxx"  );
     if (setup_3ware_nodes(node, driver))
       return set_err((errno ? errno : ENXIO), "setup_3ware_nodes(\"%s\", \"%s\") failed", node, driver);
   }
@@ -1428,7 +1771,6 @@ bool linux_escalade_device::open()
 //   0 if the command succeeded and disk SMART status is "OK"
 //   1 if the command succeeded and disk SMART status is "FAILING"
 
-
 /* 512 is the max payload size: increase if needed */
 #define BUFFER_LEN_678K      ( sizeof(TW_Ioctl)                  ) // 1044 unpacked, 1041 packed
 #define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1        ) // 1539 unpacked, 1536 packed
@@ -1461,7 +1803,7 @@ bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out
   memset(ioctl_buffer, 0, TW_IOCTL_BUFFER_SIZE);
 
   // TODO: Handle controller differences by different classes
-  if (m_escalade_type==AMCC_3WARE_9000_CHAR) {
+  if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR) {
     tw_ioctl_apache                               = (TW_Ioctl_Buf_Apache *)ioctl_buffer;
     tw_ioctl_apache->driver_command.control_code  = TW_IOCTL_FIRMWARE_PASS_THROUGH;
     tw_ioctl_apache->driver_command.buffer_length = 512; /* payload size */
@@ -1523,7 +1865,8 @@ bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out
     // in dwords by 1 to account for the 64-bit single sgl 'address'
     // field. Note that this doesn't agree with the typedefs but it's
     // right (agree with kernel driver behavior/typedefs).
-    if (m_escalade_type==AMCC_3WARE_9000_CHAR && sizeof(long)==8)
+    if ((m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
+        && sizeof(long) == 8)
       passthru->size++;
   }
   else if (in.direction == ata_cmd_in::no_data) {
@@ -1535,7 +1878,7 @@ bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out
     passthru->sector_count = 0x0;
   }
   else if (in.direction == ata_cmd_in::data_out) {
-    if (m_escalade_type == AMCC_3WARE_9000_CHAR)
+    if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
       memcpy(tw_ioctl_apache->data_buffer, in.buffer, in.size);
     else if (m_escalade_type == AMCC_3WARE_678K_CHAR)
       memcpy(tw_ioctl_char->data_buffer,   in.buffer, in.size);
@@ -1548,7 +1891,8 @@ bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out
     passthru->byte0.sgloff = 0x5;
     passthru->size         = 0x7;  // TODO: Other value for multi-sector ?
     passthru->param        = 0xF;  // PIO data write
-    if (m_escalade_type==AMCC_3WARE_9000_CHAR && sizeof(long)==8)
+    if ((m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
+        && sizeof(long) == 8)
       passthru->size++;
   }
   else
@@ -1556,7 +1900,7 @@ bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out
 
   // Now send the command down through an ioctl()
   int ioctlreturn;
-  if (m_escalade_type==AMCC_3WARE_9000_CHAR)
+  if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
     ioctlreturn=ioctl(get_fd(), TW_IOCTL_FIRMWARE_PASS_THROUGH, tw_ioctl_apache);
   else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
     ioctlreturn=ioctl(get_fd(), TW_CMD_PACKET_WITH_DATA, tw_ioctl_char);
@@ -1607,7 +1951,7 @@ bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out
 
   // If this is a read data command, copy data to output buffer
   if (readdata) {
-    if (m_escalade_type==AMCC_3WARE_9000_CHAR)
+    if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
       memcpy(in.buffer, tw_ioctl_apache->data_buffer, in.size);
     else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
       memcpy(in.buffer, tw_ioctl_char->data_buffer, in.size);
@@ -1636,84 +1980,40 @@ bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out
   return true;
 }
 
-
 /////////////////////////////////////////////////////////////////////////////
 /// Areca RAID support
 
-class linux_areca_device
-: public /*implements*/ ata_device_with_command_set,
+///////////////////////////////////////////////////////////////////
+// SATA(ATA) device behind Areca RAID Controller
+class linux_areca_ata_device
+: public /*implements*/ areca_ata_device,
   public /*extends*/ linux_smart_device
 {
 public:
-  linux_areca_device(smart_interface * intf, const char * dev_name, int disknum);
-
-protected:
-  virtual int ata_command_interface(smart_command_set command, int select, char * data);
-
-private:
-  int m_disknum; ///< Disk number.
+  linux_areca_ata_device(smart_interface * intf, const char * dev_name, int disknum, int encnum = 1);
+  virtual smart_device * autodetect_open();
+  virtual bool arcmsr_lock();
+  virtual bool arcmsr_unlock();
+  virtual int arcmsr_do_scsi_io(struct scsi_cmnd_io * iop);
 };
 
-
-// PURPOSE
-//   This is an interface routine meant to isolate the OS dependent
-//   parts of the code, and to provide a debugging interface.  Each
-//   different port and OS needs to provide it's own interface.  This
-//   is the linux interface to the Areca "arcmsr" driver.  It allows ATA
-//   commands to be passed through the SCSI driver.
-// DETAILED DESCRIPTION OF ARGUMENTS
-//   fd: is the file descriptor provided by open()
-//   disknum is the disk number (0 to 15) in the RAID array
-//   command: defines the different operations.
-//   select: additional input data if needed (which log, which type of
-//           self-test).
-//   data:   location to write output data, if needed (512 bytes).
-//   Note: not all commands use all arguments.
-// RETURN VALUES
-//  -1 if the command failed
-//   0 if the command succeeded,
-//   STATUS_CHECK routine: 
-//  -1 if the command failed
-//   0 if the command succeeded and disk SMART status is "OK"
-//   1 if the command succeeded and disk SMART status is "FAILING"
-
-
-/*DeviceType*/
-#define ARECA_SATA_RAID                        0x90000000
-/*FunctionCode*/
-#define FUNCTION_READ_RQBUFFER                 0x0801
-#define FUNCTION_WRITE_WQBUFFER                0x0802
-#define FUNCTION_CLEAR_RQBUFFER                0x0803
-#define FUNCTION_CLEAR_WQBUFFER                0x0804
-
-/* ARECA IO CONTROL CODE*/
-#define ARCMSR_IOCTL_READ_RQBUFFER             (ARECA_SATA_RAID | FUNCTION_READ_RQBUFFER)
-#define ARCMSR_IOCTL_WRITE_WQBUFFER            (ARECA_SATA_RAID | FUNCTION_WRITE_WQBUFFER)
-#define ARCMSR_IOCTL_CLEAR_RQBUFFER            (ARECA_SATA_RAID | FUNCTION_CLEAR_RQBUFFER)
-#define ARCMSR_IOCTL_CLEAR_WQBUFFER            (ARECA_SATA_RAID | FUNCTION_CLEAR_WQBUFFER)
-#define ARECA_SIG_STR                                                  "ARCMSR"
-
-// The SRB_IO_CONTROL & SRB_BUFFER structures are used to communicate(to/from) to areca driver
-typedef struct _SRB_IO_CONTROL
-{
-       unsigned int HeaderLength;
-       unsigned char Signature[8];
-       unsigned int Timeout;
-       unsigned int ControlCode;
-       unsigned int ReturnCode;
-       unsigned int Length;
-} sSRB_IO_CONTROL;
-
-typedef struct _SRB_BUFFER
+///////////////////////////////////////////////////////////////////
+// SAS(SCSI) device behind Areca RAID Controller
+class linux_areca_scsi_device
+: public /*implements*/ areca_scsi_device,
+  public /*extends*/ linux_smart_device
 {
-       sSRB_IO_CONTROL srbioctl;
-       unsigned char   ioctldatabuffer[1032]; // the buffer to put the command data to/from firmware
-} sSRB_BUFFER;
+public:
+  linux_areca_scsi_device(smart_interface * intf, const char * dev_name, int disknum, int encnum = 1);
+  virtual smart_device * autodetect_open();
+  virtual bool arcmsr_lock();
+  virtual bool arcmsr_unlock();
+  virtual int arcmsr_do_scsi_io(struct scsi_cmnd_io * iop);
+};
 
 // Looks in /proc/scsi to suggest correct areca devices
-// If hint not NULL, return device path guess
-int find_areca_in_proc(char *hint) {
+static int find_areca_in_proc()
+{
     const char* proc_format_string="host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n";
 
     // check data formwat
@@ -1751,9 +2051,6 @@ int find_areca_in_proc(char *hint) {
         dev++;
        if (id == 16 && type == 3) {
           // devices with id=16 and type=3 might be Areca controllers
-          if (!found && hint) {
-              sprintf(hint, "/dev/sg%d", dev);
-          }
           pout("Device /dev/sg%d appears to be an Areca controller.\n", dev);
            found++;
         }
@@ -1762,473 +2059,115 @@ int find_areca_in_proc(char *hint) {
     return 0;
 }
 
+// Areca RAID Controller(SATA Disk)
+linux_areca_ata_device::linux_areca_ata_device(smart_interface * intf, const char * dev_name, int disknum, int encnum)
+: smart_device(intf, dev_name, "areca", "areca"),
+  linux_smart_device(O_RDWR | O_EXCL | O_NONBLOCK)
+{
+  set_disknum(disknum);
+  set_encnum(encnum);
+  set_info().info_name = strprintf("%s [areca_disk#%02d_enc#%02d]", dev_name, disknum, encnum);
+}
 
+smart_device * linux_areca_ata_device::autodetect_open()
+{
+  // autodetect device type
+  int is_ata = arcmsr_get_dev_type();
+  if(is_ata < 0)
+  {
+    set_err(EIO);
+    return this;
+  }
 
-void dumpdata( unsigned char *block, int len)
-{
-       int ln = (len / 16) + 1;         // total line#
-       unsigned char c;
-       int pos = 0;
-
-       printf(" Address = %p, Length = (0x%x)%d\n", block, len, len);
-       printf("      0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F      ASCII      \n");
-       printf("=====================================================================\n");
-
-       for ( int l = 0; l < ln && len; l++ )
-       {
-               // printf the line# and the HEX data
-               // if a line data length < 16 then append the space to the tail of line to reach 16 chars
-               printf("%02X | ", l);
-               for ( pos = 0; pos < 16 && len; pos++, len-- )
-               {
-                       c = block[l*16+pos];    
-                       printf("%02X ", c);
-               }
-
-               if ( pos < 16 )
-               {
-                       for ( int loop = pos; loop < 16; loop++ )
-                       {
-                               printf("   ");
-                       }
-               }
-
-               // print ASCII char
-               for ( int loop = 0; loop < pos; loop++ )
-               {
-                       c = block[l*16+loop];
-                       if ( c >= 0x20 && c <= 0x7F )
-                       {
-                               printf("%c", c);
-                       }
-                       else
-                       {
-                               printf(".");
-                       }
-               }
-               printf("\n");
-       }   
-       printf("=====================================================================\n");
-}
-
-
-
-int arcmsr_command_handler(int fd, unsigned long arcmsr_cmd, unsigned char *data, int data_len, void *ext_data /* reserved for further use */)
-{
-       ARGUSED(ext_data);
-
-       int ioctlreturn = 0;
-       sSRB_BUFFER sBuf;
-       struct scsi_cmnd_io io_hdr;  
-       int dir = DXFER_TO_DEVICE;
-
-       UINT8 cdb[10];
-       UINT8 sense[32];
-
-       unsigned char *areca_return_packet;
-       int total = 0;
-       int expected = -1;
-       unsigned char return_buff[2048];
-       unsigned char *ptr = &return_buff[0];
-       memset(return_buff, 0, sizeof(return_buff));
-
-       memset((unsigned char *)&sBuf, 0, sizeof(sBuf));
-       memset(&io_hdr, 0, sizeof(io_hdr));
-       memset(cdb, 0, sizeof(cdb));
-       memset(sense, 0, sizeof(sense));
-
-
-       sBuf.srbioctl.HeaderLength = sizeof(sSRB_IO_CONTROL);   
-       memcpy(sBuf.srbioctl.Signature, ARECA_SIG_STR, strlen(ARECA_SIG_STR));
-       sBuf.srbioctl.Timeout = 10000;      
-       sBuf.srbioctl.ControlCode = ARCMSR_IOCTL_READ_RQBUFFER;
-
-       switch ( arcmsr_cmd )
-       {
-       // command for writing data to driver
-       case ARCMSR_IOCTL_WRITE_WQBUFFER:   
-               if ( data && data_len )
-               {
-                       sBuf.srbioctl.Length = data_len;    
-                       memcpy((unsigned char *)sBuf.ioctldatabuffer, (unsigned char *)data, data_len);
-               }
-               // commands for clearing related buffer of driver
-       case ARCMSR_IOCTL_CLEAR_RQBUFFER:
-       case ARCMSR_IOCTL_CLEAR_WQBUFFER:
-               cdb[0] = 0x3B; //SCSI_WRITE_BUF command;
-               break;
-               // command for reading data from driver
-       case ARCMSR_IOCTL_READ_RQBUFFER:    
-               cdb[0] = 0x3C; //SCSI_READ_BUF command;
-               dir = DXFER_FROM_DEVICE;
-               break;
-       default:
-               // unknown arcmsr commands
-               return -1;
-       }
+  if(is_ata == 1)
+  {
+    // SATA device
+    return this;
+  }
 
-       cdb[1] = 0x01;
-       cdb[2] = 0xf0;    
-       //
-       // cdb[5][6][7][8] areca defined command code( to/from driver )
-       //    
-       cdb[5] = (char)( arcmsr_cmd >> 24);
-       cdb[6] = (char)( arcmsr_cmd >> 16);
-       cdb[7] = (char)( arcmsr_cmd >> 8);
-       cdb[8] = (char)( arcmsr_cmd & 0x0F );
-
-       io_hdr.dxfer_dir = dir;
-       io_hdr.dxfer_len = sizeof(sBuf);
-       io_hdr.dxferp = (unsigned char *)&sBuf;  
-       io_hdr.cmnd = cdb;
-       io_hdr.cmnd_len = sizeof(cdb);
-       io_hdr.sensep = sense;  
-       io_hdr.max_sense_len = sizeof(sense);
-       io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
-
-       while ( 1 )
-       {
-               ioctlreturn = do_normal_scsi_cmnd_io(fd, &io_hdr, 0);
-               if ( ioctlreturn || io_hdr.scsi_status )
-               {
-                       // errors found
-                       break;
-               }
-
-               if ( arcmsr_cmd != ARCMSR_IOCTL_READ_RQBUFFER )
-               {
-                       // if succeeded, just returns the length of outgoing data
-                       return data_len;
-               }
-
-               if ( sBuf.srbioctl.Length )
-               {
-                       //dumpdata(&sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
-                       memcpy(ptr, &sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
-                       ptr += sBuf.srbioctl.Length;
-                       total += sBuf.srbioctl.Length;
-                       // the returned bytes enough to compute payload length ?
-                       if ( expected < 0 && total >= 5 )
-                       {
-                               areca_return_packet = (unsigned char *)&return_buff[0];
-                               if ( areca_return_packet[0] == 0x5E && 
-                                        areca_return_packet[1] == 0x01 && 
-                                        areca_return_packet[2] == 0x61 )
-                               {
-                                       // valid header, let's compute the returned payload length,
-                                       // we expected the total length is 
-                                       // payload + 3 bytes header + 2 bytes length + 1 byte checksum
-                                       expected = areca_return_packet[4] * 256 + areca_return_packet[3] + 6;
-                               }
-                       }
-
-                       if ( total >= 7 && total >= expected )
-                       {
-                               //printf("total bytes received = %d, expected length = %d\n", total, expected);
-
-                               // ------ Okay! we received enough --------
-                               break;
-                       }
-               }
-       }
+  // SAS device
+  smart_device_auto_ptr newdev(new linux_areca_scsi_device(smi(), get_dev_name(), get_disknum(), get_encnum()));
+  close();
+  delete this;
+  newdev->open();      // TODO: Can possibly pass open fd
 
-       // Deal with the different error cases
-       if ( ioctlreturn )
-       {
-               printf("do_scsi_cmnd_io with write buffer failed code = %x\n", ioctlreturn);
-               return -2;
-       }
+  return newdev.release();
+}
 
+int linux_areca_ata_device::arcmsr_do_scsi_io(struct scsi_cmnd_io * iop)
+{
+  int ioctlreturn = 0;
 
-       if ( io_hdr.scsi_status )
-       {
-               printf("io_hdr.scsi_status with write buffer failed code = %x\n", io_hdr.scsi_status);
-               return -3;
-       }
+  if(!is_open()) {
+      if(!open()){
+          find_areca_in_proc();
+      }
+  }
 
+  ioctlreturn = do_normal_scsi_cmnd_io(get_fd(), iop, scsi_debugmode);
+  if ( ioctlreturn || iop->scsi_status )
+  {
+    // errors found
+    return -1;
+  }
 
-       if ( data )
-       {
-               memcpy(data, return_buff, total);
-       }
+  return ioctlreturn;
+}
 
-       return total;
+bool linux_areca_ata_device::arcmsr_lock()
+{
+  return true;
 }
 
+bool linux_areca_ata_device::arcmsr_unlock()
+{
+  return true;
+}
 
-linux_areca_device::linux_areca_device(smart_interface * intf, const char * dev_name, int disknum)
+// Areca RAID Controller(SAS Device)
+linux_areca_scsi_device::linux_areca_scsi_device(smart_interface * intf, const char * dev_name, int disknum, int encnum)
 : smart_device(intf, dev_name, "areca", "areca"),
-  linux_smart_device(O_RDWR | O_EXCL | O_NONBLOCK),
-  m_disknum(disknum)
+  linux_smart_device(O_RDWR | O_EXCL | O_NONBLOCK)
 {
-  set_info().info_name = strprintf("%s [areca_%02d]", dev_name, disknum);
-}
-
-// Areca RAID Controller
-int linux_areca_device::ata_command_interface(smart_command_set command, int select, char * data)
-{
-       // ATA input registers
-       typedef struct _ATA_INPUT_REGISTERS
-       {
-               unsigned char features;
-               unsigned char sector_count;
-               unsigned char sector_number;
-               unsigned char cylinder_low; 
-               unsigned char cylinder_high;    
-               unsigned char device_head;  
-               unsigned char command;      
-               unsigned char reserved[8];
-               unsigned char data[512]; // [in/out] buffer for outgoing/incoming data
-       } sATA_INPUT_REGISTERS;
-
-       // ATA output registers
-       // Note: The output registers is re-sorted for areca internal use only
-       typedef struct _ATA_OUTPUT_REGISTERS
-       {
-               unsigned char error;
-               unsigned char status;
-               unsigned char sector_count;
-               unsigned char sector_number;
-               unsigned char cylinder_low; 
-               unsigned char cylinder_high;
-       }sATA_OUTPUT_REGISTERS;
-
-       // Areca packet format for outgoing:
-       // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
-       // B[3~4] : 2 bytes command length + variant data length, little endian
-       // B[5]   : 1 bytes areca defined command code, ATA passthrough command code is 0x1c
-       // B[6~last-1] : variant bytes payload data
-       // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
-       // 
-       // 
-       //   header 3 bytes  length 2 bytes   cmd 1 byte    payload data x bytes  cs 1 byte 
-       // +--------------------------------------------------------------------------------+
-       // + 0x5E 0x01 0x61 |   0x00 0x00   |     0x1c   | .................... |   0x00    |
-       // +--------------------------------------------------------------------------------+
-       // 
-
-       //Areca packet format for incoming:
-       // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
-       // B[3~4] : 2 bytes payload length, little endian
-       // B[5~last-1] : variant bytes returned payload data
-       // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
-       // 
-       // 
-       //   header 3 bytes  length 2 bytes   payload data x bytes  cs 1 byte 
-       // +-------------------------------------------------------------------+
-       // + 0x5E 0x01 0x61 |   0x00 0x00   | .................... |   0x00    |
-       // +-------------------------------------------------------------------+
-       unsigned char    areca_packet[640];
-       int areca_packet_len = sizeof(areca_packet);
-       unsigned char cs = 0;   
-
-       sATA_INPUT_REGISTERS *ata_cmd;
-
-       // For debugging
-#if 0
-       memset(sInq, 0, sizeof(sInq));
-       scsiStdInquiry(fd, (unsigned char *)sInq, (int)sizeof(sInq));
-       dumpdata((unsigned char *)sInq, sizeof(sInq));
-#endif
-       memset(areca_packet, 0, areca_packet_len);
-
-       // ----- BEGIN TO SETUP HEADERS -------
-       areca_packet[0] = 0x5E;
-       areca_packet[1] = 0x01;
-       areca_packet[2] = 0x61;
-       areca_packet[3] = (unsigned char)((areca_packet_len - 6) & 0xff);
-       areca_packet[4] = (unsigned char)(((areca_packet_len - 6) >> 8) & 0xff);
-       areca_packet[5] = 0x1c; // areca defined code for ATA passthrough command
-
-
-       // ----- BEGIN TO SETUP PAYLOAD DATA -----
-
-       memcpy(&areca_packet[7], "SmrT", 4);    // areca defined password
-
-       ata_cmd = (sATA_INPUT_REGISTERS *)&areca_packet[12];
-       ata_cmd->cylinder_low    = 0x4F;
-       ata_cmd->cylinder_high   = 0xC2;
-
-
-       if ( command == READ_VALUES     ||
-                command == READ_THRESHOLDS ||
-                command == READ_LOG ||
-                command == IDENTIFY ||
-                command == PIDENTIFY )
-       {
-               // the commands will return data
-               areca_packet[6] = 0x13;
-               ata_cmd->sector_count = 0x1;
-       }
-       else if ( command == WRITE_LOG )
-       {
-               // the commands will write data
-               areca_packet[6] = 0x14;
-       }
-       else
-       {
-               // the commands will return no data
-               areca_packet[6] = 0x15;
-       }
-
-
-       ata_cmd->command = ATA_SMART_CMD;
-       // Now set ATA registers depending upon command
-       switch ( command )
-       {
-       case CHECK_POWER_MODE:  
-               //printf("command = CHECK_POWER_MODE\n");
-               ata_cmd->command = ATA_CHECK_POWER_MODE;        
-               break;
-       case READ_VALUES:
-               //printf("command = READ_VALUES\n");
-               ata_cmd->features = ATA_SMART_READ_VALUES;
-               break;
-       case READ_THRESHOLDS:    
-               //printf("command = READ_THRESHOLDS\n");
-               ata_cmd->features = ATA_SMART_READ_THRESHOLDS;
-               break;
-       case READ_LOG: 
-               //printf("command = READ_LOG\n");
-               ata_cmd->features = ATA_SMART_READ_LOG_SECTOR;
-               ata_cmd->sector_number = select;        
-               break;
-       case WRITE_LOG:        
-               //printf("command = WRITE_LOG\n");    
-               ata_cmd->features = ATA_SMART_WRITE_LOG_SECTOR;
-               memcpy(ata_cmd->data, data, 512);
-               ata_cmd->sector_count = 1;
-               ata_cmd->sector_number = select;
-               break;
-       case IDENTIFY:
-               //printf("command = IDENTIFY\n");   
-               ata_cmd->command = ATA_IDENTIFY_DEVICE;         
-               break;
-       case PIDENTIFY:
-               //printf("command = PIDENTIFY\n");
-               errno=ENODEV;
-               return -1;
-       case ENABLE:
-               //printf("command = ENABLE\n");
-               ata_cmd->features = ATA_SMART_ENABLE;
-               break;
-       case DISABLE:
-               //printf("command = DISABLE\n");
-               ata_cmd->features = ATA_SMART_DISABLE;
-               break;
-       case AUTO_OFFLINE:
-               //printf("command = AUTO_OFFLINE\n");
-               ata_cmd->features = ATA_SMART_AUTO_OFFLINE;
-               // Enable or disable?
-               ata_cmd->sector_count = select;
-               break;
-       case AUTOSAVE:
-               //printf("command = AUTOSAVE\n");
-               ata_cmd->features = ATA_SMART_AUTOSAVE;
-               // Enable or disable?
-               ata_cmd->sector_count = select;
-               break;
-       case IMMEDIATE_OFFLINE:
-               //printf("command = IMMEDIATE_OFFLINE\n");
-               ata_cmd->features = ATA_SMART_IMMEDIATE_OFFLINE;
-               // What test type to run?
-               ata_cmd->sector_number = select;
-               break;
-       case STATUS_CHECK:
-               //printf("command = STATUS_CHECK\n");
-               ata_cmd->features = ATA_SMART_STATUS;           
-               break;
-       case STATUS:
-               //printf("command = STATUS\n");
-               ata_cmd->features = ATA_SMART_STATUS;       
-               break;
-       default:
-               //printf("command = UNKNOWN\n");
-               errno=ENOSYS;
-               return -1;
-       };
-
-       areca_packet[11] = m_disknum - 1;                  // drive number
-
-       // ----- BEGIN TO SETUP CHECKSUM -----
-       for ( int loop = 3; loop < areca_packet_len - 1; loop++ )
-       {
-               cs += areca_packet[loop]; 
-       }
-       areca_packet[areca_packet_len-1] = cs;
-
-       // ----- BEGIN TO SEND TO ARECA DRIVER ------
-       int expected = 0;       
-       unsigned char return_buff[2048];
-       memset(return_buff, 0, sizeof(return_buff));
-
-       expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_RQBUFFER, NULL, 0, NULL);
-        if (expected==-3) {
-           find_areca_in_proc(NULL);
-           return -1;
-       }
-
-       expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_WQBUFFER, NULL, 0, NULL);
-       expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_WRITE_WQBUFFER, areca_packet, areca_packet_len, NULL);
-       if ( expected > 0 )
-       {
-               expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_READ_RQBUFFER, return_buff, sizeof(return_buff), NULL);
-       }
-       if ( expected < 0 )
-       {
-               return -1;
-       }
-
-       // ----- VERIFY THE CHECKSUM -----
-       cs = 0;
-       for ( int loop = 3; loop < expected - 1; loop++ )
-       {
-               cs += return_buff[loop]; 
-       }
+  set_disknum(disknum);
+  set_encnum(encnum);
+  set_info().info_name = strprintf("%s [areca_disk#%02d_enc#%02d]", dev_name, disknum, encnum);
+}
 
-       if ( return_buff[expected - 1] != cs )
-       {
-               errno = EIO;
-               return -1;
-       }
+smart_device * linux_areca_scsi_device::autodetect_open()
+{
+  return this;
+}
 
-       sATA_OUTPUT_REGISTERS *ata_out = (sATA_OUTPUT_REGISTERS *)&return_buff[5] ;
-       if ( ata_out->status )
-       {
-               if ( command == IDENTIFY )
-               {
-                       pout("The firmware of your Areca RAID controller appears to be outdated!\n" \
-                                "Please update your controller to firmware version 1.46 or later.\n" \
-                                "You may download it here: ftp://ftp.areca.com.tw/RaidCards/BIOS_Firmware\n\n");
-               }
-               errno = EIO;
-               return -1;
-       }
+int linux_areca_scsi_device::arcmsr_do_scsi_io(struct scsi_cmnd_io * iop)
+{
+  int ioctlreturn = 0;
 
-       // returns with data
-       if ( command == READ_VALUES     ||
-                command == READ_THRESHOLDS ||
-                command == READ_LOG ||
-                command == IDENTIFY ||
-                command == PIDENTIFY )
-       {
-               memcpy(data, &return_buff[7], 512); 
-       }
+  if(!is_open()) {
+      if(!open()){
+          find_areca_in_proc();
+      }
+  }
 
-       if ( command == CHECK_POWER_MODE )
-       {
-               data[0] = ata_out->sector_count;
-       }
+  ioctlreturn = do_normal_scsi_cmnd_io(get_fd(), iop, scsi_debugmode);
+  if ( ioctlreturn || iop->scsi_status )
+  {
+    // errors found
+    return -1;
+  }
 
-       if ( command == STATUS_CHECK &&
-                ( ata_out->cylinder_low == 0xF4 && ata_out->cylinder_high == 0x2C ) )
-       {
-               return 1;
-       }
+  return ioctlreturn;
+}
 
-       return 0;
+bool linux_areca_scsi_device::arcmsr_lock()
+{
+  return true;
 }
 
+bool linux_areca_scsi_device::arcmsr_unlock()
+{
+  return true;
+}
 
 /////////////////////////////////////////////////////////////////////////////
 /// Marvell support
@@ -2329,8 +2268,8 @@ int linux_marvell_device::ata_command_interface(smart_command_set command, int s
     break;
   default:
     pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command);
-    EXIT(1);
-    break;
+    errno = EINVAL;
+    return -1;
   }
   // There are two different types of ioctls().  The HDIO_DRIVE_TASK
   // one is this:
@@ -2377,7 +2316,6 @@ int linux_marvell_device::ata_command_interface(smart_command_set command, int s
   return 0;
 }
 
-
 /////////////////////////////////////////////////////////////////////////////
 /// Highpoint RAID support
 
@@ -2508,17 +2446,16 @@ int linux_highpoint_device::ata_command_interface(smart_command_set command, int
 
   if (command==WRITE_LOG) {
     unsigned char task[4*sizeof(int)+sizeof(ide_task_request_t)+512];
-    unsigned int *hpt = (unsigned int *)task;
+    unsigned int *hpt_tf = (unsigned int *)task;
     ide_task_request_t *reqtask = (ide_task_request_t *)(&task[4*sizeof(int)]);
     task_struct_t *taskfile = (task_struct_t *)reqtask->io_ports;
-    int retval;
 
     memset(task, 0, sizeof(task));
 
-    hpt[0] = m_hpt_data[0]; // controller id
-    hpt[1] = m_hpt_data[1]; // channel number
-    hpt[3] = m_hpt_data[2]; // pmport number
-    hpt[2] = HDIO_DRIVE_TASKFILE; // real hd ioctl
+    hpt_tf[0] = m_hpt_data[0]; // controller id
+    hpt_tf[1] = m_hpt_data[1]; // channel number
+    hpt_tf[3] = m_hpt_data[2]; // pmport number
+    hpt_tf[2] = HDIO_DRIVE_TASKFILE; // real hd ioctl
 
     taskfile->data           = 0;
     taskfile->feature        = ATA_SMART_WRITE_LOG_SECTOR;
@@ -2536,16 +2473,13 @@ int linux_highpoint_device::ata_command_interface(smart_command_set command, int
 
     memcpy(task+sizeof(ide_task_request_t)+4*sizeof(int), data, 512);
 
-    if ((retval=ioctl(get_fd(), HPTIO_CTL, task))) {
-      if (retval==-EINVAL)
-        pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
+    if (ioctl(get_fd(), HPTIO_CTL, task))
       return -1;
-    }
+
     return 0;
   }
 
   if (command==STATUS_CHECK){
-    int retval;
     unsigned const char normal_lo=0x4f, normal_hi=0xc2;
     unsigned const char failed_lo=0xf4, failed_hi=0x2c;
     buff[4]=normal_lo;
@@ -2553,15 +2487,8 @@ int linux_highpoint_device::ata_command_interface(smart_command_set command, int
 
     hpt[2] = HDIO_DRIVE_TASK;
 
-    if ((retval=ioctl(get_fd(), HPTIO_CTL, hpt_buff))) {
-      if (retval==-EINVAL) {
-        pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
-        pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
-      }
-      else
-        syserror("Error SMART Status command failed");
+    if (ioctl(get_fd(), HPTIO_CTL, hpt_buff))
       return -1;
-    }
 
     if (buff[4]==normal_lo && buff[5]==normal_hi)
       return 0;
@@ -2585,13 +2512,13 @@ int linux_highpoint_device::ata_command_interface(smart_command_set command, int
 #if 1
   if (command==IDENTIFY || command==PIDENTIFY) {
     unsigned char deviceid[4*sizeof(int)+512*sizeof(char)];
-    unsigned int *hpt = (unsigned int *)deviceid;
+    unsigned int *hpt_id = (unsigned int *)deviceid;
 
-    hpt[0] = m_hpt_data[0]; // controller id
-    hpt[1] = m_hpt_data[1]; // channel number
-    hpt[3] = m_hpt_data[2]; // pmport number
+    hpt_id[0] = m_hpt_data[0]; // controller id
+    hpt_id[1] = m_hpt_data[1]; // channel number
+    hpt_id[3] = m_hpt_data[2]; // pmport number
 
-    hpt[2] = HDIO_GET_IDENTITY;
+    hpt_id[2] = HDIO_GET_IDENTITY;
     if (!ioctl(get_fd(), HPTIO_CTL, deviceid) && (deviceid[4*sizeof(int)] & 0x8000))
       buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
   }
@@ -2610,7 +2537,6 @@ int linux_highpoint_device::ata_command_interface(smart_command_set command, int
   return 0;
 }
 
-
 #if 0 // TODO: Migrate from 'smart_command_set' to 'ata_in_regs' OR remove the function
 // Utility function for printing warnings
 void printwarning(smart_command_set command){
@@ -2642,7 +2568,6 @@ void printwarning(smart_command_set command){
 }
 #endif
 
-
 /////////////////////////////////////////////////////////////////////////////
 /// SCSI open with autodetection support
 
@@ -2695,12 +2620,14 @@ smart_device * linux_scsi_device::autodetect_open()
     if (!memcmp(req_buff + 8, "3ware", 5) || !memcmp(req_buff + 8, "AMCC", 4)) {
       close();
       set_err(EINVAL, "AMCC/3ware controller, please try adding '-d 3ware,N',\n"
-                      "you may need to replace %s with /dev/twaN or /dev/tweN", get_dev_name());
+                      "you may need to replace %s with /dev/twlN, /dev/twaN or /dev/tweN", get_dev_name());
       return this;
     }
 
     // DELL?
-    if (!memcmp(req_buff + 8, "DELL    PERC", 12) || !memcmp(req_buff + 8, "MegaRAID", 8)) {
+    if (!memcmp(req_buff + 8, "DELL    PERC", 12) || !memcmp(req_buff + 8, "MegaRAID", 8)
+        || !memcmp(req_buff + 16, "PERC H700", 9) || !memcmp(req_buff + 8, "LSI\0",4)
+    ) {
       close();
       set_err(EINVAL, "DELL or MegaRaid controller, please try adding '-d megaraid,N'");
       return this;
@@ -2736,6 +2663,75 @@ smart_device * linux_scsi_device::autodetect_open()
   return this;
 }
 
+/////////////////////////////////////////////////////////////////////////////
+/// NVMe support
+
+class linux_nvme_device
+: public /*implements*/ nvme_device,
+  public /*extends*/ linux_smart_device
+{
+public:
+  linux_nvme_device(smart_interface * intf, const char * dev_name,
+    const char * req_type, unsigned nsid);
+
+  virtual bool open();
+
+  virtual bool nvme_pass_through(const nvme_cmd_in & in, nvme_cmd_out & out);
+};
+
+linux_nvme_device::linux_nvme_device(smart_interface * intf, const char * dev_name,
+  const char * req_type, unsigned nsid)
+: smart_device(intf, dev_name, "nvme", req_type),
+  nvme_device(nsid),
+  linux_smart_device(O_RDONLY | O_NONBLOCK)
+{
+}
+
+bool linux_nvme_device::open()
+{
+  if (!linux_smart_device::open())
+    return false;
+
+  if (!get_nsid()) {
+    // Use actual NSID (/dev/nvmeXnN) if available,
+    // else use broadcast namespace (/dev/nvmeX)
+    int nsid = ioctl(get_fd(), NVME_IOCTL_ID, (void*)0);
+    set_nsid(nsid);
+  }
+
+  return true;
+}
+
+bool linux_nvme_device::nvme_pass_through(const nvme_cmd_in & in, nvme_cmd_out & out)
+{
+  nvme_passthru_cmd pt;
+  memset(&pt, 0, sizeof(pt));
+
+  pt.opcode = in.opcode;
+  pt.nsid = in.nsid;
+  pt.addr = (uint64_t)in.buffer;
+  pt.data_len = in.size;
+  pt.cdw10 = in.cdw10;
+  pt.cdw11 = in.cdw11;
+  pt.cdw12 = in.cdw12;
+  pt.cdw13 = in.cdw13;
+  pt.cdw14 = in.cdw14;
+  pt.cdw15 = in.cdw15;
+  // Kernel default for NVMe admin commands is 60 seconds
+  // pt.timeout_ms = 60 * 1000;
+
+  int status = ioctl(get_fd(), NVME_IOCTL_ADMIN_CMD, &pt);
+
+  if (status < 0)
+    return set_err(errno, "NVME_IOCTL_ADMIN_CMD: %s", strerror(errno));
+
+  if (status > 0)
+    return set_nvme_err(out, status);
+
+  out.result = pt.result;
+  return true;
+}
+
 
 //////////////////////////////////////////////////////////////////////
 // USB bridge ID detection
@@ -2752,17 +2748,21 @@ static bool read_id(const std::string & path, unsigned short & id)
   return ok;
 }
 
-// Get USB bridge ID for "sdX"
+// Get USB bridge ID for "sdX" or "sgN"
 static bool get_usb_id(const char * name, unsigned short & vendor_id,
                        unsigned short & product_id, unsigned short & version)
 {
-  // Only "sdX" supported
-  if (!(!strncmp(name, "sd", 2) && !strchr(name, '/')))
+  // Only "sdX" or "sgN" supported
+  if (!(name[0] == 's' && (name[1] == 'd' || name[1] == 'g') && !strchr(name, '/')))
     return false;
 
-  // Start search at dir referenced by symlink "/sys/block/sdX/device"
+  // Start search at dir referenced by symlink
+  // "/sys/block/sdX/device" or
+  // "/sys/class/scsi_generic/sgN"
   // -> "/sys/devices/.../usb*/.../host*/target*/..."
-  std::string dir = strprintf("/sys/block/%s/device", name);
+  std::string dir = strprintf("/sys/%s/%s%s",
+    (name[1] == 'd' ? "block" : "class/scsi_generic"), name,
+    (name[1] == 'd' ? "/device" : ""));
 
   // Stop search at "/sys/devices"
   struct stat st;
@@ -2785,12 +2785,11 @@ static bool get_usb_id(const char * name, unsigned short & vendor_id,
         && read_id(dir + "/bcdDevice", version)   ))
     return false;
 
-  if (con->reportscsiioctl > 1)
+  if (scsi_debugmode > 1)
     pout("USB ID = 0x%04x:0x%04x (0x%03x)\n", vendor_id, product_id, version);
   return true;
 }
 
-
 //////////////////////////////////////////////////////////////////////
 /// Linux interface
 
@@ -2798,16 +2797,21 @@ class linux_smart_interface
 : public /*implements*/ smart_interface
 {
 public:
+  virtual std::string get_os_version_str();
+
   virtual std::string get_app_examples(const char * appname);
 
-  virtual bool scan_smart_devices(smart_device_list & devlist, const char * type,
-    const char * pattern = 0);
+  virtual bool scan_smart_devices(smart_device_list & devlist,
+    const smart_devtype_list & types, const char * pattern = 0);
 
 protected:
   virtual ata_device * get_ata_device(const char * name, const char * type);
 
   virtual scsi_device * get_scsi_device(const char * name, const char * type);
 
+  virtual nvme_device * get_nvme_device(const char * name, const char * type,
+    unsigned nsid);
+
   virtual smart_device * autodetect_smart_device(const char * name);
 
   virtual smart_device * get_custom_smart_device(const char * name, const char * type);
@@ -2815,12 +2819,28 @@ protected:
   virtual std::string get_valid_custom_dev_types_str();
 
 private:
-  bool get_dev_list(smart_device_list & devlist, const char * pattern,
-    bool scan_ata, bool scan_scsi, const char * req_type, bool autodetect);
+  static const int devxy_to_n_max = 103; // Max value of devxy_to_n() below
 
+  void get_dev_list(smart_device_list & devlist, const char * pattern,
+    bool scan_scsi, bool (* p_dev_sdxy_seen)[devxy_to_n_max+1],
+    bool scan_nvme, const char * req_type, bool autodetect);
+
+  bool get_dev_megasas(smart_device_list & devlist);
   smart_device * missing_option(const char * opt);
+  int megasas_dcmd_cmd(int bus_no, uint32_t opcode, void *buf,
+    size_t bufsize, uint8_t *mbox, size_t mboxlen, uint8_t *statusp);
+  int megasas_pd_add_list(int bus_no, smart_device_list & devlist);
 };
 
+std::string linux_smart_interface::get_os_version_str()
+{
+  struct utsname u;
+  if (!uname(&u))
+    return strprintf("%s-linux-%s", u.machine, u.release);
+  else
+    return SMARTMONTOOLS_BUILD_HOST;
+}
+
 std::string linux_smart_interface::get_app_examples(const char * appname)
 {
   if (!strcmp(appname, "smartctl"))
@@ -2828,41 +2848,68 @@ std::string linux_smart_interface::get_app_examples(const char * appname)
   return "";
 }
 
+// "/dev/sdXY" -> 0-103
+// "/dev/disk/by-id/NAME" -> "../../sdXY" -> 0-103
+// Other -> -1
+static int devxy_to_n(const char * name, bool debug)
+{
+  const char * xy;
+  char dest[256];
+  if (str_starts_with(name, "/dev/sd")) {
+    // Assume "/dev/sdXY"
+    xy = name + sizeof("/dev/sd") - 1;
+  }
+  else {
+    // Assume "/dev/disk/by-id/NAME", check link target
+    int sz = readlink(name, dest, sizeof(dest)-1);
+    if (!(0 < sz && sz < (int)sizeof(dest)))
+      return -1;
+    dest[sz] = 0;
+    if (!str_starts_with(dest, "../../sd"))
+      return -1;
+    if (debug)
+      pout("%s -> %s\n", name, dest);
+    xy = dest + sizeof("../../sd") - 1;
+  }
+
+  char x = xy[0];
+  if (!('a' <= x && x <= 'z'))
+    return -1;
+  char y = xy[1];
+  if (!y)
+    // "[a-z]" -> 0-25
+    return x - 'a';
 
-// we are going to take advantage of the fact that Linux's devfs will only
-// have device entries for devices that exist.  So if we get the equivalent of
-// ls /dev/hd[a-t], we have all the ATA devices on the system
-bool linux_smart_interface::get_dev_list(smart_device_list & devlist,
-  const char * pattern, bool scan_ata, bool scan_scsi,
-  const char * req_type, bool autodetect)
+  if (!(x <= 'c' && 'a' <= y && y <= 'z' && !xy[2]))
+    return -1;
+  // "[a-c][a-z]" -> 26-103
+  return (x - 'a' + 1) * ('z' - 'a' + 1) + (y - 'a');
+}
+
+void linux_smart_interface::get_dev_list(smart_device_list & devlist,
+  const char * pattern, bool scan_scsi, bool (* p_dev_sdxy_seen)[devxy_to_n_max+1],
+  bool scan_nvme, const char * req_type, bool autodetect)
 {
+  bool debug = (ata_debugmode || scsi_debugmode || nvme_debugmode);
+
   // Use glob to look for any directory entries matching the pattern
   glob_t globbuf;
   memset(&globbuf, 0, sizeof(globbuf));
   int retglob = glob(pattern, GLOB_ERR, NULL, &globbuf);
   if (retglob) {
-    //  glob failed: free memory and return
+    // glob failed: free memory and return
     globfree(&globbuf);
 
-    if (retglob==GLOB_NOMATCH){
-      pout("glob(3) found no matches for pattern %s\n", pattern);
-      return true;
-    }
+    if (debug)
+      pout("glob(3) error %d for pattern %s\n", retglob, pattern);
 
-    if (retglob==GLOB_NOSPACE)
-      set_err(ENOMEM, "glob(3) ran out of memory matching pattern %s", pattern);
-#ifdef GLOB_ABORTED // missing in old versions of glob.h
-    else if (retglob==GLOB_ABORTED)
-      set_err(EINVAL, "glob(3) aborted matching pattern %s", pattern);
-#endif
-    else
-      set_err(EINVAL, "Unexplained error in glob(3) of pattern %s", pattern);
-
-    return false;
+    if (retglob == GLOB_NOSPACE)
+      throw std::bad_alloc();
+    return;
   }
 
   // did we find too many paths?
-  const int max_pathc = 32;
+  const int max_pathc = 1024;
   int n = (int)globbuf.gl_pathc;
   if (n > max_pathc) {
     pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n",
@@ -2870,94 +2917,162 @@ bool linux_smart_interface::get_dev_list(smart_device_list & devlist,
     n = max_pathc;
   }
 
-  // now step through the list returned by glob.  If not a link, copy
-  // to list.  If it is a link, evaluate it and see if the path ends
-  // in "disc".
-  for (int i = 0; i < n; i++){
-    // see if path is a link
-    char linkbuf[1024];
-    int retlink = readlink(globbuf.gl_pathv[i], linkbuf, sizeof(linkbuf)-1);
-
-    char tmpname[1024]={0};
-    const char * name = 0;
-    bool is_scsi = scan_scsi;
-    // if not a link (or a strange link), keep it
-    if (retlink<=0 || retlink>1023)
-      name = globbuf.gl_pathv[i];
-    else {
-      // or if it's a link that points to a disc, follow it
-      linkbuf[retlink] = 0;
-      const char *p;
-      if ((p=strrchr(linkbuf, '/')) && !strcmp(p+1, "disc"))
-        // This is the branch of the code that gets followed if we are
-        // using devfs WITH traditional compatibility links. In this
-        // case, we add the traditional device name to the list that
-        // is returned.
-        name = globbuf.gl_pathv[i];
-      else {
-        // This is the branch of the code that gets followed if we are
-        // using devfs WITHOUT traditional compatibility links.  In
-        // this case, we check that the link to the directory is of
-        // the correct type, and then append "disc" to it.
-        bool match_ata  = strstr(linkbuf, "ide");
-        bool match_scsi = strstr(linkbuf, "scsi");
-        if (((match_ata && scan_ata) || (match_scsi && scan_scsi)) && !(match_ata && match_scsi)) {
-          is_scsi = match_scsi;
-          snprintf(tmpname, sizeof(tmpname), "%s/disc", globbuf.gl_pathv[i]);
-          name = tmpname;
-        }
+  // now step through the list returned by glob.
+  for (int i = 0; i < n; i++) {
+    const char * name = globbuf.gl_pathv[i];
+
+    if (p_dev_sdxy_seen) {
+      // Follow "/dev/disk/by-id/*" symlink and check for duplicate "/dev/sdXY"
+      int dev_n = devxy_to_n(name, debug);
+      if (!(0 <= dev_n && dev_n <= devxy_to_n_max))
+        continue;
+      if ((*p_dev_sdxy_seen)[dev_n]) {
+        if (debug)
+         pout("%s: duplicate, ignored\n", name);
+        continue;
       }
+      (*p_dev_sdxy_seen)[dev_n] = true;
     }
 
-    if (name) {
-      // Found a name, add device to list.
-      smart_device * dev;
-      if (autodetect)
-        dev = autodetect_smart_device(name);
-      else if (is_scsi)
-        dev = new linux_scsi_device(this, name, req_type, true /*scanning*/);
-      else
-        dev = new linux_ata_device(this, name, req_type);
-      if (dev) // autodetect_smart_device() may return nullptr.
-        devlist.push_back(dev);
+    smart_device * dev;
+    if (autodetect) {
+      dev = autodetect_smart_device(name);
+      if (!dev)
+        continue;
     }
+    else if (scan_scsi)
+      dev = new linux_scsi_device(this, name, req_type, true /*scanning*/);
+    else if (scan_nvme)
+      dev = new linux_nvme_device(this, name, req_type, 0 /* use default nsid */);
+    else
+      dev = new linux_ata_device(this, name, req_type);
+    devlist.push_back(dev);
   }
 
   // free memory
   globfree(&globbuf);
+}
 
+// getting devices from LSI SAS MegaRaid, if available
+bool linux_smart_interface::get_dev_megasas(smart_device_list & devlist)
+{
+  /* Scanning of disks on MegaRaid device */
+  /* Perform mknod of device ioctl node */
+  int   mjr, n1;
+  char line[128];
+  bool scan_megasas = false;
+  FILE * fp = fopen("/proc/devices", "r");
+  if (!fp)
+    return false;
+  while (fgets(line, sizeof(line), fp) != NULL) {
+    n1=0;
+    if (sscanf(line, "%d megaraid_sas_ioctl%n", &mjr, &n1) == 1 && n1 == 22) {
+      scan_megasas = true;
+      n1=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR, makedev(mjr, 0));
+      if(scsi_debugmode > 0)
+        pout("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1 >= 0 ? 0 : errno);
+      if (n1 >= 0 || errno == EEXIST)
+        break;
+    }
+  }
+  fclose(fp);
+
+  if(!scan_megasas)
+    return false;
+
+  // getting bus numbers with megasas devices
+  // we are using sysfs to get list of all scsi hosts
+  DIR * dp = opendir ("/sys/class/scsi_host/");
+  if (dp != NULL)
+  {
+    struct dirent *ep;
+    while ((ep = readdir (dp)) != NULL) {
+      unsigned int host_no = 0;
+      if (!sscanf(ep->d_name, "host%u", &host_no))
+        continue;
+      /* proc_name should be megaraid_sas */
+      char sysfsdir[256];
+      snprintf(sysfsdir, sizeof(sysfsdir) - 1,
+        "/sys/class/scsi_host/host%u/proc_name", host_no);
+      if((fp = fopen(sysfsdir, "r")) == NULL)
+        continue;
+      if(fgets(line, sizeof(line), fp) != NULL && !strncmp(line,"megaraid_sas",12)) {
+        megasas_pd_add_list(host_no, devlist);
+      }
+      fclose(fp);
+    }
+    (void) closedir (dp);
+  } else { /* sysfs not mounted ? */
+    for(unsigned i = 0; i <=16; i++) // trying to add devices on first 16 buses
+      megasas_pd_add_list(i, devlist);
+  }
   return true;
 }
 
 bool linux_smart_interface::scan_smart_devices(smart_device_list & devlist,
-  const char * type, const char * pattern /*= 0*/)
+  const smart_devtype_list & types, const char * pattern /*= 0*/)
 {
-  if (pattern) {
-    set_err(EINVAL, "DEVICESCAN with pattern not implemented yet");
-    return false;
+  if (pattern)
+    return set_err(EINVAL, "DEVICESCAN with pattern not implemented yet");
+
+  // Scan type list
+  bool by_id = false;
+  const char * type_ata = 0, * type_scsi = 0, * type_sat = 0, * type_nvme = 0;
+  for (unsigned i = 0; i < types.size(); i++) {
+    const char * type = types[i].c_str();
+    if (!strcmp(type, "by-id"))
+      by_id = true;
+    else if (!strcmp(type, "ata"))
+      type_ata = "ata";
+    else if (!strcmp(type, "scsi"))
+      type_scsi = "scsi";
+    else if (!strcmp(type, "sat"))
+      type_sat = "sat";
+    else if (!strcmp(type, "nvme"))
+      type_nvme = "nvme";
+    else
+      return set_err(EINVAL, "Invalid type '%s', valid arguments are: by-id, ata, scsi, sat, nvme",
+                     type);
+  }
+  // Use default if no type specified
+  if (!(type_ata || type_scsi || type_sat || type_nvme)) {
+     type_ata = type_scsi = type_sat = "";
+#ifdef WITH_NVME_DEVICESCAN // TODO: Remove when NVMe support is no longer EXPERIMENTAL
+     type_nvme = "";
+#endif
   }
 
-  if (!type)
-    type = "";
+  if (type_ata)
+    get_dev_list(devlist, "/dev/hd[a-t]", false, 0, false, type_ata, false);
 
-  bool scan_ata  = (!*type || !strcmp(type, "ata" ));
-  // "sat" detection will be later handled in linux_scsi_device::autodetect_open()
-  bool scan_scsi = (!*type || !strcmp(type, "scsi") || !strcmp(type, "sat"));
-  if (!(scan_ata || scan_scsi))
-    return true;
+  if (type_scsi || type_sat) {
+    // "sat" detection will be later handled in linux_scsi_device::autodetect_open()
+    const char * type_scsi_sat = ((type_scsi && type_sat) ? "" // detect both
+                                  : (type_scsi ? type_scsi : type_sat));
+    bool autodetect = !*type_scsi_sat; // If no type specified, detect USB also
+
+    bool dev_sdxy_seen[devxy_to_n_max+1] = {false, };
+    bool (*p_dev_sdxy_seen)[devxy_to_n_max+1] = 0;
+    if (by_id) {
+      // Scan unique symlinks first
+      get_dev_list(devlist, "/dev/disk/by-id/*", true, &dev_sdxy_seen, false,
+                   type_scsi_sat, autodetect);
+      p_dev_sdxy_seen = &dev_sdxy_seen; // Check for duplicates below
+    }
 
-  if (scan_ata)
-    get_dev_list(devlist, "/dev/hd[a-t]", true, false, type, false);
-  if (scan_scsi) // Try USB autodetection if no type specifed
-    get_dev_list(devlist, "/dev/sd[a-z]", false, true, type, !*type);
+    get_dev_list(devlist, "/dev/sd[a-z]", true, p_dev_sdxy_seen, false, type_scsi_sat, autodetect);
+    get_dev_list(devlist, "/dev/sd[a-c][a-z]", true, p_dev_sdxy_seen, false, type_scsi_sat, autodetect);
 
-  // if we found traditional links, we are done
-  if (devlist.size() > 0)
-    return true;
+    // get device list from the megaraid device
+    get_dev_megasas(devlist);
+  }
 
-  // else look for devfs entries without traditional links
-  // TODO: Add udev support
-  return get_dev_list(devlist, "/dev/discs/disc*", scan_ata, scan_scsi, type, false);
+  if (type_nvme) {
+    get_dev_list(devlist, "/dev/nvme[0-9]", false, 0, true, type_nvme, false);
+    get_dev_list(devlist, "/dev/nvme[1-9][0-9]", false, 0, true, type_nvme, false);
+  }
+
+  return true;
 }
 
 ata_device * linux_smart_interface::get_ata_device(const char * name, const char * type)
@@ -2970,132 +3085,261 @@ scsi_device * linux_smart_interface::get_scsi_device(const char * name, const ch
   return new linux_scsi_device(this, name, type);
 }
 
+nvme_device * linux_smart_interface::get_nvme_device(const char * name, const char * type,
+  unsigned nsid)
+{
+  return new linux_nvme_device(this, name, type, nsid);
+}
+
 smart_device * linux_smart_interface::missing_option(const char * opt)
 {
   set_err(EINVAL, "requires option '%s'", opt);
   return 0;
 }
 
-// Return true if STR starts with PREFIX.
-static bool str_starts_with(const char * str, const char * prefix)
+int
+linux_smart_interface::megasas_dcmd_cmd(int bus_no, uint32_t opcode, void *buf,
+  size_t bufsize, uint8_t *mbox, size_t mboxlen, uint8_t *statusp)
 {
-  return !strncmp(str, prefix, strlen(prefix));
+  struct megasas_iocpacket ioc;
+
+  if ((mbox != NULL && (mboxlen == 0 || mboxlen > MFI_MBOX_SIZE)) ||
+    (mbox == NULL && mboxlen != 0)) 
+  {
+    errno = EINVAL;
+    return (-1);
+  }
+
+  bzero(&ioc, sizeof(ioc));
+  struct megasas_dcmd_frame * dcmd = &ioc.frame.dcmd;
+  ioc.host_no = bus_no;
+  if (mbox)
+    bcopy(mbox, dcmd->mbox.w, mboxlen);
+  dcmd->cmd = MFI_CMD_DCMD;
+  dcmd->timeout = 0;
+  dcmd->flags = 0;
+  dcmd->data_xfer_len = bufsize;
+  dcmd->opcode = opcode;
+
+  if (bufsize > 0) {
+    dcmd->sge_count = 1;
+    dcmd->data_xfer_len = bufsize;
+    dcmd->sgl.sge32[0].phys_addr = (intptr_t)buf;
+    dcmd->sgl.sge32[0].length = (uint32_t)bufsize;
+    ioc.sge_count = 1;
+    ioc.sgl_off = offsetof(struct megasas_dcmd_frame, sgl);
+    ioc.sgl[0].iov_base = buf;
+    ioc.sgl[0].iov_len = bufsize;
+  }
+
+  int fd;
+  if ((fd = ::open("/dev/megaraid_sas_ioctl_node", O_RDWR)) <= 0) {
+    return (errno);
+  }
+
+  int r = ioctl(fd, MEGASAS_IOC_FIRMWARE, &ioc);
+  ::close(fd);
+  if (r < 0) {
+    return (r);
+  }
+
+  if (statusp != NULL)
+    *statusp = dcmd->cmd_status;
+  else if (dcmd->cmd_status != MFI_STAT_OK) {
+    fprintf(stderr, "command %x returned error status %x\n",
+      opcode, dcmd->cmd_status);
+    errno = EIO;
+    return (-1);
+  }
+  return (0);
+}
+
+int
+linux_smart_interface::megasas_pd_add_list(int bus_no, smart_device_list & devlist)
+{
+  /*
+  * Keep fetching the list in a loop until we have a large enough
+  * buffer to hold the entire list.
+  */
+  megasas_pd_list * list = 0;
+  for (unsigned list_size = 1024; ; ) {
+    list = reinterpret_cast<megasas_pd_list *>(realloc(list, list_size));
+    if (!list)
+      throw std::bad_alloc();
+    bzero(list, list_size);
+    if (megasas_dcmd_cmd(bus_no, MFI_DCMD_PD_GET_LIST, list, list_size, NULL, 0,
+      NULL) < 0) 
+    {
+      free(list);
+      return (-1);
+    }
+    if (list->size <= list_size)
+      break;
+    list_size = list->size;
+  }
+
+  // adding all SCSI devices
+  for (unsigned i = 0; i < list->count; i++) {
+    if(list->addr[i].scsi_dev_type)
+      continue; /* non disk device found */
+    char line[128];
+    snprintf(line, sizeof(line) - 1, "/dev/bus/%d", bus_no);
+    smart_device * dev = new linux_megaraid_device(this, line, list->addr[i].device_id);
+    devlist.push_back(dev);
+  }
+  free(list);
+  return (0);
+}
+
+// Return kernel release as integer ("2.6.31" -> 206031)
+static unsigned get_kernel_release()
+{
+  struct utsname u;
+  if (uname(&u))
+    return 0;
+  unsigned x = 0, y = 0, z = 0;
+  if (!(sscanf(u.release, "%u.%u.%u", &x, &y, &z) == 3
+        && x < 100 && y < 100 && z < 1000             ))
+    return 0;
+  return x * 100000 + y * 1000 + z;
+}
+
+// Check for SCSI host proc_name "hpsa"
+static bool is_hpsa(const char * name)
+{
+  char path[128];
+  snprintf(path, sizeof(path), "/sys/block/%s/device", name);
+  char * syshostpath = realpath(path, (char *)0);
+  if (!syshostpath)
+    return false;
+
+  char * syshost = strrchr(syshostpath, '/');
+  if (!syshost) {
+    free(syshostpath);
+    return false;
+  }
+
+  char * hostsep = strchr(++syshost, ':');
+  if (hostsep)
+    *hostsep = 0;
+
+  snprintf(path, sizeof(path), "/sys/class/scsi_host/host%s/proc_name", syshost);
+  free(syshostpath);
+  int fd = open(path, O_RDONLY);
+  if (fd < 0)
+    return false;
+
+  char proc_name[32];
+  ssize_t n = read(fd, proc_name, sizeof(proc_name) - 1);
+  close(fd);
+  if (n < 4)
+    return false;
+
+  proc_name[n] = 0;
+  if (proc_name[n - 1] == '\n')
+    proc_name[n - 1] = 0;
+
+  if (scsi_debugmode > 1)
+    pout("%s -> %s: \"%s\"\n", name, path, proc_name);
+
+  if (strcmp(proc_name, "hpsa"))
+    return false;
+
+  return true;
 }
 
 // Guess device type (ata or scsi) based on device name (Linux
 // specific) SCSI device name in linux can be sd, sr, scd, st, nst,
 // osst, nosst and sg.
-static const char * lin_dev_prefix = "/dev/";
-static const char * lin_dev_ata_disk_plus = "h";
-static const char * lin_dev_ata_devfs_disk_plus = "ide/";
-static const char * lin_dev_scsi_devfs_disk_plus = "scsi/";
-static const char * lin_dev_scsi_disk_plus = "s";
-static const char * lin_dev_scsi_tape1 = "ns";
-static const char * lin_dev_scsi_tape2 = "os";
-static const char * lin_dev_scsi_tape3 = "nos";
-static const char * lin_dev_3ware_9000_char = "twa";
-static const char * lin_dev_3ware_678k_char = "twe";
-static const char * lin_dev_cciss_dir = "cciss/";
-static const char * lin_dev_areca = "sg";
-
 smart_device * linux_smart_interface::autodetect_smart_device(const char * name)
 {
-  const char * dev_name = name; // TODO: Remove this hack
-  int dev_prefix_len = strlen(lin_dev_prefix);
+  const char * test_name = name;
 
-  // if dev_name null, or string length zero
-  int len;
-  if (!dev_name || !(len = strlen(dev_name)))
-    return 0;
-
-  // Dereference if /dev/disk/by-*/* symlink
-  char linkbuf[100];
-  if (   str_starts_with(dev_name, "/dev/disk/by-")
-      && readlink(dev_name, linkbuf, sizeof(linkbuf)) > 0
-      && str_starts_with(linkbuf, "../../")) {
-    dev_name = linkbuf + sizeof("../../")-1;
+  // Dereference symlinks
+  struct stat st;
+  std::string pathbuf;
+  if (!lstat(name, &st) && S_ISLNK(st.st_mode)) {
+    char * p = realpath(name, (char *)0);
+    if (p) {
+      pathbuf = p;
+      free(p);
+      test_name = pathbuf.c_str();
+    }
   }
+
   // Remove the leading /dev/... if it's there
-  else if (!strncmp(lin_dev_prefix, dev_name, dev_prefix_len)) {
-    if (len <= dev_prefix_len)
-      // if nothing else in the string, unrecognized
-      return 0;
-    // else advance pointer to following characters
-    dev_name += dev_prefix_len;
-  }
+  static const char dev_prefix[] = "/dev/";
+  if (str_starts_with(test_name, dev_prefix))
+    test_name += strlen(dev_prefix);
 
   // form /dev/h* or h*
-  if (!strncmp(lin_dev_ata_disk_plus, dev_name,
-               strlen(lin_dev_ata_disk_plus)))
+  if (str_starts_with(test_name, "h"))
     return new linux_ata_device(this, name, "");
 
   // form /dev/ide/* or ide/*
-  if (!strncmp(lin_dev_ata_devfs_disk_plus, dev_name,
-               strlen(lin_dev_ata_devfs_disk_plus)))
+  if (str_starts_with(test_name, "ide/"))
     return new linux_ata_device(this, name, "");
 
   // form /dev/s* or s*
-  if (!strncmp(lin_dev_scsi_disk_plus, dev_name,
-               strlen(lin_dev_scsi_disk_plus))) {
+  if (str_starts_with(test_name, "s")) {
 
     // Try to detect possible USB->(S)ATA bridge
     unsigned short vendor_id = 0, product_id = 0, version = 0;
-    if (get_usb_id(dev_name, vendor_id, product_id, version)) {
+    if (get_usb_id(test_name, vendor_id, product_id, version)) {
       const char * usbtype = get_usb_dev_type_by_id(vendor_id, product_id, version);
       if (!usbtype)
         return 0;
-      // Linux USB layer does not support 16 byte SAT pass through command
-      if (!strcmp(usbtype, "sat"))
+
+      // Kernels before 2.6.29 do not support the sense data length
+      // required for SAT ATA PASS-THROUGH(16)
+      if (!strcmp(usbtype, "sat") && get_kernel_release() < 206029)
         usbtype = "sat,12";
+
       // Return SAT/USB device for this type
       // (Note: linux_scsi_device::autodetect_open() will not be called in this case)
-      return get_sat_device(usbtype, new linux_scsi_device(this, name, ""));
+      return get_scsi_passthrough_device(usbtype, new linux_scsi_device(this, name, ""));
     }
 
-    // No USB bridge found, assume regular SCSI device
+    // Fail if hpsa driver
+    if (is_hpsa(test_name))
+      return missing_option("-d cciss,N");
+
+    // No USB bridge or hpsa driver found, assume regular SCSI device
     return new linux_scsi_device(this, name, "");
   }
 
   // form /dev/scsi/* or scsi/*
-  if (!strncmp(lin_dev_scsi_devfs_disk_plus, dev_name,
-               strlen(lin_dev_scsi_devfs_disk_plus)))
+  if (str_starts_with(test_name, "scsi/"))
+    return new linux_scsi_device(this, name, "");
+
+  // form /dev/bsg/* or bsg/*
+  if (str_starts_with(test_name, "bsg/"))
     return new linux_scsi_device(this, name, "");
 
   // form /dev/ns* or ns*
-  if (!strncmp(lin_dev_scsi_tape1, dev_name,
-               strlen(lin_dev_scsi_tape1)))
+  if (str_starts_with(test_name, "ns"))
     return new linux_scsi_device(this, name, "");
 
   // form /dev/os* or os*
-  if (!strncmp(lin_dev_scsi_tape2, dev_name,
-               strlen(lin_dev_scsi_tape2)))
+  if (str_starts_with(test_name, "os"))
     return new linux_scsi_device(this, name, "");
 
   // form /dev/nos* or nos*
-  if (!strncmp(lin_dev_scsi_tape3, dev_name,
-               strlen(lin_dev_scsi_tape3)))
+  if (str_starts_with(test_name, "nos"))
     return new linux_scsi_device(this, name, "");
 
-  // form /dev/twa*
-  if (!strncmp(lin_dev_3ware_9000_char, dev_name,
-               strlen(lin_dev_3ware_9000_char)))
-    return missing_option("-d 3ware,N");
+  // form /dev/nvme* or nvme*
+  if (str_starts_with(test_name, "nvme"))
+    return new linux_nvme_device(this, name, "", 0 /* use default nsid */);
 
-  // form /dev/twe*
-  if (!strncmp(lin_dev_3ware_678k_char, dev_name,
-               strlen(lin_dev_3ware_678k_char)))
+  // form /dev/tw[ael]* or tw[ael]*
+  if (str_starts_with(test_name, "tw") && strchr("ael", test_name[2]))
     return missing_option("-d 3ware,N");
 
-  // form /dev/cciss*
-  if (!strncmp(lin_dev_cciss_dir, dev_name,
-               strlen(lin_dev_cciss_dir)))
+  // form /dev/cciss/* or cciss/*
+  if (str_starts_with(test_name, "cciss/"))
     return missing_option("-d cciss,N");
 
-  // form /dev/sg*
-  if ( !strncmp(lin_dev_areca, dev_name,
-                strlen(lin_dev_areca)) )
-    return missing_option("-d areca,N");
-
   // we failed to recognize any of the forms
   return 0;
 }
@@ -3118,7 +3362,9 @@ smart_device * linux_smart_interface::get_custom_smart_device(const char * name,
       return 0;
     }
 
-    if (!strncmp(name, "/dev/twa", 8))
+    if (!strncmp(name, "/dev/twl", 8))
+      return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_9700_CHAR, disknum);
+    else if (!strncmp(name, "/dev/twa", 8))
       return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_9000_CHAR, disknum);
     else if (!strncmp(name, "/dev/twe", 8))
       return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_678K_CHAR, disknum);
@@ -3128,16 +3374,17 @@ smart_device * linux_smart_interface::get_custom_smart_device(const char * name,
 
   // Areca?
   disknum = n1 = n2 = -1;
-  if (sscanf(type, "areca,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
-    if (n2 != (int)strlen(type)) {
-      set_err(EINVAL, "Option -d areca,N requires N to be a non-negative integer");
+  int encnum = 1;
+  if (sscanf(type, "areca,%n%d/%d%n", &n1, &disknum, &encnum, &n2) >= 1 || n1 == 6) {
+    if (!(1 <= disknum && disknum <= 128)) {
+      set_err(EINVAL, "Option -d areca,N/E (N=%d) must have 1 <= N <= 128", disknum);
       return 0;
     }
-    if (!(1 <= disknum && disknum <= 24)) {
-      set_err(EINVAL, "Option -d areca,N (N=%d) must have 1 <= N <= 24", disknum);
+    if (!(1 <= encnum && encnum <= 8)) {
+      set_err(EINVAL, "Option -d areca,N/E (E=%d) must have 1 <= E <= 8", encnum);
       return 0;
     }
-    return new linux_areca_device(this, name, disknum);
+    return new linux_areca_ata_device(this, name, disknum, encnum);
   }
 
   // Highpoint ?
@@ -3153,7 +3400,7 @@ smart_device * linux_smart_interface::get_custom_smart_device(const char * name,
       set_err(EINVAL, "Option '-d hpt,L/M/N' invalid controller id L supplied");
       return 0;
     }
-    if (!(1 <= channel && channel <= 8)) {
+    if (!(1 <= channel && channel <= 128)) {
       set_err(EINVAL, "Option '-d hpt,L/M/N' invalid channel number M supplied");
       return 0;
     }
@@ -3172,24 +3419,34 @@ smart_device * linux_smart_interface::get_custom_smart_device(const char * name,
       set_err(EINVAL, "Option -d cciss,N requires N to be a non-negative integer");
       return 0;
     }
-    if (!(0 <= disknum && disknum <= 15)) {
-      set_err(EINVAL, "Option -d cciss,N (N=%d) must have 0 <= N <= 15", disknum);
+    if (!(0 <= disknum && disknum <= 127)) {
+      set_err(EINVAL, "Option -d cciss,N (N=%d) must have 0 <= N <= 127", disknum);
       return 0;
     }
-    return new linux_cciss_device(this, name, disknum);
+    return get_sat_device("sat,auto", new linux_cciss_device(this, name, disknum));
   }
 #endif // HAVE_LINUX_CCISS_IOCTL_H
 
   // MegaRAID ?
   if (sscanf(type, "megaraid,%d", &disknum) == 1) {
-    return new linux_megaraid_device(this, name, 0, disknum);
+    return new linux_megaraid_device(this, name, disknum);
   }
+
+  //aacraid?
+  unsigned host, chan, device;
+  if (sscanf(type, "aacraid,%u,%u,%u", &host, &chan, &device) == 3) {
+    //return new linux_aacraid_device(this,name,channel,device);
+    return get_sat_device("sat,auto",
+      new linux_aacraid_device(this, name, host, chan, device));
+
+  }
+
   return 0;
 }
 
 std::string linux_smart_interface::get_valid_custom_dev_types_str()
 {
-  return "marvell, areca,N, 3ware,N, hpt,L/M/N, megaraid,N"
+  return "marvell, areca,N/E, 3ware,N, hpt,L/M/N, megaraid,N, aacraid,H,L,ID"
 #ifdef HAVE_LINUX_CCISS_IOCTL_H
                                               ", cciss,N"
 #endif
@@ -3198,7 +3455,6 @@ std::string linux_smart_interface::get_valid_custom_dev_types_str()
 
 } // namespace
 
-
 /////////////////////////////////////////////////////////////////////////////
 /// Initialize platform interface and register with smi()