]> git.proxmox.com Git - mirror_smartmontools-debian.git/blobdiff - os_freebsd.cpp
Updated changelog
[mirror_smartmontools-debian.git] / os_freebsd.cpp
index f92ab489791ab027753c4db054e4802ff87f2bc9..5038b1219ecc52e6aff98c95e677ec81cf308586 100644 (file)
@@ -3,7 +3,7 @@
  *
  * Home page of code is: http://smartmontools.sourceforge.net
  *
- * Copyright (C) 2003-8 Eduard Martinescu <smartmontools-support@lists.sourceforge.net>
+ * Copyright (C) 2003-10 Eduard Martinescu <smartmontools-support@lists.sourceforge.net>
  *
  * 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
@@ -20,6 +20,7 @@
 #include <dirent.h>
 #include <fcntl.h>
 #include <err.h>
+#include <errno.h>
 #include <camlib.h>
 #include <cam/scsi/scsi_message.h>
 #include <cam/scsi/scsi_pass.h>
@@ -41,7 +42,6 @@
 #include "scsicmds.h"
 #include "cciss.h"
 #include "utility.h"
-#include "extern.h"
 #include "os_freebsd.h"
 
 #include "dev_interface.h"
 #if (FREEBSDVER >= 800000)
 #include <libusb20_desc.h>
 #include <libusb20.h>
+#elif defined(__DragonFly__)
+#include <bus/usb/usb.h>
+#include <bus/usb/usbhid.h>
 #else
 #include <dev/usb/usb.h>
 #include <dev/usb/usbhid.h>
 #endif
 
-#define CONTROLLER_UNKNOWN              0x00
-#define CONTROLLER_ATA                  0x01
-#define CONTROLLER_SCSI                 0x02
-#define CONTROLLER_3WARE_678K           0x04  // NOT set by guess_device_type()
-#define CONTROLLER_3WARE_9000_CHAR      0x05  // set by guess_device_type()
-#define CONTROLLER_3WARE_678K_CHAR      0x06  // set by guess_device_type()
-#define CONTROLLER_HPT                  0x09  // SATA drives behind HighPoint Raid controllers
-#define CONTROLLER_CCISS  0x10  // CCISS controller 
+#define CONTROLLER_3WARE_9000_CHAR      0x01
+#define CONTROLLER_3WARE_678K_CHAR      0x02
 
-static __unused const char *filenameandversion="$Id: os_freebsd.cpp 2920 2009-09-20 12:22:41Z samm2 $";
+#ifndef PATHINQ_SETTINGS_SIZE
+#define PATHINQ_SETTINGS_SIZE   128
+#endif
 
-const char *os_XXXX_c_cvsid="$Id: os_freebsd.cpp 2920 2009-09-20 12:22:41Z samm2 $" \
+const char *os_XXXX_c_cvsid="$Id: os_freebsd.cpp 3525 2012-03-22 08:54:52Z samm2 $" \
 ATACMDS_H_CVSID CCISS_H_CVSID CONFIG_H_CVSID INT64_H_CVSID OS_FREEBSD_H_CVSID SCSICMDS_H_CVSID UTILITY_H_CVSID;
 
-extern smartmonctrl * con;
-
-// Private table of open devices: guaranteed zero on startup since
-// part of static data.
-struct freebsd_dev_channel *devicetable[FREEBSD_MAXDEV];
-
-// Returns 1 if device not available/open/found else 0.  Also shifts fd into valid range.
-static int isnotopen(int *fd, struct freebsd_dev_channel** fdchan) {
-  // put valid "file descriptor" into range 0...FREEBSD_MAXDEV-1
-  *fd -= FREEBSD_FDOFFSET;
-
-  // check for validity of "file descriptor".
-  if (*fd<0 || *fd>=FREEBSD_MAXDEV || !((*fdchan)=devicetable[*fd])) {
-    errno = ENODEV;
-    return 1;
-  }
-
-  return 0;
-}
-
 #define NO_RETURN 0
 #define BAD_SMART 1
 #define NO_DISK_3WARE 2
@@ -138,20 +117,11 @@ void printwarning(int msgNo, const char* extra) {
 #define ATA_DEVICE "/dev/ata"
 #endif
 
+#define ARGUSED(x) ((void)(x))
+
 // global variable holding byte count of allocated memory
 long long bytes;
 
-const char * dev_freebsd_cpp_cvsid = "$Id: os_freebsd.cpp 2920 2009-09-20 12:22:41Z samm2 $"
-  DEV_INTERFACE_H_CVSID;
-
-extern smartmonctrl * con; // con->reportscsiioctl
-
-/////////////////////////////////////////////////////////////////////////////
-
-#ifdef HAVE_ATA_IDENTIFY_IS_CACHED
-int ata_identify_is_cached(int fd);
-#endif
-
 /////////////////////////////////////////////////////////////////////////////
 
 namespace os_freebsd { // No need to publish anything, name provided for Doxygen
@@ -180,6 +150,9 @@ 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.
   const char * m_mode; ///< Mode string for deviceopen().
@@ -188,7 +161,7 @@ private:
 #ifdef __GLIBC__
 static inline void * reallocf(void *ptr, size_t size) {
    void *rv = realloc(ptr, size);
-   if(rv == NULL)
+   if((rv == NULL) && (size != 0))
      free(ptr);
    return rv;
    }
@@ -221,6 +194,9 @@ static const char  smartctl_examples[] =
   "  smartctl -a --device=cciss,0 /dev/ciss0\n"
          "                              (Prints all SMART information for first disk \n"
          "                               on Common Interface for SCSI-3 Support driver)\n"
+  "  smartctl -a --device=areca,1 /dev/arcmsr0\n"
+         "                              (Prints all SMART information for first disk \n"
+         "                               on first ARECA RAID controller)\n"
 
          ;
 
@@ -230,593 +206,248 @@ bool freebsd_smart_device::is_open() const
 }
 
 
-static int hpt_hba(const char* name) {
-  int i=0;
-  const char *hpt_node[]={"hptmv", "hptmv6", "hptrr", "hptiop", "hptmviop", "hpt32xx", "rr2320",
-  "rr232x", "rr2310", "rr2310_00", "rr2300", "rr2340", "rr1740", NULL};
-  while (hpt_node[i]) {
-    if (!strncmp(name, hpt_node[i], strlen(hpt_node[i])))
-      return 1;
-    i++;
+bool freebsd_smart_device::open()
+{
+  const char *dev = get_dev_name();
+  if ((m_fd = ::open(dev,O_RDONLY))<0) {
+    set_err(errno);
+    return false;
   }
-  return 0;
+  return true;
 }
 
-static int get_tw_channel_unit (const char* name, int* unit, int* dev) {
-  const char *p;
-  /* device node sanity check */
-  for (p = name + 3; *p; p++)
-    if (*p < '0' || *p > '9')
-    return -1;
-  if (strlen(name) > 4 && *(name + 3) == '0')
-    return -1;
+bool freebsd_smart_device::close()
+{
+  int failed = 0;
+  // close device, if open
+  if (is_open())
+    failed=::close(get_fd());
 
-  if (dev != NULL)
-    *dev=atoi(name + 3);
+  set_fd(-1);
 
-  /* no need for unit number */
-  if (unit != NULL)
-    *unit=0;
-  return 0;
+  if(failed) return false;
+    else return true;
 }
 
-#ifndef IOCATAREQUEST
-static int get_ata_channel_unit ( const char* name, int* unit, int* dev) {
-#ifndef ATAREQUEST
-  *dev=0;
-  *unit=0;
-  return 0;
-#else
-  // there is no direct correlation between name 'ad0, ad1, ...' and
-  // channel/unit number.  So we need to iterate through the possible
-  // channels and check each unit to see if we match names
-  struct ata_cmd iocmd;
-  int fd,maxunit;
+/////////////////////////////////////////////////////////////////////////////
+/// Implement standard ATA support
 
-  bzero(&iocmd, sizeof(struct ata_cmd));
+class freebsd_ata_device
+: public /*implements*/ ata_device,
+  public /*extends*/ freebsd_smart_device
+{
+public:
+  freebsd_ata_device(smart_interface * intf, const char * dev_name, const char * req_type);
+  virtual bool ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out);
 
-  if ((fd = open(ATA_DEVICE, O_RDWR)) < 0)
-    return -errno;
+protected:
+  virtual int do_cmd(struct ata_ioc_request* request, bool is_48bit_cmd);
+};
 
-  iocmd.cmd = ATAGMAXCHANNEL;
-  if (ioctl(fd, IOCATA, &iocmd) < 0) {
-    return -errno;
-    close(fd);
-  }
-  maxunit = iocmd.u.maxchan;
-  for (*unit = 0; *unit < maxunit; (*unit)++) {
-    iocmd.channel = *unit;
-    iocmd.device = -1;
-    iocmd.cmd = ATAGPARM;
-    if (ioctl(fd, IOCATA, &iocmd) < 0) {
-      close(fd);
-      return -errno;
-    }
-    if (iocmd.u.param.type[0] && !strcmp(name,iocmd.u.param.name[0])) {
-      *dev = 0;
-      break;
-    }
-    if (iocmd.u.param.type[1] && !strcmp(name,iocmd.u.param.name[1])) {
-      *dev = 1;
-      break;
-    }
-  }
-  close(fd);
-  if (*unit == maxunit)
-    return -1;
-  else
-    return 0;
-#endif
+freebsd_ata_device::freebsd_ata_device(smart_interface * intf, const char * dev_name, const char * req_type)
+: smart_device(intf, dev_name, "ata", req_type),
+  freebsd_smart_device("ATA")
+{
 }
-#endif
-
-// Guess device type (ata or scsi) based on device name (FreeBSD
-// specific) SCSI device name in FreeBSD can be sd, sr, scd, st, nst,
-// osst, nosst and sg.
-static const char * fbsd_dev_prefix = _PATH_DEV;
-static const char * fbsd_dev_ata_disk_prefix = "ad";
-static const char * fbsd_dev_scsi_disk_plus = "da";
-static const char * fbsd_dev_scsi_pass = "pass";
-static const char * fbsd_dev_scsi_tape1 = "sa";
-static const char * fbsd_dev_scsi_tape2 = "nsa";
-static const char * fbsd_dev_scsi_tape3 = "esa";
-static const char * fbsd_dev_twe_ctrl = "twe";
-static const char * fbsd_dev_twa_ctrl = "twa";
-static const char * fbsd_dev_cciss = "ciss";
-
-int parse_ata_chan_dev(const char * dev_name, struct freebsd_dev_channel *chan, const char * type) {
-  int len;
-  int dev_prefix_len = strlen(fbsd_dev_prefix);
-
-
-  // No Autodetection if device type was specified by user
-  if (*type){
-    if(!strcmp(type,"ata")) return CONTROLLER_ATA;
-    if(!strcmp(type,"cciss")) return CONTROLLER_CCISS;
-    if(!strcmp(type,"scsi") || !strcmp(type,"sat")) goto handlescsi;
-    if(!strcmp(type,"3ware")){
-      return  parse_ata_chan_dev(dev_name,NULL,"");
-    }
-    if(!strcmp(type,"hpt")) return CONTROLLER_HPT;
-    return CONTROLLER_UNKNOWN;
-    // todo - add other types
-  }
-
-  // if dev_name null, or string length zero
-  if (!dev_name || !(len = strlen(dev_name)))
-    return CONTROLLER_UNKNOWN;
-
-  // Remove the leading /dev/... if it's there
-  if (!strncmp(fbsd_dev_prefix, dev_name, dev_prefix_len)) {
-    if (len <= dev_prefix_len) 
-      // if nothing else in the string, unrecognized
-    return CONTROLLER_UNKNOWN;
-    // else advance pointer to following characters
-    dev_name += dev_prefix_len;
-  }
-  // form /dev/ad* or ad*
-  if (!strncmp(fbsd_dev_ata_disk_prefix, dev_name,
-    strlen(fbsd_dev_ata_disk_prefix))) {
-#ifndef IOCATAREQUEST
-  if (chan != NULL) {
-    if (get_ata_channel_unit(dev_name,&(chan->channel),&(chan->device))<0) {
-      return CONTROLLER_UNKNOWN;
-    }
-  }
-#endif
-    return CONTROLLER_ATA;
-  }
-
-  // form /dev/pass* or pass*
-  if (!strncmp(fbsd_dev_scsi_pass, dev_name,
-    strlen(fbsd_dev_scsi_pass)))
-    goto handlescsi;
-
-  // form /dev/da* or da*
-  if (!strncmp(fbsd_dev_scsi_disk_plus, dev_name,
-               strlen(fbsd_dev_scsi_disk_plus)))
-    goto handlescsi;
-
-  // form /dev/sa* or sa*
-  if (!strncmp(fbsd_dev_scsi_tape1, dev_name,
-    strlen(fbsd_dev_scsi_tape1)))
-    goto handlescsi;
-
-  // form /dev/nsa* or nsa*
-  if (!strncmp(fbsd_dev_scsi_tape2, dev_name,
-    strlen(fbsd_dev_scsi_tape2)))
-    goto handlescsi;
-
-  // form /dev/esa* or esa*
-  if (!strncmp(fbsd_dev_scsi_tape3, dev_name,
-    strlen(fbsd_dev_scsi_tape3)))
-    goto handlescsi;
-
-  if (!strncmp(fbsd_dev_twa_ctrl,dev_name,
-    strlen(fbsd_dev_twa_ctrl))) 
-  {
-    if (chan != NULL) {
-      if (get_tw_channel_unit(dev_name,&(chan->channel),&(chan->device))<0) {
-        return CONTROLLER_UNKNOWN;
-      }
-    }
-    else if (get_tw_channel_unit(dev_name,NULL,NULL)<0) {
-      return CONTROLLER_UNKNOWN;
-    }
-    return CONTROLLER_3WARE_9000_CHAR;
-  }
-
-  if (!strncmp(fbsd_dev_twe_ctrl,dev_name,
-        strlen(fbsd_dev_twe_ctrl))) 
-  {
-    if (chan != NULL) {
-      if (get_tw_channel_unit(dev_name,&(chan->channel),&(chan->device))<0) {
-        return CONTROLLER_UNKNOWN;
-      }
-    }
-    else if (get_tw_channel_unit(dev_name,NULL,NULL)<0) {
-      return CONTROLLER_UNKNOWN;
-    }
-    return CONTROLLER_3WARE_678K_CHAR;
-  }
-
-  if (hpt_hba(dev_name)) {
-    return CONTROLLER_HPT;
-  }
-
-  // form /dev/ciss*
-  if (!strncmp(fbsd_dev_cciss, dev_name, strlen(fbsd_dev_cciss)))
-    return CONTROLLER_CCISS;
-
-  // we failed to recognize any of the forms
-  return CONTROLLER_UNKNOWN;
-
- handlescsi:
-  if (chan != NULL) {
-    if (!(chan->devname = (char *)calloc(1,DEV_IDLEN+1)))
-      return CONTROLLER_UNKNOWN;
-    if (cam_get_device(dev_name,chan->devname,DEV_IDLEN,&(chan->unitnum)) == -1)
-      return CONTROLLER_UNKNOWN;
-  }
-  return CONTROLLER_SCSI;
 
+int freebsd_ata_device::do_cmd( struct ata_ioc_request* request, bool is_48bit_cmd)
+{
+  int fd = get_fd();
+  ARGUSED(is_48bit_cmd); // no support for 48 bit commands in the IOCATAREQUEST
+  return ioctl(fd, IOCATAREQUEST, request);
 }
 
 
-bool freebsd_smart_device::open()
+
+bool freebsd_ata_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out)
 {
+  bool ata_48bit = false; // no ata_48bit_support via IOCATAREQUEST
+  if(!strcmp("atacam",get_dev_type())) // enable for atacam interface
+    ata_48bit = true;
+
+  if (!ata_cmd_is_ok(in,
+    true,  // data_out_support
+    true,  // multi_sector_support
+    ata_48bit) 
+    ) 
+    return false;
 
-  const char *dev = get_dev_name();
-  struct freebsd_dev_channel *fdchan;
-  int parse_ok, i;
+  struct ata_ioc_request request;
+  bzero(&request,sizeof(struct ata_ioc_request));
 
-  // Search table for a free entry
-  for (i=0; i<FREEBSD_MAXDEV; i++)
-    if (!devicetable[i])
-    break;
+  request.timeout=SCSI_TIMEOUT_DEFAULT;
+  request.u.ata.command=in.in_regs.command;
+  request.u.ata.feature=in.in_regs.features;
 
-  // If no free entry found, return error.  We have max allowed number
-  // of "file descriptors" already allocated.
-  if (i == FREEBSD_MAXDEV) {
-    errno = EMFILE;
-    return false;
-  }
+  request.u.ata.count = in.in_regs.sector_count_16;
+  request.u.ata.lba = in.in_regs.lba_48;
 
-  fdchan = (struct freebsd_dev_channel *)calloc(1,sizeof(struct freebsd_dev_channel));
-  if (fdchan == NULL) {
-    // errno already set by call to malloc()
-    return false;
+  switch (in.direction) {
+    case ata_cmd_in::no_data:  
+      request.flags=ATA_CMD_CONTROL;
+      break;
+    case ata_cmd_in::data_in:  
+      request.flags=ATA_CMD_READ | ATA_CMD_CONTROL;
+      request.data=(char *)in.buffer;
+      request.count=in.size;
+      break;
+    case ata_cmd_in::data_out: 
+      request.flags=ATA_CMD_WRITE | ATA_CMD_CONTROL;
+      request.data=(char *)in.buffer;
+      request.count=in.size;
+      break;
+    default:
+      return set_err(ENOSYS);
   }
 
-  parse_ok = parse_ata_chan_dev(dev,fdchan,get_req_type());
-
-  if (parse_ok == CONTROLLER_UNKNOWN) {
-    free(fdchan);
-    errno = ENOTTY;
-    return false; // can't handle what we don't know
-  }
+  clear_err();
+  errno = 0;
+  if (do_cmd(&request, in.in_regs.is_48bit_cmd()))
+      return set_err(errno);
+  if (request.error)
+      return set_err(EIO, "request failed, error code 0x%02x", request.error);
 
-  if (parse_ok == CONTROLLER_ATA) {
-#ifdef IOCATAREQUEST
-    if ((fdchan->device = ::open(dev,O_RDONLY))<0) {
-#else
-    if ((fdchan->atacommand = ::open("/dev/ata",O_RDWR))<0) {
-#endif
-      int myerror = errno; // preserve across free call
-      free(fdchan);
-      errno = myerror;
-      return false;
-    }
-  }
+  out.out_regs.error = request.error;
+  out.out_regs.sector_count_16 = request.u.ata.count;
+  out.out_regs.lba_48 = request.u.ata.lba;
 
-  if (parse_ok == CONTROLLER_3WARE_678K_CHAR) {
-    char buf[512];
-    sprintf(buf,"/dev/twe%d",fdchan->device);
-#ifdef IOCATAREQUEST
-    if ((fdchan->device = ::open(buf,O_RDWR))<0) {
-#else
-    if ((fdchan->atacommand = ::open(buf,O_RDWR))<0) {
-#endif
-      int myerror = errno; // preserve across free call
-      free(fdchan);
-      errno = myerror;
-      return false;
-    }
-  }
 
-  if (parse_ok == CONTROLLER_3WARE_9000_CHAR) {
-    char buf[512];
-    sprintf(buf,"/dev/twa%d",fdchan->device);
-#ifdef IOCATAREQUEST
-    if ((fdchan->device = ::open(buf,O_RDWR))<0) {
-#else
-    if ((fdchan->atacommand = ::open(buf,O_RDWR))<0) {
-#endif
-      int myerror = errno; // preserve across free call
-      free(fdchan);
-      errno = myerror;
-      return false;
-    }
-  }
+  // Command specific processing
+  if (in.in_regs.command == ATA_SMART_CMD
+       && in.in_regs.features == ATA_SMART_STATUS
+       && in.out_needed.lba_high)
+  {
+    unsigned const char normal_lo=0x4f, normal_hi=0xc2;
+    unsigned const char failed_lo=0xf4, failed_hi=0x2c;
 
-  if (parse_ok == CONTROLLER_HPT) {
-    if ((fdchan->device = ::open(dev,O_RDWR))<0) {
-      int myerror = errno; // preserve across free call
-      free(fdchan);
-      errno = myerror;
-      return false;
-    }
-  }
+    // Cyl low and Cyl high unchanged means "Good SMART status"
+    if (!(out.out_regs.lba_mid==normal_lo && out.out_regs.lba_high==normal_hi)
+    // These values mean "Bad SMART status"
+        && !(out.out_regs.lba_mid==failed_lo && out.out_regs.lba_high==failed_hi))
 
-  if (parse_ok == CONTROLLER_CCISS) {
-    if ((fdchan->device = ::open(dev,O_RDWR))<0) {
-      int myerror = errno; // preserve across free call
-      free(fdchan);
-      errno = myerror;
-      return false;
+    {
+      // We haven't gotten output that makes sense; print out some debugging info
+      char buf[512];
+      sprintf(buf,"CMD=0x%02x\nFR =0x%02x\nNS =0x%02x\nSC =0x%02x\nCL =0x%02x\nCH =0x%02x\nRETURN =0x%04x\n",
+        (int)request.u.ata.command,
+        (int)request.u.ata.feature,
+        (int)request.u.ata.count,
+        (int)((request.u.ata.lba) & 0xff),
+        (int)((request.u.ata.lba>>8) & 0xff),
+        (int)((request.u.ata.lba>>16) & 0xff),
+        (int)request.error);
+      printwarning(BAD_SMART,buf);
+      out.out_regs.lba_high = failed_hi; 
+      out.out_regs.lba_mid = failed_lo;
     }
   }
 
-  if (parse_ok == CONTROLLER_SCSI) {
-    // this is really a NO-OP, as the parse takes care
-    // of filling in correct details
-  }
-
-  // return pointer to "file descriptor" table entry, properly offset.
-  devicetable[i]=fdchan;
-  m_fd = i+FREEBSD_FDOFFSET;
-  // endofold
-  if (m_fd < 0) {
-    set_err((errno==ENOENT || errno==ENOTDIR) ? ENODEV : errno);
-    return false;
-  }
   return true;
 }
 
-bool freebsd_smart_device::close()
+#if FREEBSDVER > 800100
+class freebsd_atacam_device : public freebsd_ata_device
 {
-  int fd = m_fd; m_fd = -1;
-  struct freebsd_dev_channel *fdchan;
-  int failed = 0;
-
-  // check for valid file descriptor
-  if (isnotopen(&fd, &fdchan))
-    return false;
-
-  // did we allocate a SCSI device name?
-  if (fdchan->devname)
-    free(fdchan->devname);
+public:
+  freebsd_atacam_device(smart_interface * intf, const char * dev_name, const char * req_type)
+  : smart_device(intf, dev_name, "atacam", req_type), freebsd_ata_device(intf, dev_name, req_type)
+  {}
+  
+  virtual bool open();
+  virtual bool close();
+  
+protected:
+  int m_fd;
+  struct cam_device *m_camdev;
 
-  // close device, if open
-  if (fdchan->device)
-    failed=::close(fdchan->device);
-#ifndef IOCATAREQUEST
-  if (fdchan->atacommand)
-    failed=::close(fdchan->atacommand);
-#endif
+  virtual int do_cmd( struct ata_ioc_request* request , bool is_48bit_cmd);
+};
 
-  // if close succeeded, then remove from device list
-  // Eduard, should we also remove it from list if close() fails?  I'm
-  // not sure. Here I only remove it from list if close() worked.
-  if (!failed) {
-    free(fdchan);
-    devicetable[fd]=NULL;
+bool freebsd_atacam_device::open(){
+  const char *dev = get_dev_name();
+  
+  if ((m_camdev = cam_open_device(dev, O_RDWR)) == NULL) {
+    set_err(errno);
+    return false;
   }
-  if(failed) return false;
-  else return true;
+  set_fd(m_camdev->fd);
+  return true;
 }
 
-/////////////////////////////////////////////////////////////////////////////
-/// Implement standard ATA support with old functions
-
-class freebsd_ata_device
-: public /*implements*/ ata_device_with_command_set,
-  public /*extends*/ freebsd_smart_device
-{
-public:
-  freebsd_ata_device(smart_interface * intf, const char * dev_name, const char * req_type);
-
-#ifdef HAVE_ATA_IDENTIFY_IS_CACHED
-  virtual bool ata_identify_is_cached() const;
-#endif
-
-protected:
-  virtual int ata_command_interface(smart_command_set command, int select, char * data);
-};
-
-freebsd_ata_device::freebsd_ata_device(smart_interface * intf, const char * dev_name, const char * req_type)
-: smart_device(intf, dev_name, "ata", req_type),
-  freebsd_smart_device("ATA")
-{
+bool freebsd_atacam_device::close(){
+  cam_close_device(m_camdev);
+  set_fd(-1);
+  return true;
 }
 
-int freebsd_ata_device::ata_command_interface(smart_command_set command, int select, char * data)
+int freebsd_atacam_device::do_cmd( struct ata_ioc_request* request, bool is_48bit_cmd)
 {
- int fd=get_fd();
-#if !defined(ATAREQUEST) && !defined(IOCATAREQUEST)
- // sorry, but without ATAng, we can't do anything here
- printwarning(BAD_KERNEL,NULL);
- errno = ENOSYS;
- return -1;
-#else
- struct freebsd_dev_channel* con;
- int retval, copydata=0;
-#ifdef IOCATAREQUEST
- struct ata_ioc_request request;
-#else
- struct ata_cmd iocmd;
-#endif
- unsigned char buff[512];
-
- // check that "file descriptor" is valid
- if (isnotopen(&fd,&con))
-  return -1;
+  union ccb ccb;
+  int camflags;
 
bzero(buff,512);
 memset(&ccb, 0, sizeof(ccb));
 
-#ifdef IOCATAREQUEST
- bzero(&request,sizeof(struct ata_ioc_request));
-#else
- bzero(&iocmd,sizeof(struct ata_cmd));
-#endif
- bzero(buff,512);
+  if (request->count == 0)
+    camflags = CAM_DIR_NONE;
+  else if (request->flags & ATA_CMD_READ)
+    camflags = CAM_DIR_IN;
+  else
+    camflags = CAM_DIR_OUT;
+  if(is_48bit_cmd)
+    camflags |= CAM_ATAIO_48BIT;
+
+  cam_fill_ataio(&ccb.ataio,
+                 0,
+                 NULL,
+                 camflags,
+                 MSG_SIMPLE_Q_TAG,
+                 (u_int8_t*)request->data,
+                 request->count,
+                 request->timeout * 1000); // timeout in seconds
+
+  ccb.ataio.cmd.flags = CAM_ATAIO_NEEDRESULT;
+  // ata_28bit_cmd
+  ccb.ataio.cmd.command = request->u.ata.command;
+  ccb.ataio.cmd.features = request->u.ata.feature;
+  ccb.ataio.cmd.lba_low = request->u.ata.lba;
+  ccb.ataio.cmd.lba_mid = request->u.ata.lba >> 8;
+  ccb.ataio.cmd.lba_high = request->u.ata.lba >> 16;
+  // ata_48bit cmd
+  ccb.ataio.cmd.lba_low_exp = request->u.ata.lba >> 24;
+  ccb.ataio.cmd.lba_mid_exp = request->u.ata.lba >> 32;
+  ccb.ataio.cmd.lba_high_exp = request->u.ata.lba >> 40;
+  ccb.ataio.cmd.device = 0x40 | ((request->u.ata.lba >> 24) & 0x0f);
+  ccb.ataio.cmd.sector_count = request->u.ata.count;
+  ccb.ataio.cmd.sector_count_exp = request->u.ata.count  >> 8;;
+
+  ccb.ccb_h.flags |= CAM_DEV_QFRZDIS;
+
+  if (cam_send_ccb(m_camdev, &ccb) < 0) {
+    err(1, "cam_send_ccb");
+    return -1;
+  }
 
-#ifndef IOCATAREQUEST
- iocmd.cmd=ATAREQUEST;
- iocmd.channel=con->channel;
- iocmd.device=con->device;
-#define request iocmd.u.request
-#endif
+  if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
+    cam_error_print(m_camdev, &ccb, CAM_ESF_ALL, CAM_EPF_ALL, stderr);
+    return -1;
+  }
 
- request.u.ata.command=ATA_SMART_CMD;
- request.timeout=600;
- switch (command){
- case READ_VALUES:
-  request.u.ata.feature=ATA_SMART_READ_VALUES;
-  request.u.ata.lba=0xc24f<<8;
-  request.flags=ATA_CMD_READ;
-  request.data=(char *)buff;
-  request.count=512;
-  copydata=1;
-  break;
- case READ_THRESHOLDS:
-  request.u.ata.feature=ATA_SMART_READ_THRESHOLDS;
-  request.u.ata.count=1;
-  request.u.ata.lba=1|(0xc24f<<8);
-  request.flags=ATA_CMD_READ;
-  request.data=(char *)buff;
-  request.count=512;
-  copydata=1;
-  break;
- case READ_LOG:
-  request.u.ata.feature=ATA_SMART_READ_LOG_SECTOR;
-  request.u.ata.lba=select|(0xc24f<<8);
-  request.u.ata.count=1;
-  request.flags=ATA_CMD_READ;
-  request.data=(char *)buff;
-  request.count=512;
-  copydata=1;
-  break;
- case IDENTIFY:
-  request.u.ata.command=ATA_IDENTIFY_DEVICE;
-  request.flags=ATA_CMD_READ;
-  request.data=(char *)buff;
-  request.count=512;
-  copydata=1;
-  break;
- case PIDENTIFY:
-  request.u.ata.command=ATA_IDENTIFY_PACKET_DEVICE;
-  request.flags=ATA_CMD_READ;
-  request.data=(char *)buff;
-  request.count=512;
-  copydata=1;
-  break;
- case ENABLE:
-  request.u.ata.feature=ATA_SMART_ENABLE;
-  request.u.ata.lba=0xc24f<<8;
-  request.flags=ATA_CMD_CONTROL;
-  break;
- case DISABLE:
-  request.u.ata.feature=ATA_SMART_DISABLE;
-  request.u.ata.lba=0xc24f<<8;
-  request.flags=ATA_CMD_CONTROL;
-  break;
- case AUTO_OFFLINE:
-  // NOTE: According to ATAPI 4 and UP, this command is obsolete
-  request.u.ata.feature=ATA_SMART_AUTO_OFFLINE;
-  request.u.ata.lba=0xc24f<<8;                                                                                                                                         
-  request.u.ata.count=select;                                                                                                                                          
-  request.flags=ATA_CMD_CONTROL;
-  break;
- case AUTOSAVE:
-  request.u.ata.feature=ATA_SMART_AUTOSAVE;
-  request.u.ata.lba=0xc24f<<8;
-  request.u.ata.count=select;
-  request.flags=ATA_CMD_CONTROL;
-  break;
- case IMMEDIATE_OFFLINE:
-  request.u.ata.feature=ATA_SMART_IMMEDIATE_OFFLINE;
-  request.u.ata.lba = select|(0xc24f<<8); // put test in sector
-  request.flags=ATA_CMD_CONTROL;
-  break;
- case STATUS_CHECK: // same command, no HDIO in FreeBSD
- case STATUS:
-  // this command only says if SMART is working.  It could be
-  // replaced with STATUS_CHECK below.
-  request.u.ata.feature=ATA_SMART_STATUS;
-  request.u.ata.lba=0xc24f<<8;
-  request.flags=ATA_CMD_CONTROL;
-  break;
- case CHECK_POWER_MODE:
-  request.u.ata.command=ATA_CHECK_POWER_MODE;
-  request.u.ata.feature=0;
-  request.flags=ATA_CMD_CONTROL;
-  break;
- case WRITE_LOG:
-  memcpy(buff, data, 512);
-  request.u.ata.feature=ATA_SMART_WRITE_LOG_SECTOR;
-  request.u.ata.lba=select|(0xc24f<<8);
-  request.u.ata.count=1;
-  request.flags=ATA_CMD_WRITE;
-  request.data=(char *)buff;
-  request.count=512;
-  break;
- default:
-  pout("Unrecognized command %d in ata_command_interface()\n"
-   "Please contact " PACKAGE_BUGREPORT "\n", command);
-  errno=ENOSYS;
-  return -1;
- }
-
- if (command==STATUS_CHECK){
-  unsigned const char normal_lo=0x4f, normal_hi=0xc2;
-  unsigned const char failed_lo=0xf4, failed_hi=0x2c;
-  unsigned char low,high;
-
-#ifdef IOCATAREQUEST
-  if ((retval=ioctl(con->device, IOCATAREQUEST, &request)) || request.error)
-#else
-  if ((retval=ioctl(con->atacommand, IOCATA, &iocmd)) || request.error)
-#endif
-  return -1;
+  request->u.ata.lba =
+    ((u_int64_t)(ccb.ataio.res.lba_low)) |
+    ((u_int64_t)(ccb.ataio.res.lba_mid) << 8) |
+    ((u_int64_t)(ccb.ataio.res.lba_high) << 16) |
+    ((u_int64_t)(ccb.ataio.res.lba_low_exp) << 24) |
+    ((u_int64_t)(ccb.ataio.res.lba_mid_exp) << 32) |
+    ((u_int64_t)(ccb.ataio.res.lba_high_exp) << 40);
 
-#if (FREEBSDVER < 502000)
-  printwarning(NO_RETURN,NULL);
-#endif
+  request->u.ata.count = ccb.ataio.res.sector_count | (ccb.ataio.res.sector_count_exp << 8);
+  request->error = ccb.ataio.res.error;
 
-  high = (request.u.ata.lba >> 16) & 0xff;
-  low = (request.u.ata.lba >> 8) & 0xff;
-
-  // Cyl low and Cyl high unchanged means "Good SMART status"
-  if (low==normal_lo && high==normal_hi)
-   return 0;
-
-  // These values mean "Bad SMART status"
-  if (low==failed_lo && high==failed_hi)
-   return 1;
-
-  // We haven't gotten output that makes sense; print out some debugging info
-  char buf[512];
-  sprintf(buf,"CMD=0x%02x\nFR =0x%02x\nNS =0x%02x\nSC =0x%02x\nCL =0x%02x\nCH =0x%02x\nRETURN =0x%04x\n",
-   (int)request.u.ata.command,
-   (int)request.u.ata.feature,
-   (int)request.u.ata.count,
-   (int)((request.u.ata.lba) & 0xff),
-   (int)((request.u.ata.lba>>8) & 0xff),
-   (int)((request.u.ata.lba>>16) & 0xff),
-   (int)request.error);
-  printwarning(BAD_SMART,buf);
-  return 0;   
- }
-
-#ifdef IOCATAREQUEST
- if ((retval=ioctl(con->device, IOCATAREQUEST, &request)) || request.error)
-#else
- if ((retval=ioctl(con->atacommand, IOCATA, &iocmd)) || request.error)
-#endif
- {
-  return -1;
- }
- // 
- if (command == CHECK_POWER_MODE) {
-  data[0] = request.u.ata.count & 0xff;
   return 0;
- }
- if (copydata)
-  memcpy(data, buff, 512);
-
- return 0;
-#endif
 }
 
-#ifdef HAVE_ATA_IDENTIFY_IS_CACHED
-bool freebsd_ata_device::ata_identify_is_cached() const
-{
-  return !!::ata_identify_is_cached(get_fd());
-}
 #endif
 
-
 /////////////////////////////////////////////////////////////////////////////
 /// Implement AMCC/3ware RAID support with old functions
 
@@ -830,6 +461,7 @@ public:
 
 protected:
   virtual int ata_command_interface(smart_command_set command, int select, char * data);
+  virtual bool open();
 
 private:
   int m_escalade_type; ///< Type string for escalade_command_interface().
@@ -848,11 +480,23 @@ freebsd_escalade_device::freebsd_escalade_device(smart_interface * intf, const c
   set_info().info_name = strprintf("%s [3ware_disk_%02d]", dev_name, disknum);
 }
 
+bool freebsd_escalade_device::open()
+{
+  const char *dev = get_dev_name();
+  int fd;
+  
+  if ((fd = ::open(dev,O_RDWR))<0) {
+    set_err(errno);
+    return false;
+  }
+  set_fd(fd);
+  return true;
+}
+
 int freebsd_escalade_device::ata_command_interface(smart_command_set command, int select, char * data)
 {
   // to hold true file descriptor
   int fd = get_fd();
-  struct freebsd_dev_channel* con;
 
   // return value and buffer for ioctl()
   int  ioctlreturn, readdata=0;
@@ -868,10 +512,6 @@ int freebsd_escalade_device::ata_command_interface(smart_command_set command, in
     return -1;
   }
 
-  // check that "file descriptor" is valid
-  if (isnotopen(&fd,&con))
-    return -1;
-
   memset(ioctl_buffer, 0, TW_IOCTL_BUFFER_SIZE);
 
   if (m_escalade_type==CONTROLLER_3WARE_9000_CHAR) {
@@ -1022,17 +662,9 @@ int freebsd_escalade_device::ata_command_interface(smart_command_set command, in
 
   // Now send the command down through an ioctl()
   if (m_escalade_type==CONTROLLER_3WARE_9000_CHAR) {
-#ifdef IOCATAREQUEST
-    ioctlreturn=ioctl(con->device,TW_OSL_IOCTL_FIRMWARE_PASS_THROUGH,cmd_twa);
-#else
-    ioctlreturn=ioctl(con->atacommand,TW_OSL_IOCTL_FIRMWARE_PASS_THROUGH,cmd_twa);
-#endif
+    ioctlreturn=ioctl(fd,TW_OSL_IOCTL_FIRMWARE_PASS_THROUGH,cmd_twa);
   } else {
-#ifdef IOCATAREQUEST
-    ioctlreturn=ioctl(con->device,TWEIO_COMMAND,cmd_twe);
-#else
-    ioctlreturn=ioctl(con->atacommand,TWEIO_COMMAND,cmd_twe);
-#endif
+    ioctlreturn=ioctl(fd,TWEIO_COMMAND,cmd_twe);
   }
 
   // Deal with the different error cases
@@ -1093,7 +725,7 @@ int freebsd_escalade_device::ata_command_interface(smart_command_set command, in
     *data=*(char *)&(ata->sector_count);
 
   // look for nonexistent devices/ports
-  if (command==IDENTIFY && !nonempty((unsigned char *)data, 512)) {
+  if (command==IDENTIFY && !nonempty(data, 512)) {
     errno=ENODEV;
     return -1;
   }
@@ -1115,6 +747,7 @@ public:
 
 protected:
   virtual int ata_command_interface(smart_command_set command, int select, char * data);
+  virtual bool open();
 
 private:
   unsigned char m_hpt_data[3]; ///< controller/channel/port
@@ -1130,20 +763,28 @@ freebsd_highpoint_device::freebsd_highpoint_device(smart_interface * intf, const
   set_info().info_name = strprintf("%s [hpt_disk_%u/%u/%u]", dev_name, m_hpt_data[0], m_hpt_data[1], m_hpt_data[2]);
 }
 
+bool freebsd_highpoint_device::open()
+{
+  const char *dev = get_dev_name();
+  int fd;
+  
+  if ((fd = ::open(dev,O_RDWR))<0) {
+    set_err(errno);
+    return false;
+  }
+  set_fd(fd);
+  return true;
+}
+
 int freebsd_highpoint_device::ata_command_interface(smart_command_set command, int select, char * data)
 {
   int fd=get_fd(); 
   int ids[2];
-  struct freebsd_dev_channel* fbcon;
   HPT_IOCTL_PARAM param;
   HPT_CHANNEL_INFO_V2 info;
   unsigned char* buff[512 + 2 * sizeof(HPT_PASS_THROUGH_HEADER)];
   PHPT_PASS_THROUGH_HEADER pide_pt_hdr, pide_pt_hdr_out;
 
-  // check that "file descriptor" is valid
-  if (isnotopen(&fd, &fbcon))
-    return -1;
-
   // get internal deviceid
   ids[0] = m_hpt_data[0] - 1;
   ids[1] = m_hpt_data[1] - 1;
@@ -1161,7 +802,7 @@ int freebsd_highpoint_device::ata_command_interface(smart_command_set command, i
     param.ctrl_code = HPT_IOCTL_GET_CHANNEL_INFO;
     param.out_size = sizeof(HPT_CHANNEL_INFO);
   }
-  if (ioctl(fbcon->device, HPT_DO_IOCONTROL, &param)!=0 ||
+  if (ioctl(fd, HPT_DO_IOCONTROL, &param)!=0 ||
       info.devices[m_hpt_data[2]-1]==0) {
     return -1;
   }
@@ -1246,7 +887,7 @@ int freebsd_highpoint_device::ata_command_interface(smart_command_set command, i
 
   pide_pt_hdr_out = (PHPT_PASS_THROUGH_HEADER)param.out;
 
-  if ((ioctl(fbcon->device, HPT_DO_IOCONTROL, &param)!=0) ||
+  if ((ioctl(fd, HPT_DO_IOCONTROL, &param)!=0) ||
       (pide_pt_hdr_out->command & 1)) {
     return -1;
   }
@@ -1290,7 +931,7 @@ int freebsd_highpoint_device::ata_command_interface(smart_command_set command, i
 
 
 /////////////////////////////////////////////////////////////////////////////
-/// Implement standard SCSI support with old functions
+/// Standard SCSI support
 
 class freebsd_scsi_device
 : public /*implements*/ scsi_device,
@@ -1302,8 +943,33 @@ public:
   virtual smart_device * autodetect_open();
 
   virtual bool scsi_pass_through(scsi_cmnd_io * iop);
+  
+  virtual bool open();
+
+  virtual bool close();
+  
+private:
+  int m_fd;
+  struct cam_device *m_camdev;
 };
 
+bool freebsd_scsi_device::open(){
+  const char *dev = get_dev_name();
+  
+  if ((m_camdev = cam_open_device(dev, O_RDWR)) == NULL) {
+    set_err(errno);
+    return false;
+  }
+  set_fd(m_camdev->fd);
+  return true;
+}
+
+bool freebsd_scsi_device::close(){
+  cam_close_device(m_camdev);
+  set_fd(-1);
+  return true;
+}
+
 freebsd_scsi_device::freebsd_scsi_device(smart_interface * intf,
   const char * dev_name, const char * req_type)
 : smart_device(intf, dev_name, "scsi", req_type),
@@ -1311,11 +977,10 @@ freebsd_scsi_device::freebsd_scsi_device(smart_interface * intf,
 {
 }
 
-// Interface to SCSI devices.  See os_linux.c
-int do_normal_scsi_cmnd_io(int fd, struct scsi_cmnd_io * iop, int report)
+
+bool freebsd_scsi_device::scsi_pass_through(scsi_cmnd_io * iop)
 {
-  struct freebsd_dev_channel* con = NULL;
-  struct cam_device* cam_dev = NULL;
+  int report=scsi_debugmode;
   union ccb *ccb;
 
   if (report > 0) {
@@ -1339,20 +1004,29 @@ int do_normal_scsi_cmnd_io(int fd, struct scsi_cmnd_io * iop, int report)
         pout("]");
   }
 
-  // check that "file descriptor" is valid
-  if (isnotopen(&fd,&con))
+  if(m_camdev==NULL) {
+    warnx("error: camdev=0!");
     return -ENOTTY;
-
-
-  if (!(cam_dev = cam_open_spec_device(con->devname,con->unitnum,O_RDWR,NULL))) {
-    warnx("%s",cam_errbuf);
-    return -EIO;
   }
 
-  if (!(ccb = cam_getccb(cam_dev))) {
+  if (!(ccb = cam_getccb(m_camdev))) {
     warnx("error allocating ccb");
     return -ENOMEM;
   }
+  // mfi SAT layer is known to be buggy
+  if(!strcmp("mfi",m_camdev->sim_name)) {
+    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 && 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 && iop->cmnd[9] == ATA_SMART_CMD &&
+        iop->cmnd[3] == ATA_SMART_WRITE_LOG_SECTOR)) 
+      return set_err(ENOSYS, "SMART WRITE LOG SECTOR command is not supported by controller firmware"); 
+  }
 
   // clear out structure, except for header that was filled in for us
   bzero(&(&ccb->ccb_h)[1],
@@ -1370,35 +1044,28 @@ int do_normal_scsi_cmnd_io(int fd, struct scsi_cmnd_io * iop, int report)
     /* timout (converted to seconds) */ iop->timeout*1000);
   memcpy(ccb->csio.cdb_io.cdb_bytes,iop->cmnd,iop->cmnd_len);
 
-  if (cam_send_ccb(cam_dev,ccb) < 0) {
+  if (cam_send_ccb(m_camdev,ccb) < 0) {
     warn("error sending SCSI ccb");
-#if (FREEBSDVER > 500000)
-    cam_error_print(cam_dev,ccb,CAM_ESF_ALL,CAM_EPF_ALL,stderr);
-#endif
+    cam_error_print(m_camdev,ccb,CAM_ESF_ALL,CAM_EPF_ALL,stderr);
     cam_freeccb(ccb);
     return -EIO;
   }
 
   if (((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) && ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_SCSI_STATUS_ERROR)) {
-#if (FREEBSDVER > 500000)
-    cam_error_print(cam_dev,ccb,CAM_ESF_ALL,CAM_EPF_ALL,stderr);
-#endif
+    cam_error_print(m_camdev,ccb,CAM_ESF_ALL,CAM_EPF_ALL,stderr);
     cam_freeccb(ccb);
     return -EIO;
   }
 
   if (iop->sensep) {
-    memcpy(iop->sensep,&(ccb->csio.sense_data),sizeof(struct scsi_sense_data));
-    iop->resp_sense_len = sizeof(struct scsi_sense_data);
+    iop->resp_sense_len = ccb->csio.sense_len - ccb->csio.sense_resid;
+    memcpy(iop->sensep,&(ccb->csio.sense_data),iop->resp_sense_len);
   }
 
   iop->scsi_status = ccb->csio.scsi_status;
 
   cam_freeccb(ccb);
 
-  if (cam_dev)
-    cam_close_device(cam_dev);
-
   if (report > 0) {
     int trunc;
 
@@ -1409,59 +1076,440 @@ int do_normal_scsi_cmnd_io(int fd, struct scsi_cmnd_io * iop, int report)
       (trunc ? " [only first 256 bytes shown]" : ""));
     dStrHex(iop->dxferp, (trunc ? 256 : iop->dxfer_len) , 1);
   }
-  return 0;
+
+  return true;
 }
 
 
-/* Check and call the right interface. Maybe when the do_generic_scsi_cmd_io interface is better
-   we can take off this crude way of calling the right interface */
-int do_scsi_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
+/////////////////////////////////////////////////////////////////////////////
+/// Areca RAID support
+
+class freebsd_areca_device
+: public /*implements*/ ata_device,
+  public /*extends*/ freebsd_smart_device
 {
-  struct freebsd_dev_channel *fdchan;
-  switch(m_controller_type)
-  {
-  case CONTROLLER_CCISS:
-#ifdef HAVE_DEV_CISS_CISSIO_H
-    // check that "file descriptor" is valid
-    if (isnotopen(&dev_fd,&fdchan))
-      return -ENOTTY;
+public:
+  freebsd_areca_device(smart_interface * intf, const char * dev_name, int disknum);
 
-    return cciss_io_interface(fdchan->device, m_controller_port-1, iop, report);
-#else
-    {
-      static int warned = 0;
-      if (!warned) {
-        pout("CCISS support is not available in this build of smartmontools,\n"
-          "/usr/src/sys/dev/ciss/cissio.h was not available at build time.\n\n");
-        warned = 1;
-      }
-    }
-    return -ENOSYS;
-#endif
-// not reached
-    break;
+protected:
+  virtual bool ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out); 
 
-  default:
-    return do_normal_scsi_cmnd_io(dev_fd, iop, report);
-    // not reached
-    break;
-  }
+private:
+  int m_disknum; ///< Disk number.
+};
+
+
+// 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"
+
+
+/*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           _IOWR('F', FUNCTION_READ_RQBUFFER, sSRB_BUFFER)
+#define ARCMSR_IOCTL_WRITE_WQBUFFER          _IOWR('F', FUNCTION_WRITE_WQBUFFER, sSRB_BUFFER)
+#define ARCMSR_IOCTL_CLEAR_RQBUFFER          _IOWR('F', FUNCTION_CLEAR_RQBUFFER, sSRB_BUFFER)
+#define ARCMSR_IOCTL_CLEAR_WQBUFFER          _IOWR('F', FUNCTION_CLEAR_WQBUFFER, sSRB_BUFFER)
+#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
+{
+       sSRB_IO_CONTROL srbioctl;
+       unsigned char   ioctldatabuffer[1032]; // the buffer to put the command data to/from firmware
+} sSRB_BUFFER;
+
+
+// For debugging areca code
+
+static void areca_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");
 }
 
-bool freebsd_scsi_device::scsi_pass_through(scsi_cmnd_io * iop)
+
+static int arcmsr_command_handler(int fd, unsigned long arcmsr_cmd, unsigned char *data, int data_len, void *ext_data /* reserved for further use */)
 {
-  unsigned char oldtype = m_controller_type, oldport = m_controller_port;
-  m_controller_type = CONTROLLER_SCSI; m_controller_port = 0;
-  int status = do_scsi_cmnd_io(get_fd(), iop, con->reportscsiioctl);
-  m_controller_type = oldtype; m_controller_port = oldport;
-  if (status < 0) {
-    set_err(-status);
-    return false;
-  }
-  return true;
+       ARGUSED(ext_data);
+
+       int ioctlreturn = 0;
+       sSRB_BUFFER sBuf;
+
+       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));
+
+
+       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:
+               break;
+               // command for reading data from driver
+       case ARCMSR_IOCTL_READ_RQBUFFER:    
+               break;
+       default:
+               // unknown arcmsr commands
+               return -1;
+       }
+
+
+       while ( 1 )
+       {
+               ioctlreturn = ioctl(fd,arcmsr_cmd,&sBuf);
+               if ( ioctlreturn  )
+               {
+                       // 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 )
+               {
+                       if(ata_debugmode)
+                           areca_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;
+                       }
+               }
+       }
+
+       // Deal with the different error cases
+       if ( ioctlreturn )
+       {
+               pout("ioctl write buffer failed code = %x\n", ioctlreturn);
+               return -2;
+       }
+
+
+       if ( data )
+       {
+               memcpy(data, return_buff, total);
+       }
+
+       return total;
+}
+
+
+freebsd_areca_device::freebsd_areca_device(smart_interface * intf, const char * dev_name, int disknum)
+: smart_device(intf, dev_name, "areca", "areca"),
+  freebsd_smart_device("ATA"),
+  m_disknum(disknum)
+{
+  set_info().info_name = strprintf("%s [areca_%02d]", dev_name, disknum);
+}
+
+// Areca RAID Controller
+// int freebsd_areca_device::ata_command_interface(smart_command_set command, int select, char * data)
+bool freebsd_areca_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out) 
+{
+if (!ata_cmd_is_ok(in, 
+    true, // data_out_support 
+    false, // TODO: multi_sector_support 
+    true) // ata_48bit_support 
+    )
+    return false; 
+
+       // 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
+       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];
+
+       // Set registers
+        {
+           const ata_in_regs_48bit & r = in.in_regs;
+           ata_cmd->features     = r.features_16;
+           ata_cmd->sector_count  = r.sector_count_16;
+           ata_cmd->sector_number = r.lba_low_16;
+           ata_cmd->cylinder_low  = r.lba_mid_16;
+           ata_cmd->cylinder_high = r.lba_high_16;
+           ata_cmd->device_head   = r.device;
+           ata_cmd->command      = r.command;
+       }
+       bool readdata = false; 
+       if (in.direction == ata_cmd_in::data_in) { 
+           readdata = true;
+           // the command will read data
+           areca_packet[6] = 0x13;
+       }
+       else if ( in.direction == ata_cmd_in::no_data )
+       {
+               // the commands will return no data
+               areca_packet[6] = 0x15;
+       }
+       else if (in.direction == ata_cmd_in::data_out) 
+       {
+               // the commands will write data
+               memcpy(ata_cmd->data, in.buffer, in.size);
+               areca_packet[6] = 0x14;
+       }
+       else {
+           // COMMAND NOT SUPPORTED VIA ARECA IOCTL INTERFACE
+           return set_err(ENOTSUP, "DATA OUT not supported for this Areca controller type");
+       }
+
+       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) {
+           return set_err(EIO);
+       }
+
+       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]; 
+       }
+
+       if ( return_buff[expected - 1] != cs )
+       {
+               return set_err(EIO);
+       }
+
+       sATA_OUTPUT_REGISTERS *ata_out = (sATA_OUTPUT_REGISTERS *)&return_buff[5] ;
+       if ( ata_out->status )
+       {
+               if ( in.in_regs.command == ATA_IDENTIFY_DEVICE
+                && !nonempty((unsigned char *)in.buffer, in.size)) 
+                {
+                   return set_err(ENODEV, "No drive on port %d", m_disknum);
+                } 
+       }
+
+       // returns with data
+       if (readdata)
+       {
+               memcpy(in.buffer, &return_buff[7], in.size); 
+       }
+
+       // Return register values
+       {
+           ata_out_regs_48bit & r = out.out_regs;
+           r.error           = ata_out->error;
+           r.sector_count_16 = ata_out->sector_count;
+           r.lba_low_16      = ata_out->sector_number;
+           r.lba_mid_16      = ata_out->cylinder_low;
+           r.lba_high_16     = ata_out->cylinder_high;
+           r.status          = ata_out->status;
+       }
+       return true;
 }
 
 
+
 /////////////////////////////////////////////////////////////////////////////
 /// Implement CCISS RAID support with old functions
 
@@ -1473,11 +1521,23 @@ public:
   freebsd_cciss_device(smart_interface * intf, const char * name, unsigned char disknum);
 
   virtual bool scsi_pass_through(scsi_cmnd_io * iop);
+  virtual bool open();
 
 private:
   unsigned char m_disknum; ///< Disk number.
 };
 
+bool freebsd_cciss_device::open()
+{
+  const char *dev = get_dev_name();
+  int fd;
+  if ((fd = ::open(dev,O_RDWR))<0) {
+    set_err(errno);
+    return false;
+  }
+  set_fd(fd);
+  return true;
+}
 
 freebsd_cciss_device::freebsd_cciss_device(smart_interface * intf,
   const char * dev_name, unsigned char disknum)
@@ -1490,15 +1550,11 @@ freebsd_cciss_device::freebsd_cciss_device(smart_interface * intf,
 
 bool freebsd_cciss_device::scsi_pass_through(scsi_cmnd_io * iop)
 {
-  // See os_linux.cpp
-  unsigned char oldtype = m_controller_type, oldport = m_controller_port;
-  m_controller_type = CONTROLLER_CCISS; m_controller_port = m_disknum+1;
-  int status = do_scsi_cmnd_io(get_fd(), iop, con->reportscsiioctl);
-  m_controller_type = oldtype; m_controller_port = oldport;
-  if (status < 0) {
-      set_err(-status);
-      return false;
-  }
+  int status = cciss_io_interface(get_fd(), m_disknum, iop, scsi_debugmode);
+  if (status < 0)
+      return set_err(-status);
+  return true;
+  // not reached
   return true;
 }
 
@@ -1539,26 +1595,27 @@ smart_device * freebsd_scsi_device::autodetect_open()
     return this;
 
   // Use INQUIRY to detect type
-  smart_device * newdev = 0;
-  try {
-    // 3ware ?
-    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());
-      return this;
-    }
 
-    // SAT or USB ?
-    newdev = smi()->autodetect_sat_device(this, req_buff, len);
-    if (newdev)
+  // 3ware ?
+  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());
+    return this;
+  }
+
+  // SAT or USB, skip MFI controllers because of bugs
+  {
+    smart_device * newdev = smi()->autodetect_sat_device(this, req_buff, len);
+    if (newdev) {
       // NOTE: 'this' is now owned by '*newdev'
+      if(!strcmp("mfi",m_camdev->sim_name)) {
+        newdev->close();
+        newdev->set_err(ENOSYS, "SATA device detected,\n"
+          "MegaRAID SAT layer is reportedly buggy, use '-d sat' to try anyhow");
+      }
       return newdev;
-  }
-  catch (...) {
-    // Cleanup if exception occurs after newdev was allocated
-    delete newdev;
-    throw;
+    }
   }
 
   // Nothing special found
@@ -1583,6 +1640,10 @@ public:
 protected:
   virtual ata_device * get_ata_device(const char * name, const char * type);
 
+#if FREEBSDVER > 800100
+  virtual ata_device * get_atacam_device(const char * name, const char * type);
+#endif
+
   virtual scsi_device * get_scsi_device(const char * name, const char * type);
 
   virtual smart_device * autodetect_smart_device(const char * name);
@@ -1614,153 +1675,45 @@ ata_device * freebsd_smart_interface::get_ata_device(const char * name, const ch
   return new freebsd_ata_device(this, name, type);
 }
 
-scsi_device * freebsd_smart_interface::get_scsi_device(const char * name, const char * type)
+#if FREEBSDVER > 800100
+ata_device * freebsd_smart_interface::get_atacam_device(const char * name, const char * type)
 {
-  return new freebsd_scsi_device(this, name, type);
+  return new freebsd_atacam_device(this, name, type);
 }
+#endif
 
-static int 
-cam_getumassno(char * devname) {
-  union ccb ccb;
-  int bufsize, fd;
-  unsigned int i;
-  int error = -1;
-  char devstring[256];
-
-  if ((fd = open(XPT_DEVICE, O_RDWR)) == -1) {
-    warn("couldn't open %s", XPT_DEVICE);
-    return(1);
-  }
-  bzero(&ccb, sizeof(union ccb));
-
-  ccb.ccb_h.path_id = CAM_XPT_PATH_ID;
-  ccb.ccb_h.target_id = CAM_TARGET_WILDCARD;
-  ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;
-  ccb.ccb_h.func_code = XPT_DEV_MATCH;
-  bufsize = sizeof(struct dev_match_result) * 100;
-  ccb.cdm.match_buf_len = bufsize;
-  ccb.cdm.matches = (struct dev_match_result *)malloc(bufsize);
-
-  if (ccb.cdm.matches == NULL) {
-    warnx("can't malloc memory for matches");
-    close(fd);
-    return(1);
-  }
-  ccb.cdm.num_matches = 0;
-  /*
-  * We fetch all nodes, since we display most of them in the default
-  * case, and all in the verbose case.
-  */
-  ccb.cdm.num_patterns = 0;
-  ccb.cdm.pattern_buf_len = 0;
-  /*
-  * We do the ioctl multiple times if necessary, in case there are
-  * more than 100 nodes in the EDT.
-  */
-
-  do {
-    if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
-      warn("error sending CAMIOCOMMAND ioctl");
-      error = -1;
-      break;
-    }
-    if ((ccb.ccb_h.status != CAM_REQ_CMP)
-      || ((ccb.cdm.status != CAM_DEV_MATCH_LAST)
-        && (ccb.cdm.status != CAM_DEV_MATCH_MORE))) 
-    {
-      warnx("got CAM error %#x, CDM error %d\n",
-        ccb.ccb_h.status, ccb.cdm.status);
-      error = -1;
-      break;
-    }
-
-    struct bus_match_result *bus_result = 0;
-    for (i = 0; i < ccb.cdm.num_matches; i++) {
-      switch (ccb.cdm.matches[i].type) {
-      case DEV_MATCH_BUS: {
-          // struct bus_match_result *bus_result;
-          bus_result =
-          &ccb.cdm.matches[i].result.bus_result;
-          break;
-      }
-    case DEV_MATCH_DEVICE:   {
-        /* we are not interested in device name */
-        break;
-      }
-    case DEV_MATCH_PERIPH: {
-        struct periph_match_result *periph_result;
-
-        periph_result =
-        &ccb.cdm.matches[i].result.periph_result;
-
-        snprintf(devstring,sizeof(devstring),"%s%d",periph_result->periph_name,periph_result->unit_number);
-        if(strcmp(devstring,devname)==0){ /* found our device */
-          if(strcmp(bus_result->dev_name,"umass-sim")) {
-            close(fd);
-            return -1; /* non usb device found, giving up */
-          }
-          /* return bus number */
-          return  bus_result->unit_number;
-        }
-        break;
-    }
-
-  default:
-    fprintf(stdout, "WARN: unknown match type\n");
-    break;
-      }
-    }
-  } while ((ccb.ccb_h.status == CAM_REQ_CMP)
-    && (ccb.cdm.status == CAM_DEV_MATCH_MORE));
-
-  close(fd);
-  free(ccb.cdm.matches);
-  return(error); /* no device found */
+scsi_device * freebsd_smart_interface::get_scsi_device(const char * name, const char * type)
+{
+  return new freebsd_scsi_device(this, name, type);
 }
 
-
 // we are using CAM subsystem XPT enumerator to found all CAM (scsi/usb/ada/...)
 // devices on system despite of it's names
 //
 // If any errors occur, leave errno set as it was returned by the
 // system call, and return <0.
 //
+// arguments: 
+// names: resulting array
+// show_all - export duplicate device name or not
+//
 // Return values:
 // -1:   error
 // >=0: number of discovered devices
 
-int get_dev_names_cam(char*** names) {
-  int n = 0;
-  char** mp = NULL;
-  unsigned int i;
-  union ccb ccb;
-  int bufsize, fd = -1;
-  int skip_device = 0, skip_bus = 0, changed = 0;
-  char *devname = NULL;
-  int serrno=-1;
-
-  // in case of non-clean exit
-  *names=NULL;
-  ccb.cdm.matches = NULL;
-
+bool get_dev_names_cam(std::vector<std::string> & names, bool show_all)
+{
+  int fd;
   if ((fd = open(XPT_DEVICE, O_RDWR)) == -1) {
     if (errno == ENOENT) /* There are no CAM device on this computer */
       return 0;
-    serrno = errno;
+    int serrno = errno;
     pout("%s control device couldn't opened: %s\n", XPT_DEVICE, strerror(errno));
-    n = -1;
-    goto end;
+    errno = serrno;
+    return false;
   }
 
-  // allocate space for up to MAX_NUM_DEV number of ATA devices
-  mp =  (char **)calloc(MAX_NUM_DEV, sizeof(char*));
-  if (mp == NULL) {
-    serrno=errno;
-    pout("Out of memory constructing scan device list (on line %d)\n", __LINE__);
-    n = -1;
-    goto end;
-  };
-
+  union ccb ccb;
   bzero(&ccb, sizeof(union ccb));
 
   ccb.ccb_h.path_id = CAM_XPT_PATH_ID;
@@ -1768,14 +1721,15 @@ int get_dev_names_cam(char*** names) {
   ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;
 
   ccb.ccb_h.func_code = XPT_DEV_MATCH;
-  bufsize = sizeof(struct dev_match_result) * MAX_NUM_DEV;
+  int bufsize = sizeof(struct dev_match_result) * MAX_NUM_DEV;
   ccb.cdm.match_buf_len = bufsize;
+  // TODO: Use local buffer instead of malloc() if possible
   ccb.cdm.matches = (struct dev_match_result *)malloc(bufsize);
+  bzero(ccb.cdm.matches,bufsize); // clear ccb.cdm.matches structure
+  
   if (ccb.cdm.matches == NULL) {
-    serrno = errno;
-    pout("can't malloc memory for matches on line %d\n", __LINE__);
-    n = -1;
-    goto end;
+    close(fd);
+    throw std::bad_alloc();
   }
   ccb.cdm.num_matches = 0;
   ccb.cdm.num_patterns = 0;
@@ -1785,24 +1739,29 @@ int get_dev_names_cam(char*** names) {
    * We do the ioctl multiple times if necessary, in case there are
    * more than MAX_NUM_DEV nodes in the EDT.
    */
+  int skip_device = 0, skip_bus = 0, changed = 0; // TODO: bool
+  std::string devname;
   do {
     if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
-      serrno = errno;
+      int serrno = errno;
       pout("error sending CAMIOCOMMAND ioctl: %s\n", strerror(errno));
-      n = -1;
-      break;
+      free(ccb.cdm.matches);
+      close(fd);
+      errno = serrno;
+      return false;
     }
 
     if ((ccb.ccb_h.status != CAM_REQ_CMP)
       || ((ccb.cdm.status != CAM_DEV_MATCH_LAST)
       && (ccb.cdm.status != CAM_DEV_MATCH_MORE))) {
       pout("got CAM error %#x, CDM error %d\n", ccb.ccb_h.status, ccb.cdm.status);
-      serrno = ENXIO;
-      n = -1;
-      goto end;
+      free(ccb.cdm.matches);
+      close(fd);
+      errno = ENXIO;
+      return false;
     }
 
-    for (i = 0; i < ccb.cdm.num_matches && n < MAX_NUM_DEV; i++) {
+    for (unsigned i = 0; i < ccb.cdm.num_matches; i++) {
       struct bus_match_result *bus_result;
       struct device_match_result *dev_result;
       struct periph_match_result *periph_result;
@@ -1810,8 +1769,7 @@ int get_dev_names_cam(char*** names) {
       if (ccb.cdm.matches[i].type == DEV_MATCH_BUS) {
         bus_result = &ccb.cdm.matches[i].result.bus_result;
 
-        if (strcmp(bus_result->dev_name,"ata") == 0 /* ATAPICAM devices will be probed as ATA devices, skip'em there */
-          || strcmp(bus_result->dev_name,"xpt") == 0) /* skip XPT bus at all */
+        if (strcmp(bus_result->dev_name,"xpt") == 0) /* skip XPT bus at all */
         skip_bus = 1;
         else
           skip_bus = 0;
@@ -1823,62 +1781,35 @@ int get_dev_names_cam(char*** names) {
           skip_device = 1;
         else
           skip_device = 0;
-
+        
         //        /* Shall we skip non T_DIRECT devices ? */
         //        if (dev_result->inq_data.device != T_DIRECT)
         //          skip_device = 1;
         changed = 1;
-      } else if (ccb.cdm.matches[i].type == DEV_MATCH_PERIPH && skip_device == 0) { 
+      } else if (ccb.cdm.matches[i].type == DEV_MATCH_PERIPH && 
+          (skip_device == 0 || show_all)) { 
         /* One device may be populated as many peripherals (pass0 & da0 for example). 
         * We are searching for latest name
         */
         periph_result =  &ccb.cdm.matches[i].result.periph_result;
-        free(devname);
-        asprintf(&devname, "%s%s%d", _PATH_DEV, periph_result->periph_name, periph_result->unit_number);
-        if (devname == NULL) {
-          serrno=errno;
-          pout("Out of memory constructing scan SCSI device list (on line %d)\n", __LINE__);
-          n = -1;
-          goto end;
-        };
+        devname = strprintf("%s%s%d", _PATH_DEV, periph_result->periph_name, periph_result->unit_number);
         changed = 0;
       };
-
-      if (changed == 1 && devname != NULL) {
-        mp[n] = devname;
-        devname = NULL;
-        bytes+=1+strlen(mp[n]);
-        n++;
+      if ((changed == 1 || show_all) && !devname.empty()) {
+        names.push_back(devname);
+        devname.erase();
         changed = 0;
       };
     }
 
-  } while ((ccb.ccb_h.status == CAM_REQ_CMP) && (ccb.cdm.status == CAM_DEV_MATCH_MORE) && n < MAX_NUM_DEV);
+  } while ((ccb.ccb_h.status == CAM_REQ_CMP) && (ccb.cdm.status == CAM_DEV_MATCH_MORE));
 
-  if (devname != NULL) {
-    mp[n] = devname;
-    devname = NULL;
-    bytes+=1+strlen(mp[n]);
-    n++;
-  };
-
-  mp = (char **)reallocf(mp,n*(sizeof (char*))); // shrink to correct size
-  bytes += (n)*(sizeof(char*)); // and set allocated byte count
+  if (!devname.empty())
+    names.push_back(devname);
 
-end:
   free(ccb.cdm.matches);
-  if (fd>-1)
-    close(fd);
-  if (n <= 0) {
-    free(mp);
-    mp = NULL;
-  }
-
-  *names=mp;
-
-  if (serrno>-1)
-    errno=serrno;
-  return(n);
+  close(fd);
+  return true;
 }
 
 // we are using ATA subsystem enumerator to found all ATA devices on system
@@ -1946,6 +1877,12 @@ int get_dev_names_ata(char*** names) {
     };
   };  
   mp = (char **)reallocf(mp,n*(sizeof (char*))); // shrink to correct size
+  if (mp == NULL && n > 0 ) { // reallocf never fail for size=0, but may return NULL
+    serrno=errno;
+    pout("Out of memory constructing scan device list (on line %d)\n", __LINE__);
+    n = -1;
+    goto end;
+  };
   bytes += (n)*(sizeof(char*)); // and set allocated byte count
 
 end:
@@ -1983,11 +1920,10 @@ bool freebsd_smart_interface::scan_smart_devices(smart_device_list & devlist,
     }
   }
 
-  char * * scsinames = 0; int numscsi = 0;
-  if (!type || !strcmp(type, "scsi")) {
-    numscsi = get_dev_names_cam(&scsinames);
-    if (numscsi < 0) {
-      set_err(ENOMEM);
+  std::vector<std::string> scsinames;
+  if (!type || !strcmp(type, "scsi")) { // do not export duplicated names
+    if (!get_dev_names_cam(scsinames, false)) {
+      set_err(errno);
       return false;
     }
   }
@@ -1999,19 +1935,21 @@ bool freebsd_smart_interface::scan_smart_devices(smart_device_list & devlist,
   for (i = 0; i < numata; i++) {
     ata_device * atadev = get_ata_device(atanames[i], type);
     if (atadev)
-      devlist.add(atadev);
+      devlist.push_back(atadev);
+    free(atanames[i]);
   }
+  if(numata) free(atanames);
 
-  for (i = 0; i < numscsi; i++) {
+  for (i = 0; i < (int)scsinames.size(); i++) {
     if(!*type) { // try USB autodetection if no type specified
-      smart_device * smartdev = autodetect_smart_device(scsinames[i]);
+      smart_device * smartdev = autodetect_smart_device(scsinames[i].c_str());
       if(smartdev)
-        devlist.add(smartdev);
+        devlist.push_back(smartdev);
     }
     else {
-      scsi_device * scsidev = get_scsi_device(scsinames[i], type);
+      scsi_device * scsidev = get_scsi_device(scsinames[i].c_str(), type);
       if (scsidev)
-        devlist.add(scsidev);
+        devlist.push_back(scsidev);
     }
   }
   return true;
@@ -2152,48 +2090,105 @@ static int usbdevlist(int busno,unsigned short & vendor_id,
 #endif
 }
 
-// Get USB bridge ID for "/dev/daX"
-static bool get_usb_id(const char * path, unsigned short & vendor_id,
-  unsigned short & product_id, unsigned short & version)
-{
-  if (strlen(path) < 5)
-    return false;
-  int bus = cam_getumassno((char *)path+5);
-  if (bus == -1) 
-    return false;
-
-  usbdevlist(bus,vendor_id,
-    product_id, version);
-  return true;
-}
-
-
 smart_device * freebsd_smart_interface::autodetect_smart_device(const char * name)
 {
-  int guess = parse_ata_chan_dev(name,NULL,"");
   unsigned short vendor_id = 0, product_id = 0, version = 0;
+  struct cam_device *cam_dev;
+  union ccb ccb;
+  int bus=-1;
+  int i,c;
+  int len;
+  const char * test_name = name;
 
-  switch (guess) {
-  case CONTROLLER_ATA : 
-    return new freebsd_ata_device(this, name, "");
-  case CONTROLLER_SCSI: 
-    // Try to detect possible USB->(S)ATA bridge
-    if (get_usb_id(name, vendor_id, product_id, version)) {
-      const char * usbtype = get_usb_dev_type_by_id(vendor_id, product_id, version);
-      if (!usbtype)
-        return 0;
-      // Return SAT/USB device for this type
-      // (Note: freebsd_scsi_device::autodetect_open() will not be called in this case)
-      return get_sat_device(usbtype, new freebsd_scsi_device(this, name, ""));
-    }
-    // non usb device, handle as normal scsi
-    return new freebsd_scsi_device(this, name, "");
-  case CONTROLLER_CCISS:
-    // device - cciss, but no ID known
-    set_err(EINVAL, "Option -d cciss,N requires N to be a non-negative integer");
+  // if dev_name null, or string length zero
+  if (!name || !(len = strlen(name)))
     return 0;
+
+  // 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();
+    }
   }
-  // TODO: Test autodetected device here
+
+  // check ATA bus
+  char * * atanames = 0; int numata = 0;
+  numata = get_dev_names_ata(&atanames);
+  if (numata > 0) {
+    // check ATA/ATAPI devices
+    for (i = 0; i < numata; i++) {
+      if(!strcmp(atanames[i],test_name)) {
+        for (c = i; c < numata; c++) free(atanames[c]);
+        free(atanames);
+        return new freebsd_ata_device(this, test_name, "");
+      }
+      else free(atanames[i]);
+    }
+    if(numata) free(atanames);
+  }
+  else {
+    if (numata < 0)
+      pout("Unable to get ATA device list\n");
+  }
+
+  // check CAM
+  std::vector<std::string> scsinames;
+  if (!get_dev_names_cam(scsinames, true))
+    pout("Unable to get CAM device list\n");
+  else if (!scsinames.empty()) {
+    // check all devices on CAM bus
+    for (i = 0; i < (int)scsinames.size(); i++) {
+      if(strcmp(scsinames[i].c_str(), test_name)==0)
+      { // our disk device is CAM
+        if ((cam_dev = cam_open_device(test_name, O_RDWR)) == NULL) {
+          // open failure
+          set_err(errno);
+          return 0;
+        }
+        // zero the payload
+        bzero(&(&ccb.ccb_h)[1], PATHINQ_SETTINGS_SIZE);
+        ccb.ccb_h.func_code = XPT_PATH_INQ; // send PATH_INQ to the device
+        if (ioctl(cam_dev->fd, CAMIOCOMMAND, &ccb) == -1) {
+          warn("Get Transfer Settings CCB failed\n"
+            "%s", strerror(errno));
+          cam_close_device(cam_dev);
+          return 0;
+        }
+        // now check if we are working with USB device, see umass.c
+        if(strcmp(ccb.cpi.dev_name,"umass-sim") == 0) { // USB device found
+          usbdevlist(bus,vendor_id, product_id, version);
+          int bus=ccb.cpi.unit_number; // unit_number will match umass number
+          cam_close_device(cam_dev);
+          if(usbdevlist(bus,vendor_id, product_id, version)){
+            const char * usbtype = get_usb_dev_type_by_id(vendor_id, product_id, version);
+            if (usbtype)
+              return get_sat_device(usbtype, new freebsd_scsi_device(this, test_name, ""));
+          }
+          return 0;
+        }
+#if FREEBSDVER > 800100
+        // check if we have ATA device connected to CAM (ada)
+        if(ccb.cpi.protocol == PROTO_ATA){
+          cam_close_device(cam_dev);
+          return new freebsd_atacam_device(this, test_name, "");
+        }
+#endif
+        // close cam device, we don`t need it anymore
+        cam_close_device(cam_dev);
+        // handle as usual scsi
+        return new freebsd_scsi_device(this, test_name, "");      
+      }
+    }
+  }
+  // device is LSI raid supported by mfi driver
+  if(!strncmp("/dev/mfid", test_name, strlen("/dev/mfid")))
+    set_err(EINVAL, "To monitor disks on LSI RAID load mfip.ko module and run 'smartctl -a /dev/passX' to show SMART information");
+  // device type unknown
   return 0;
 }
 
@@ -2201,7 +2196,10 @@ smart_device * freebsd_smart_interface::autodetect_smart_device(const char * nam
 smart_device * freebsd_smart_interface::get_custom_smart_device(const char * name, const char * type)
 {
   // 3Ware ?
-  int disknum = -1, n1 = -1, n2 = -1;
+  static const char * fbsd_dev_twe_ctrl = "/dev/twe";
+  static const char * fbsd_dev_twa_ctrl = "/dev/twa";
+  int disknum = -1, n1 = -1, n2 = -1, contr = -1;
+
   if (sscanf(type, "3ware,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
     if (n2 != (int)strlen(type)) {
       set_err(EINVAL, "Option -d 3ware,N requires N to be a non-negative integer");
@@ -2211,9 +2209,20 @@ smart_device * freebsd_smart_interface::get_custom_smart_device(const char * nam
       set_err(EINVAL, "Option -d 3ware,N (N=%d) must have 0 <= N <= 127", disknum);
       return 0;
     }
-    int contr = parse_ata_chan_dev(name,NULL,"");
-    if (contr != CONTROLLER_3WARE_9000_CHAR && contr != CONTROLLER_3WARE_678K_CHAR)
-      contr = CONTROLLER_3WARE_678K;
+
+    // guess 3ware device type based on device name
+    if (!strncmp(fbsd_dev_twa_ctrl, name, strlen(fbsd_dev_twa_ctrl))){
+      contr=CONTROLLER_3WARE_9000_CHAR;
+    }
+    if (!strncmp(fbsd_dev_twe_ctrl, name, strlen(fbsd_dev_twe_ctrl))){
+      contr=CONTROLLER_3WARE_678K_CHAR;
+    }
+
+    if(contr == -1){
+      set_err(EINVAL, "3ware controller type unknown, use %sX or %sX devices", 
+        fbsd_dev_twe_ctrl, fbsd_dev_twa_ctrl);
+      return 0;
+    }
     return new freebsd_escalade_device(this, name, contr, disknum);
   } 
 
@@ -2230,7 +2239,7 @@ smart_device * freebsd_smart_interface::get_custom_smart_device(const char * nam
       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 <= 16)) {
       set_err(EINVAL, "Option '-d hpt,L/M/N' invalid channel number M supplied");
       return 0;
     }
@@ -2248,19 +2257,41 @@ smart_device * freebsd_smart_interface::get_custom_smart_device(const char * nam
       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 freebsd_cciss_device(this, name, disknum);
   }
+#if FREEBSDVER > 800100
+  // adaX devices ?
+  if(!strcmp(type,"atacam"))
+    return new freebsd_atacam_device(this, name, "");
+#endif
+  // 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");
+      return 0;
+    }
+    if (!(1 <= disknum && disknum <= 24)) {
+      set_err(EINVAL, "Option -d areca,N (N=%d) must have 1 <= N <= 24", disknum);
+      return 0;
+    }
+    return new freebsd_areca_device(this, name, disknum);
+  }
 
   return 0;
 }
 
 std::string freebsd_smart_interface::get_valid_custom_dev_types_str()
 {
-  return "3ware,N, hpt,L/M/N, cciss,N";
+  return "3ware,N, hpt,L/M/N, cciss,N, areca,N"
+#if FREEBSDVER > 800100
+  ", atacam"
+#endif
+  ;
 }
 
 } // namespace