smartmontools SVN Rev 3317
Utility to control and monitor storage systems with "S.M.A.R.T."
os_linux.cpp
Go to the documentation of this file.
00001 /*
00002  *  os_linux.cpp
00003  *
00004  * Home page of code is: http://smartmontools.sourceforge.net
00005  *
00006  * Copyright (C) 2003-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
00007  * Copyright (C) 2003-11 Doug Gilbert <dgilbert@interlog.com>
00008  * Copyright (C) 2008-14 Christian Franke <smartmontools-support@lists.sourceforge.net>
00009  *
00010  * Original AACRaid code:
00011  *  Copyright (C) 2014    Raghava Aditya <raghava.aditya@pmcs.com>
00012  *
00013  * Original Areca code:
00014  *  Copyright (C) 2008-12 Hank Wu <hank@areca.com.tw>
00015  *  Copyright (C) 2008    Oliver Bock <brevilo@users.sourceforge.net>
00016  *
00017  * Original MegaRAID code:
00018  *  Copyright (C) 2008    Jordan Hargrave <jordan_hargrave@dell.com>
00019  *
00020  * 3ware code was derived from code that was:
00021  *
00022  *  Written By: Adam Radford <linux@3ware.com>
00023  *  Modifications By: Joel Jacobson <linux@3ware.com>
00024  *                    Arnaldo Carvalho de Melo <acme@conectiva.com.br>
00025  *                    Brad Strand <linux@3ware.com>
00026  *
00027  *  Copyright (C) 1999-2003 3ware Inc.
00028  *
00029  *  Kernel compatablity By:     Andre Hedrick <andre@suse.com>
00030  *  Non-Copyright (C) 2000      Andre Hedrick <andre@suse.com>
00031  *
00032  * Other ars of this file are derived from code that was
00033  *
00034  * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
00035  * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
00036  *
00037  * This program is free software; you can redistribute it and/or modify
00038  * it under the terms of the GNU General Public License as published by
00039  * the Free Software Foundation; either version 2, or (at your option)
00040  * any later version.
00041  *
00042  * You should have received a copy of the GNU General Public License
00043  * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
00044  *
00045  * This code was originally developed as a Senior Thesis by Michael Cornwell
00046  * at the Concurrent Systems Laboratory (now part of the Storage Systems
00047  * Research Center), Jack Baskin School of Engineering, University of
00048  * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
00049  *
00050  */
00051 
00052 // This file contains the linux-specific IOCTL parts of
00053 // smartmontools. It includes one interface routine for ATA devices,
00054 // one for SCSI devices, and one for ATA devices behind escalade
00055 // controllers.
00056 
00057 #include "config.h"
00058 
00059 #include <errno.h>
00060 #include <fcntl.h>
00061 #include <glob.h>
00062 
00063 #include <scsi/scsi.h>
00064 #include <scsi/scsi_ioctl.h>
00065 #include <scsi/sg.h>
00066 #include <stdlib.h>
00067 #include <string.h>
00068 #include <sys/ioctl.h>
00069 #include <sys/stat.h>
00070 #include <sys/utsname.h>
00071 #include <unistd.h>
00072 #include <stddef.h>  // for offsetof()
00073 #include <sys/uio.h>
00074 #include <sys/types.h>
00075 #include <dirent.h>
00076 #ifndef makedev // old versions of types.h do not include sysmacros.h
00077 #include <sys/sysmacros.h>
00078 #endif
00079 #ifdef WITH_SELINUX
00080 #include <selinux/selinux.h>
00081 #endif
00082 
00083 #include "int64.h"
00084 #include "atacmds.h"
00085 #include "os_linux.h"
00086 #include "scsicmds.h"
00087 #include "utility.h"
00088 #include "cciss.h"
00089 #include "megaraid.h"
00090 #include "aacraid.h"
00091 
00092 #include "dev_interface.h"
00093 #include "dev_ata_cmd_set.h"
00094 #include "dev_areca.h"
00095 
00096 #ifndef ENOTSUP
00097 #define ENOTSUP ENOSYS
00098 #endif
00099 
00100 #define ARGUSED(x) ((void)(x))
00101 
00102 const char * os_linux_cpp_cvsid = "$Id: os_linux.cpp 3900 2014-05-01 17:08:59Z chrfranke $"
00103   OS_LINUX_H_CVSID;
00104 extern unsigned char failuretest_permissive;
00105 
00106 namespace os_linux { // No need to publish anything, name provided for Doxygen
00107 
00108 /////////////////////////////////////////////////////////////////////////////
00109 /// Shared open/close routines
00110 
00111 class linux_smart_device
00112 : virtual public /*implements*/ smart_device
00113 {
00114 public:
00115   explicit linux_smart_device(int flags, int retry_flags = -1)
00116     : smart_device(never_called),
00117       m_fd(-1),
00118       m_flags(flags), m_retry_flags(retry_flags)
00119       { }
00120 
00121   virtual ~linux_smart_device() throw();
00122 
00123   virtual bool is_open() const;
00124 
00125   virtual bool open();
00126 
00127   virtual bool close();
00128 
00129 protected:
00130   /// Return filedesc for derived classes.
00131   int get_fd() const
00132     { return m_fd; }
00133 
00134   void set_fd(int fd)
00135     { m_fd = fd; }
00136 
00137 private:
00138   int m_fd; ///< filedesc, -1 if not open.
00139   int m_flags; ///< Flags for ::open()
00140   int m_retry_flags; ///< Flags to retry ::open(), -1 if no retry
00141 };
00142 
00143 linux_smart_device::~linux_smart_device() throw()
00144 {
00145   if (m_fd >= 0)
00146     ::close(m_fd);
00147 }
00148 
00149 bool linux_smart_device::is_open() const
00150 {
00151   return (m_fd >= 0);
00152 }
00153 
00154 bool linux_smart_device::open()
00155 {
00156   m_fd = ::open(get_dev_name(), m_flags);
00157 
00158   if (m_fd < 0 && errno == EROFS && m_retry_flags != -1)
00159     // Retry
00160     m_fd = ::open(get_dev_name(), m_retry_flags);
00161 
00162   if (m_fd < 0) {
00163     if (errno == EBUSY && (m_flags & O_EXCL))
00164       // device is locked
00165       return set_err(EBUSY,
00166         "The requested controller is used exclusively by another process!\n"
00167         "(e.g. smartctl or smartd)\n"
00168         "Please quit the impeding process or try again later...");
00169     return set_err((errno==ENOENT || errno==ENOTDIR) ? ENODEV : errno);
00170   }
00171 
00172   if (m_fd >= 0) {
00173     // sets FD_CLOEXEC on the opened device file descriptor.  The
00174     // descriptor is otherwise leaked to other applications (mail
00175     // sender) which may be considered a security risk and may result
00176     // in AVC messages on SELinux-enabled systems.
00177     if (-1 == fcntl(m_fd, F_SETFD, FD_CLOEXEC))
00178       // TODO: Provide an error printing routine in class smart_interface
00179       pout("fcntl(set  FD_CLOEXEC) failed, errno=%d [%s]\n", errno, strerror(errno));
00180   }
00181 
00182   return true;
00183 }
00184 
00185 // equivalent to close(file descriptor)
00186 bool linux_smart_device::close()
00187 {
00188   int fd = m_fd; m_fd = -1;
00189   if (::close(fd) < 0)
00190     return set_err(errno);
00191   return true;
00192 }
00193 
00194 // examples for smartctl
00195 static const char  smartctl_examples[] =
00196                   "=================================================== SMARTCTL EXAMPLES =====\n\n"
00197                   "  smartctl --all /dev/hda                    (Prints all SMART information)\n\n"
00198                   "  smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda\n"
00199                   "                                              (Enables SMART on first disk)\n\n"
00200                   "  smartctl --test=long /dev/hda          (Executes extended disk self-test)\n\n"
00201                   "  smartctl --attributes --log=selftest --quietmode=errorsonly /dev/hda\n"
00202                   "                                      (Prints Self-Test & Attribute errors)\n"
00203                   "  smartctl --all --device=3ware,2 /dev/sda\n"
00204                   "  smartctl --all --device=3ware,2 /dev/twe0\n"
00205                   "  smartctl --all --device=3ware,2 /dev/twa0\n"
00206                   "  smartctl --all --device=3ware,2 /dev/twl0\n"
00207                   "          (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
00208                   "  smartctl --all --device=hpt,1/1/3 /dev/sda\n"
00209                   "          (Prints all SMART info for the SATA disk attached to the 3rd PMPort\n"
00210                   "           of the 1st channel on the 1st HighPoint RAID controller)\n"
00211                   "  smartctl --all --device=areca,3/1 /dev/sg2\n"
00212                   "          (Prints all SMART info for 3rd ATA disk of the 1st enclosure\n"
00213                   "           on Areca RAID controller)\n"
00214   ;
00215 
00216 /////////////////////////////////////////////////////////////////////////////
00217 /// Linux ATA support
00218 
00219 class linux_ata_device
00220 : public /*implements*/ ata_device_with_command_set,
00221   public /*extends*/ linux_smart_device
00222 {
00223 public:
00224   linux_ata_device(smart_interface * intf, const char * dev_name, const char * req_type);
00225 
00226 protected:
00227   virtual int ata_command_interface(smart_command_set command, int select, char * data);
00228 };
00229 
00230 linux_ata_device::linux_ata_device(smart_interface * intf, const char * dev_name, const char * req_type)
00231 : smart_device(intf, dev_name, "ata", req_type),
00232   linux_smart_device(O_RDONLY | O_NONBLOCK)
00233 {
00234 }
00235 
00236 // PURPOSE
00237 //   This is an interface routine meant to isolate the OS dependent
00238 //   parts of the code, and to provide a debugging interface.  Each
00239 //   different port and OS needs to provide it's own interface.  This
00240 //   is the linux one.
00241 // DETAILED DESCRIPTION OF ARGUMENTS
00242 //   device: is the file descriptor provided by open()
00243 //   command: defines the different operations.
00244 //   select: additional input data if needed (which log, which type of
00245 //           self-test).
00246 //   data:   location to write output data, if needed (512 bytes).
00247 //   Note: not all commands use all arguments.
00248 // RETURN VALUES
00249 //  -1 if the command failed
00250 //   0 if the command succeeded,
00251 //   STATUS_CHECK routine:
00252 //  -1 if the command failed
00253 //   0 if the command succeeded and disk SMART status is "OK"
00254 //   1 if the command succeeded and disk SMART status is "FAILING"
00255 
00256 #define BUFFER_LENGTH (4+512)
00257 
00258 int linux_ata_device::ata_command_interface(smart_command_set command, int select, char * data)
00259 {
00260   unsigned char buff[BUFFER_LENGTH];
00261   // positive: bytes to write to caller.  negative: bytes to READ from
00262   // caller. zero: non-data command
00263   int copydata=0;
00264 
00265   const int HDIO_DRIVE_CMD_OFFSET = 4;
00266 
00267   // See struct hd_drive_cmd_hdr in hdreg.h.  Before calling ioctl()
00268   // buff[0]: ATA COMMAND CODE REGISTER
00269   // buff[1]: ATA SECTOR NUMBER REGISTER == LBA LOW REGISTER
00270   // buff[2]: ATA FEATURES REGISTER
00271   // buff[3]: ATA SECTOR COUNT REGISTER
00272 
00273   // Note that on return:
00274   // buff[2] contains the ATA SECTOR COUNT REGISTER
00275 
00276   // clear out buff.  Large enough for HDIO_DRIVE_CMD (4+512 bytes)
00277   memset(buff, 0, BUFFER_LENGTH);
00278 
00279   buff[0]=ATA_SMART_CMD;
00280   switch (command){
00281   case CHECK_POWER_MODE:
00282     buff[0]=ATA_CHECK_POWER_MODE;
00283     copydata=1;
00284     break;
00285   case READ_VALUES:
00286     buff[2]=ATA_SMART_READ_VALUES;
00287     buff[3]=1;
00288     copydata=512;
00289     break;
00290   case READ_THRESHOLDS:
00291     buff[2]=ATA_SMART_READ_THRESHOLDS;
00292     buff[1]=buff[3]=1;
00293     copydata=512;
00294     break;
00295   case READ_LOG:
00296     buff[2]=ATA_SMART_READ_LOG_SECTOR;
00297     buff[1]=select;
00298     buff[3]=1;
00299     copydata=512;
00300     break;
00301   case WRITE_LOG:
00302     break;
00303   case IDENTIFY:
00304     buff[0]=ATA_IDENTIFY_DEVICE;
00305     buff[3]=1;
00306     copydata=512;
00307     break;
00308   case PIDENTIFY:
00309     buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
00310     buff[3]=1;
00311     copydata=512;
00312     break;
00313   case ENABLE:
00314     buff[2]=ATA_SMART_ENABLE;
00315     buff[1]=1;
00316     break;
00317   case DISABLE:
00318     buff[2]=ATA_SMART_DISABLE;
00319     buff[1]=1;
00320     break;
00321   case STATUS:
00322     // this command only says if SMART is working.  It could be
00323     // replaced with STATUS_CHECK below.
00324     buff[2]=ATA_SMART_STATUS;
00325     break;
00326   case AUTO_OFFLINE:
00327     // NOTE: According to ATAPI 4 and UP, this command is obsolete
00328     // select == 241 for enable but no data transfer.  Use TASK ioctl.
00329     buff[1]=ATA_SMART_AUTO_OFFLINE;
00330     buff[2]=select;
00331     break;
00332   case AUTOSAVE:
00333     // select == 248 for enable but no data transfer.  Use TASK ioctl.
00334     buff[1]=ATA_SMART_AUTOSAVE;
00335     buff[2]=select;
00336     break;
00337   case IMMEDIATE_OFFLINE:
00338     buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
00339     buff[1]=select;
00340     break;
00341   case STATUS_CHECK:
00342     // This command uses HDIO_DRIVE_TASK and has different syntax than
00343     // the other commands.
00344     buff[1]=ATA_SMART_STATUS;
00345     break;
00346   default:
00347     pout("Unrecognized command %d in linux_ata_command_interface()\n"
00348          "Please contact " PACKAGE_BUGREPORT "\n", command);
00349     errno=ENOSYS;
00350     return -1;
00351   }
00352 
00353   // This command uses the HDIO_DRIVE_TASKFILE ioctl(). This is the
00354   // only ioctl() that can be used to WRITE data to the disk.
00355   if (command==WRITE_LOG) {
00356     unsigned char task[sizeof(ide_task_request_t)+512];
00357     ide_task_request_t *reqtask=(ide_task_request_t *) task;
00358     task_struct_t      *taskfile=(task_struct_t *) reqtask->io_ports;
00359     int retval;
00360 
00361     memset(task,      0, sizeof(task));
00362 
00363     taskfile->data           = 0;
00364     taskfile->feature        = ATA_SMART_WRITE_LOG_SECTOR;
00365     taskfile->sector_count   = 1;
00366     taskfile->sector_number  = select;
00367     taskfile->low_cylinder   = 0x4f;
00368     taskfile->high_cylinder  = 0xc2;
00369     taskfile->device_head    = 0;
00370     taskfile->command        = ATA_SMART_CMD;
00371 
00372     reqtask->data_phase      = TASKFILE_OUT;
00373     reqtask->req_cmd         = IDE_DRIVE_TASK_OUT;
00374     reqtask->out_size        = 512;
00375     reqtask->in_size         = 0;
00376 
00377     // copy user data into the task request structure
00378     memcpy(task+sizeof(ide_task_request_t), data, 512);
00379 
00380     if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASKFILE, task))) {
00381       if (retval==-EINVAL)
00382         pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
00383       return -1;
00384     }
00385     return 0;
00386   }
00387 
00388   // There are two different types of ioctls().  The HDIO_DRIVE_TASK
00389   // one is this:
00390   if (command==STATUS_CHECK || command==AUTOSAVE || command==AUTO_OFFLINE){
00391     int retval;
00392 
00393     // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
00394     // have to read the IDE driver source code.  Sigh.
00395     // buff[0]: ATA COMMAND CODE REGISTER
00396     // buff[1]: ATA FEATURES REGISTER
00397     // buff[2]: ATA SECTOR_COUNT
00398     // buff[3]: ATA SECTOR NUMBER
00399     // buff[4]: ATA CYL LO REGISTER
00400     // buff[5]: ATA CYL HI REGISTER
00401     // buff[6]: ATA DEVICE HEAD
00402 
00403     unsigned const char normal_lo=0x4f, normal_hi=0xc2;
00404     unsigned const char failed_lo=0xf4, failed_hi=0x2c;
00405     buff[4]=normal_lo;
00406     buff[5]=normal_hi;
00407 
00408     if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASK, buff))) {
00409       if (retval==-EINVAL) {
00410         pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
00411         pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
00412       }
00413       else
00414         syserror("Error SMART Status command failed");
00415       return -1;
00416     }
00417 
00418     // Cyl low and Cyl high unchanged means "Good SMART status"
00419     if (buff[4]==normal_lo && buff[5]==normal_hi)
00420       return 0;
00421 
00422     // These values mean "Bad SMART status"
00423     if (buff[4]==failed_lo && buff[5]==failed_hi)
00424       return 1;
00425 
00426     // We haven't gotten output that makes sense; print out some debugging info
00427     syserror("Error SMART Status command failed");
00428     pout("Please get assistance from " PACKAGE_HOMEPAGE "\n");
00429     pout("Register values returned from SMART Status command are:\n");
00430     pout("ST =0x%02x\n",(int)buff[0]);
00431     pout("ERR=0x%02x\n",(int)buff[1]);
00432     pout("NS =0x%02x\n",(int)buff[2]);
00433     pout("SC =0x%02x\n",(int)buff[3]);
00434     pout("CL =0x%02x\n",(int)buff[4]);
00435     pout("CH =0x%02x\n",(int)buff[5]);
00436     pout("SEL=0x%02x\n",(int)buff[6]);
00437     return -1;
00438   }
00439 
00440 #if 1
00441   // Note to people doing ports to other OSes -- don't worry about
00442   // this block -- you can safely ignore it.  I have put it here
00443   // because under linux when you do IDENTIFY DEVICE to a packet
00444   // device, it generates an ugly kernel syslog error message.  This
00445   // is harmless but frightens users.  So this block detects packet
00446   // devices and make IDENTIFY DEVICE fail "nicely" without a syslog
00447   // error message.
00448   //
00449   // If you read only the ATA specs, it appears as if a packet device
00450   // *might* respond to the IDENTIFY DEVICE command.  This is
00451   // misleading - it's because around the time that SFF-8020 was
00452   // incorporated into the ATA-3/4 standard, the ATA authors were
00453   // sloppy. See SFF-8020 and you will see that ATAPI devices have
00454   // *always* had IDENTIFY PACKET DEVICE as a mandatory part of their
00455   // command set, and return 'Command Aborted' to IDENTIFY DEVICE.
00456   if (command==IDENTIFY || command==PIDENTIFY){
00457     unsigned short deviceid[256];
00458     // check the device identity, as seen when the system was booted
00459     // or the device was FIRST registered.  This will not be current
00460     // if the user has subsequently changed some of the parameters. If
00461     // device is a packet device, swap the command interpretations.
00462     if (!ioctl(get_fd(), HDIO_GET_IDENTITY, deviceid) && (deviceid[0] & 0x8000))
00463       buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
00464   }
00465 #endif
00466 
00467   // We are now doing the HDIO_DRIVE_CMD type ioctl.
00468   if ((ioctl(get_fd(), HDIO_DRIVE_CMD, buff)))
00469     return -1;
00470 
00471   // CHECK POWER MODE command returns information in the Sector Count
00472   // register (buff[3]).  Copy to return data buffer.
00473   if (command==CHECK_POWER_MODE)
00474     buff[HDIO_DRIVE_CMD_OFFSET]=buff[2];
00475 
00476   // if the command returns data then copy it back
00477   if (copydata)
00478     memcpy(data, buff+HDIO_DRIVE_CMD_OFFSET, copydata);
00479 
00480   return 0;
00481 }
00482 
00483 // >>>>>> Start of general SCSI specific linux code
00484 
00485 /* Linux specific code.
00486  * Historically smartmontools (and smartsuite before it) used the
00487  * SCSI_IOCTL_SEND_COMMAND ioctl which is available to all linux device
00488  * nodes that use the SCSI subsystem. A better interface has been available
00489  * via the SCSI generic (sg) driver but this involves the extra step of
00490  * mapping disk devices (e.g. /dev/sda) to the corresponding sg device
00491  * (e.g. /dev/sg2). In the linux kernel 2.6 series most of the facilities of
00492  * the sg driver have become available via the SG_IO ioctl which is available
00493  * on all SCSI devices (on SCSI tape devices from lk 2.6.6).
00494  * So the strategy below is to find out if the SG_IO ioctl is available and
00495  * if so use it; failing that use the older SCSI_IOCTL_SEND_COMMAND ioctl.
00496  * Should work in 2.0, 2.2, 2.4 and 2.6 series linux kernels. */
00497 
00498 #define MAX_DXFER_LEN 1024      /* can be increased if necessary */
00499 #define SEND_IOCTL_RESP_SENSE_LEN 16    /* ioctl limitation */
00500 #define SG_IO_RESP_SENSE_LEN 64 /* large enough see buffer */
00501 #define LSCSI_DRIVER_MASK  0xf /* mask out "suggestions" */
00502 #define LSCSI_DRIVER_SENSE  0x8 /* alternate CHECK CONDITION indication */
00503 #define LSCSI_DID_ERROR 0x7 /* Need to work around aacraid driver quirk */
00504 #define LSCSI_DRIVER_TIMEOUT  0x6
00505 #define LSCSI_DID_TIME_OUT  0x3
00506 #define LSCSI_DID_BUS_BUSY  0x2
00507 #define LSCSI_DID_NO_CONNECT  0x1
00508 
00509 #ifndef SCSI_IOCTL_SEND_COMMAND
00510 #define SCSI_IOCTL_SEND_COMMAND 1
00511 #endif
00512 
00513 #define SG_IO_PRESENT_UNKNOWN 0
00514 #define SG_IO_PRESENT_YES 1
00515 #define SG_IO_PRESENT_NO 2
00516 
00517 static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
00518                          int unknown);
00519 static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report);
00520 
00521 static int sg_io_state = SG_IO_PRESENT_UNKNOWN;
00522 
00523 /* Preferred implementation for issuing SCSI commands in linux. This
00524  * function uses the SG_IO ioctl. Return 0 if command issued successfully
00525  * (various status values should still be checked). If the SCSI command
00526  * cannot be issued then a negative errno value is returned. */
00527 static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
00528                          int unknown)
00529 {
00530 #ifndef SG_IO
00531     ARGUSED(dev_fd); ARGUSED(iop); ARGUSED(report);
00532     return -ENOTTY;
00533 #else
00534     struct sg_io_hdr io_hdr;
00535 
00536     if (report > 0) {
00537         int k, j;
00538         const unsigned char * ucp = iop->cmnd;
00539         const char * np;
00540         char buff[256];
00541         const int sz = (int)sizeof(buff);
00542 
00543         np = scsi_get_opcode_name(ucp[0]);
00544         j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
00545         for (k = 0; k < (int)iop->cmnd_len; ++k)
00546             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
00547         if ((report > 1) &&
00548             (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
00549             int trunc = (iop->dxfer_len > 256) ? 1 : 0;
00550 
00551             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
00552                           "data, len=%d%s:\n", (int)iop->dxfer_len,
00553                           (trunc ? " [only first 256 bytes shown]" : ""));
00554             dStrHex((const char *)iop->dxferp,
00555                     (trunc ? 256 : iop->dxfer_len) , 1);
00556         }
00557         else
00558             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
00559         pout("%s", buff);
00560     }
00561     memset(&io_hdr, 0, sizeof(struct sg_io_hdr));
00562     io_hdr.interface_id = 'S';
00563     io_hdr.cmd_len = iop->cmnd_len;
00564     io_hdr.mx_sb_len = iop->max_sense_len;
00565     io_hdr.dxfer_len = iop->dxfer_len;
00566     io_hdr.dxferp = iop->dxferp;
00567     io_hdr.cmdp = iop->cmnd;
00568     io_hdr.sbp = iop->sensep;
00569     /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
00570        defaults to 60 seconds. */
00571     io_hdr.timeout = ((0 == iop->timeout) ? 60 : iop->timeout) * 1000;
00572     switch (iop->dxfer_dir) {
00573         case DXFER_NONE:
00574             io_hdr.dxfer_direction = SG_DXFER_NONE;
00575             break;
00576         case DXFER_FROM_DEVICE:
00577             io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
00578             break;
00579         case DXFER_TO_DEVICE:
00580             io_hdr.dxfer_direction = SG_DXFER_TO_DEV;
00581             break;
00582         default:
00583             pout("do_scsi_cmnd_io: bad dxfer_dir\n");
00584             return -EINVAL;
00585     }
00586     iop->resp_sense_len = 0;
00587     iop->scsi_status = 0;
00588     iop->resid = 0;
00589     if (ioctl(dev_fd, SG_IO, &io_hdr) < 0) {
00590         if (report && (! unknown))
00591             pout("  SG_IO ioctl failed, errno=%d [%s]\n", errno,
00592                  strerror(errno));
00593         return -errno;
00594     }
00595     iop->resid = io_hdr.resid;
00596     iop->scsi_status = io_hdr.status;
00597     if (report > 0) {
00598         pout("  scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
00599              "  info=0x%x  duration=%d milliseconds  resid=%d\n", io_hdr.status,
00600              io_hdr.host_status, io_hdr.driver_status, io_hdr.info,
00601              io_hdr.duration, io_hdr.resid);
00602         if (report > 1) {
00603             if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
00604                 int trunc, len;
00605 
00606                 len = iop->dxfer_len - iop->resid;
00607                 trunc = (len > 256) ? 1 : 0;
00608                 if (len > 0) {
00609                     pout("  Incoming data, len=%d%s:\n", len,
00610                          (trunc ? " [only first 256 bytes shown]" : ""));
00611                     dStrHex((const char*)iop->dxferp, (trunc ? 256 : len),
00612                             1);
00613                 } else
00614                     pout("  Incoming data trimmed to nothing by resid\n");
00615             }
00616         }
00617     }
00618 
00619     if (io_hdr.info & SG_INFO_CHECK) { /* error or warning */
00620         int masked_driver_status = (LSCSI_DRIVER_MASK & io_hdr.driver_status);
00621 
00622         if (0 != io_hdr.host_status) {
00623             if ((LSCSI_DID_NO_CONNECT == io_hdr.host_status) ||
00624                 (LSCSI_DID_BUS_BUSY == io_hdr.host_status) ||
00625                 (LSCSI_DID_TIME_OUT == io_hdr.host_status))
00626                 return -ETIMEDOUT;
00627             else
00628                /* Check for DID_ERROR - workaround for aacraid driver quirk */
00629                if (LSCSI_DID_ERROR != io_hdr.host_status) {
00630                        return -EIO; /* catch all if not DID_ERR */
00631                }
00632         }
00633         if (0 != masked_driver_status) {
00634             if (LSCSI_DRIVER_TIMEOUT == masked_driver_status)
00635                 return -ETIMEDOUT;
00636             else if (LSCSI_DRIVER_SENSE != masked_driver_status)
00637                 return -EIO;
00638         }
00639         if (LSCSI_DRIVER_SENSE == masked_driver_status)
00640             iop->scsi_status = SCSI_STATUS_CHECK_CONDITION;
00641         iop->resp_sense_len = io_hdr.sb_len_wr;
00642         if ((SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) &&
00643             iop->sensep && (iop->resp_sense_len > 0)) {
00644             if (report > 1) {
00645                 pout("  >>> Sense buffer, len=%d:\n",
00646                      (int)iop->resp_sense_len);
00647                 dStrHex((const char *)iop->sensep, iop->resp_sense_len , 1);
00648             }
00649         }
00650         if (report) {
00651             if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) {
00652                 if ((iop->sensep[0] & 0x7f) > 0x71)
00653                     pout("  status=%x: [desc] sense_key=%x asc=%x ascq=%x\n",
00654                          iop->scsi_status, iop->sensep[1] & 0xf,
00655                          iop->sensep[2], iop->sensep[3]);
00656                 else
00657                     pout("  status=%x: sense_key=%x asc=%x ascq=%x\n",
00658                          iop->scsi_status, iop->sensep[2] & 0xf,
00659                          iop->sensep[12], iop->sensep[13]);
00660             }
00661             else
00662                 pout("  status=0x%x\n", iop->scsi_status);
00663         }
00664     }
00665     return 0;
00666 #endif
00667 }
00668 
00669 struct linux_ioctl_send_command
00670 {
00671     int inbufsize;
00672     int outbufsize;
00673     UINT8 buff[MAX_DXFER_LEN + 16];
00674 };
00675 
00676 /* The Linux SCSI_IOCTL_SEND_COMMAND ioctl is primitive and it doesn't
00677  * support: CDB length (guesses it from opcode), resid and timeout.
00678  * Patches in Linux 2.4.21 and 2.5.70 to extend SEND DIAGNOSTIC timeout
00679  * to 2 hours in order to allow long foreground extended self tests. */
00680 static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
00681 {
00682     struct linux_ioctl_send_command wrk;
00683     int status, buff_offset;
00684     size_t len;
00685 
00686     memcpy(wrk.buff, iop->cmnd, iop->cmnd_len);
00687     buff_offset = iop->cmnd_len;
00688     if (report > 0) {
00689         int k, j;
00690         const unsigned char * ucp = iop->cmnd;
00691         const char * np;
00692         char buff[256];
00693         const int sz = (int)sizeof(buff);
00694 
00695         np = scsi_get_opcode_name(ucp[0]);
00696         j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
00697         for (k = 0; k < (int)iop->cmnd_len; ++k)
00698             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
00699         if ((report > 1) &&
00700             (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
00701             int trunc = (iop->dxfer_len > 256) ? 1 : 0;
00702 
00703             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
00704                           "data, len=%d%s:\n", (int)iop->dxfer_len,
00705                           (trunc ? " [only first 256 bytes shown]" : ""));
00706             dStrHex((const char *)iop->dxferp,
00707                     (trunc ? 256 : iop->dxfer_len) , 1);
00708         }
00709         else
00710             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
00711         pout("%s", buff);
00712     }
00713     switch (iop->dxfer_dir) {
00714         case DXFER_NONE:
00715             wrk.inbufsize = 0;
00716             wrk.outbufsize = 0;
00717             break;
00718         case DXFER_FROM_DEVICE:
00719             wrk.inbufsize = 0;
00720             if (iop->dxfer_len > MAX_DXFER_LEN)
00721                 return -EINVAL;
00722             wrk.outbufsize = iop->dxfer_len;
00723             break;
00724         case DXFER_TO_DEVICE:
00725             if (iop->dxfer_len > MAX_DXFER_LEN)
00726                 return -EINVAL;
00727             memcpy(wrk.buff + buff_offset, iop->dxferp, iop->dxfer_len);
00728             wrk.inbufsize = iop->dxfer_len;
00729             wrk.outbufsize = 0;
00730             break;
00731         default:
00732             pout("do_scsi_cmnd_io: bad dxfer_dir\n");
00733             return -EINVAL;
00734     }
00735     iop->resp_sense_len = 0;
00736     iop->scsi_status = 0;
00737     iop->resid = 0;
00738     status = ioctl(dev_fd, SCSI_IOCTL_SEND_COMMAND, &wrk);
00739     if (-1 == status) {
00740         if (report)
00741             pout("  SCSI_IOCTL_SEND_COMMAND ioctl failed, errno=%d [%s]\n",
00742                  errno, strerror(errno));
00743         return -errno;
00744     }
00745     if (0 == status) {
00746         if (report > 0)
00747             pout("  status=0\n");
00748         if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
00749             memcpy(iop->dxferp, wrk.buff, iop->dxfer_len);
00750             if (report > 1) {
00751                 int trunc = (iop->dxfer_len > 256) ? 1 : 0;
00752 
00753                 pout("  Incoming data, len=%d%s:\n", (int)iop->dxfer_len,
00754                      (trunc ? " [only first 256 bytes shown]" : ""));
00755                 dStrHex((const char*)iop->dxferp,
00756                         (trunc ? 256 : iop->dxfer_len) , 1);
00757             }
00758         }
00759         return 0;
00760     }
00761     iop->scsi_status = status & 0x7e; /* bits 0 and 7 used to be for vendors */
00762     if (LSCSI_DRIVER_SENSE == ((status >> 24) & 0xf))
00763         iop->scsi_status = SCSI_STATUS_CHECK_CONDITION;
00764     len = (SEND_IOCTL_RESP_SENSE_LEN < iop->max_sense_len) ?
00765                 SEND_IOCTL_RESP_SENSE_LEN : iop->max_sense_len;
00766     if ((SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) &&
00767         iop->sensep && (len > 0)) {
00768         memcpy(iop->sensep, wrk.buff, len);
00769         iop->resp_sense_len = len;
00770         if (report > 1) {
00771             pout("  >>> Sense buffer, len=%d:\n", (int)len);
00772             dStrHex((const char *)wrk.buff, len , 1);
00773         }
00774     }
00775     if (report) {
00776         if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) {
00777             pout("  status=%x: sense_key=%x asc=%x ascq=%x\n", status & 0xff,
00778                  wrk.buff[2] & 0xf, wrk.buff[12], wrk.buff[13]);
00779         }
00780         else
00781             pout("  status=0x%x\n", status);
00782     }
00783     if (iop->scsi_status > 0)
00784         return 0;
00785     else {
00786         if (report > 0)
00787             pout("  ioctl status=0x%x but scsi status=0, fail with EIO\n",
00788                  status);
00789         return -EIO;      /* give up, assume no device there */
00790     }
00791 }
00792 
00793 /* SCSI command transmission interface function, linux version.
00794  * Returns 0 if SCSI command successfully launched and response
00795  * received. Even when 0 is returned the caller should check
00796  * scsi_cmnd_io::scsi_status for SCSI defined errors and warnings
00797  * (e.g. CHECK CONDITION). If the SCSI command could not be issued
00798  * (e.g. device not present or timeout) or some other problem
00799  * (e.g. timeout) then returns a negative errno value */
00800 static int do_normal_scsi_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop,
00801                                   int report)
00802 {
00803     int res;
00804 
00805     /* implementation relies on static sg_io_state variable. If not
00806      * previously set tries the SG_IO ioctl. If that succeeds assume
00807      * that SG_IO ioctl functional. If it fails with an errno value
00808      * other than ENODEV (no device) or permission then assume
00809      * SCSI_IOCTL_SEND_COMMAND is the only option. */
00810     switch (sg_io_state) {
00811     case SG_IO_PRESENT_UNKNOWN:
00812         /* ignore report argument */
00813         if (0 == (res = sg_io_cmnd_io(dev_fd, iop, report, 1))) {
00814             sg_io_state = SG_IO_PRESENT_YES;
00815             return 0;
00816         } else if ((-ENODEV == res) || (-EACCES == res) || (-EPERM == res))
00817             return res;         /* wait until we see a device */
00818         sg_io_state = SG_IO_PRESENT_NO;
00819         /* drop through by design */
00820     case SG_IO_PRESENT_NO:
00821         return sisc_cmnd_io(dev_fd, iop, report);
00822     case SG_IO_PRESENT_YES:
00823         return sg_io_cmnd_io(dev_fd, iop, report, 0);
00824     default:
00825         pout(">>>> do_scsi_cmnd_io: bad sg_io_state=%d\n", sg_io_state);
00826         sg_io_state = SG_IO_PRESENT_UNKNOWN;
00827         return -EIO;    /* report error and reset state */
00828     }
00829 }
00830 
00831 // >>>>>> End of general SCSI specific linux code
00832 
00833 /////////////////////////////////////////////////////////////////////////////
00834 /// Standard SCSI support
00835 
00836 class linux_scsi_device
00837 : public /*implements*/ scsi_device,
00838   public /*extends*/ linux_smart_device
00839 {
00840 public:
00841   linux_scsi_device(smart_interface * intf, const char * dev_name,
00842                     const char * req_type, bool scanning = false);
00843 
00844   virtual smart_device * autodetect_open();
00845 
00846   virtual bool scsi_pass_through(scsi_cmnd_io * iop);
00847 
00848 private:
00849   bool m_scanning; ///< true if created within scan_smart_devices
00850 };
00851 
00852 linux_scsi_device::linux_scsi_device(smart_interface * intf,
00853   const char * dev_name, const char * req_type, bool scanning /*= false*/)
00854 : smart_device(intf, dev_name, "scsi", req_type),
00855   // If opened with O_RDWR, a SATA disk in standby mode
00856   // may spin-up after device close().
00857   linux_smart_device(O_RDONLY | O_NONBLOCK),
00858   m_scanning(scanning)
00859 {
00860 }
00861 
00862 bool linux_scsi_device::scsi_pass_through(scsi_cmnd_io * iop)
00863 {
00864   int status = do_normal_scsi_cmnd_io(get_fd(), iop, scsi_debugmode);
00865   if (status < 0)
00866       return set_err(-status);
00867   return true;
00868 }
00869 
00870 /////////////////////////////////////////////////////////////////////////////
00871 /// PMC AacRAID support
00872 
00873 class linux_aacraid_device
00874 :public   scsi_device,
00875  public /*extends */   linux_smart_device
00876 {
00877 public:
00878   linux_aacraid_device(smart_interface *intf, const char *dev_name,
00879     unsigned int host, unsigned int channel, unsigned int device);
00880 
00881   virtual ~linux_aacraid_device() throw();
00882 
00883   virtual bool open();
00884 
00885   virtual bool scsi_pass_through(scsi_cmnd_io *iop);
00886 
00887 private:
00888   //Device Host number
00889   int aHost;
00890 
00891   //Channel(Lun) of the device
00892   int aLun;
00893 
00894   //Id of the device
00895   int aId;
00896 
00897 };
00898 
00899 linux_aacraid_device::linux_aacraid_device(smart_interface *intf,
00900   const char *dev_name, unsigned int host, unsigned int channel, unsigned int device)
00901    : smart_device(intf,dev_name,"aacraid","aacraid"),
00902      linux_smart_device(O_RDWR|O_NONBLOCK),
00903      aHost(host), aLun(channel), aId(device)
00904 {
00905   set_info().info_name = strprintf("%s [aacraid_disk_%02d_%02d_%d]",dev_name,aHost,aLun,aId);
00906   set_info().dev_type  = strprintf("aacraid,%d,%d,%d",aHost,aLun,aId);
00907 }
00908 
00909 linux_aacraid_device::~linux_aacraid_device() throw()
00910 {
00911 }
00912 
00913 bool linux_aacraid_device::open()
00914 {
00915   //Create the character device name based on the host number
00916   //Required for get stats from disks connected to different controllers
00917   char dev_name[128];
00918   snprintf(dev_name, sizeof(dev_name), "/dev/aac%d", aHost);
00919 
00920   //Initial open of dev name to check if it exsists
00921   int afd = ::open(dev_name,O_RDWR);
00922 
00923   if(afd < 0 && errno == ENOENT) {
00924 
00925     FILE *fp = fopen("/proc/devices","r");
00926     if(NULL == fp)
00927       return set_err(errno,"cannot open /proc/devices:%s",
00928                      strerror(errno));
00929 
00930     char line[256];
00931     int mjr = -1;
00932 
00933     while(fgets(line,sizeof(line),fp) !=NULL) {
00934       int nc = -1;
00935       if(sscanf(line,"%d aac%n",&mjr,&nc) == 1
00936                 && nc > 0 && '\n' == line[nc])
00937         break;
00938       mjr = -1;
00939     }
00940 
00941     //work with /proc/devices is done
00942     fclose(fp);
00943 
00944     if (mjr < 0)
00945       return set_err(ENOENT, "aac entry not found in /proc/devices");
00946 
00947     //Create misc device file in /dev/ used for communication with driver
00948     if(mknod(dev_name,S_IFCHR,makedev(mjr,aHost)))
00949       return set_err(errno,"cannot create %s:%s",dev_name,strerror(errno));
00950 
00951     afd = ::open(dev_name,O_RDWR);
00952   }
00953 
00954   if(afd < 0)
00955     return set_err(errno,"cannot open %s:%s",dev_name,strerror(errno));
00956 
00957   set_fd(afd);
00958   return true;
00959 }
00960 
00961 bool linux_aacraid_device::scsi_pass_through(scsi_cmnd_io *iop)
00962 {
00963   int report = scsi_debugmode;
00964 
00965   if (report > 0) {
00966     int k, j;
00967     const unsigned char * ucp = iop->cmnd;
00968     const char * np;
00969     char buff[256];
00970     const int sz = (int)sizeof(buff);
00971 
00972     np = scsi_get_opcode_name(ucp[0]);
00973     j  = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
00974     for (k = 0; k < (int)iop->cmnd_len; ++k)
00975       j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
00976       if ((report > 1) &&
00977         (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
00978         int trunc = (iop->dxfer_len > 256) ? 1 : 0;
00979 
00980         j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
00981                       "data, len=%d%s:\n", (int)iop->dxfer_len,
00982                       (trunc ? " [only first 256 bytes shown]" : ""));
00983         dStrHex((const char *)iop->dxferp,
00984                (trunc ? 256 : iop->dxfer_len) , 1);
00985     }
00986     else
00987       j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
00988 
00989     pout("%s", buff);
00990   }
00991 
00992 
00993   //return test commands
00994   if (iop->cmnd[0] == 0x00)
00995     return true;
00996 
00997   user_aac_reply *pReply;
00998 
00999   #ifdef ENVIRONMENT64
01000     // Create user 64 bit request
01001     user_aac_srb64  *pSrb;
01002     uint8_t aBuff[sizeof(user_aac_srb64) + sizeof(user_aac_reply)] = {0,};
01003 
01004     pSrb    = (user_aac_srb64*)aBuff;
01005     pReply  = (user_aac_reply*)(aBuff+sizeof(user_aac_srb64));
01006 
01007  #elif defined(ENVIRONMENT32)
01008     //Create user 32 bit request
01009     user_aac_srb32  *pSrb;
01010     uint8_t aBuff[sizeof(user_aac_srb32) + sizeof(user_aac_reply)] = {0,};
01011 
01012     pSrb    = (user_aac_srb32*)aBuff;
01013     pReply  = (user_aac_reply*)(aBuff+sizeof(user_aac_srb32));
01014 
01015  #endif
01016 
01017   pSrb->function = SRB_FUNCTION_EXECUTE_SCSI;
01018   //channel is 0 always
01019   pSrb->channel  = 0;
01020   pSrb->id       = aId;
01021   pSrb->lun      = aLun;
01022   pSrb->timeout  = 0;
01023 
01024   pSrb->retry_limit = 0;
01025   pSrb->cdb_size    = iop->cmnd_len;
01026 
01027   switch(iop->dxfer_dir) {
01028     case DXFER_NONE:
01029       pSrb->flags = SRB_NoDataXfer;
01030       break;
01031     case DXFER_FROM_DEVICE:
01032       pSrb->flags = SRB_DataIn;
01033       break;
01034     case DXFER_TO_DEVICE:
01035       pSrb->flags = SRB_DataOut;
01036       break;
01037     default:
01038       pout("aacraid: bad dxfer_dir\n");
01039       return set_err(EINVAL, "aacraid: bad dxfer_dir\n");
01040   }
01041 
01042   if(iop->dxfer_len > 0) {
01043 
01044     #ifdef ENVIRONMENT64
01045       pSrb->sg64.count = 1;
01046       pSrb->sg64.sg64[0].addr64.lo32 = ((intptr_t)iop->dxferp) &
01047                                          0x00000000ffffffff;
01048       pSrb->sg64.sg64[0].addr64.hi32 = ((intptr_t)iop->dxferp) >> 32;
01049 
01050       pSrb->sg64.sg64[0].length = (uint32_t)iop->dxfer_len;
01051       pSrb->count = sizeof(user_aac_srb64) +
01052                           (sizeof(user_sgentry64)*(pSrb->sg64.count-1));
01053     #elif defined(ENVIRONMENT32)
01054       pSrb->sg32.count = 1;
01055       pSrb->sg32.sg32[0].addr32 = (intptr_t)iop->dxferp;
01056 
01057       pSrb->sg32.sg32[0].length = (uint32_t)iop->dxfer_len;
01058       pSrb->count = sizeof(user_aac_srb32) +
01059                           (sizeof(user_sgentry32)*(pSrb->sg32.count-1));
01060     #endif
01061 
01062   }
01063 
01064   memcpy(pSrb->cdb,iop->cmnd,iop->cmnd_len);
01065 
01066   int rc = 0;
01067   errno = 0;
01068   rc = ioctl(get_fd(),FSACTL_SEND_RAW_SRB,pSrb);
01069   if(rc!= 0 || pReply->srb_status != 0x01) {
01070     if(pReply->srb_status == 0x08) {
01071       return set_err(EIO, "aacraid: Device %d %d does not exist\n" ,aLun,aId );
01072     }
01073   return set_err((errno ? errno : EIO), "aacraid result: %d.%d = %d/%d",
01074                             aLun, aId, errno,
01075                             pReply->srb_status);
01076   }
01077   return true;
01078 }
01079 
01080 
01081 /////////////////////////////////////////////////////////////////////////////
01082 /// LSI MegaRAID support
01083 
01084 class linux_megaraid_device
01085 : public /* implements */ scsi_device,
01086   public /* extends */ linux_smart_device
01087 {
01088 public:
01089   linux_megaraid_device(smart_interface *intf, const char *name, 
01090     unsigned int bus, unsigned int tgt);
01091 
01092   virtual ~linux_megaraid_device() throw();
01093 
01094   virtual smart_device * autodetect_open();
01095 
01096   virtual bool open();
01097   virtual bool close();
01098 
01099   virtual bool scsi_pass_through(scsi_cmnd_io *iop);
01100 
01101 private:
01102   unsigned int m_disknum;
01103   unsigned int m_busnum;
01104   unsigned int m_hba;
01105   int m_fd;
01106 
01107   bool (linux_megaraid_device::*pt_cmd)(int cdblen, void *cdb, int dataLen, void *data,
01108     int senseLen, void *sense, int report, int direction);
01109   bool megasas_cmd(int cdbLen, void *cdb, int dataLen, void *data,
01110     int senseLen, void *sense, int report, int direction);
01111   bool megadev_cmd(int cdbLen, void *cdb, int dataLen, void *data,
01112     int senseLen, void *sense, int report, int direction);
01113 };
01114 
01115 linux_megaraid_device::linux_megaraid_device(smart_interface *intf,
01116   const char *dev_name, unsigned int bus, unsigned int tgt)
01117  : smart_device(intf, dev_name, "megaraid", "megaraid"),
01118    linux_smart_device(O_RDWR | O_NONBLOCK),
01119    m_disknum(tgt), m_busnum(bus), m_hba(0),
01120    m_fd(-1), pt_cmd(0)
01121 {
01122   set_info().info_name = strprintf("%s [megaraid_disk_%02d]", dev_name, m_disknum);
01123   set_info().dev_type = strprintf("megaraid,%d", tgt);
01124 }
01125 
01126 linux_megaraid_device::~linux_megaraid_device() throw()
01127 {
01128   if (m_fd >= 0)
01129     ::close(m_fd);
01130 }
01131 
01132 smart_device * linux_megaraid_device::autodetect_open()
01133 {
01134   int report = scsi_debugmode;
01135 
01136   // Open device
01137   if (!open())
01138     return this;
01139 
01140   // The code below is based on smartd.cpp:SCSIFilterKnown()
01141   if (strcmp(get_req_type(), "megaraid"))
01142     return this;
01143 
01144   // Get INQUIRY
01145   unsigned char req_buff[64] = {0, };
01146   int req_len = 36;
01147   if (scsiStdInquiry(this, req_buff, req_len)) {
01148       close();
01149       set_err(EIO, "INQUIRY failed");
01150       return this;
01151   }
01152 
01153   int avail_len = req_buff[4] + 5;
01154   int len = (avail_len < req_len ? avail_len : req_len);
01155   if (len < 36)
01156       return this;
01157 
01158   if (report)
01159     pout("Got MegaRAID inquiry.. %s\n", req_buff+8);
01160 
01161   // Use INQUIRY to detect type
01162   {
01163     // SAT?
01164     ata_device * newdev = smi()->autodetect_sat_device(this, req_buff, len);
01165     if (newdev) // NOTE: 'this' is now owned by '*newdev'
01166       return newdev;
01167   }
01168 
01169   // Nothing special found
01170   return this;
01171 }
01172 
01173 bool linux_megaraid_device::open()
01174 {
01175   char line[128];
01176   int   mjr;
01177   int report = scsi_debugmode;
01178 
01179   if(sscanf(get_dev_name(),"/dev/bus/%d", &m_hba) == 0) {
01180     if (!linux_smart_device::open())
01181       return false;
01182     /* Get device HBA */
01183     struct sg_scsi_id sgid;
01184     if (ioctl(get_fd(), SG_GET_SCSI_ID, &sgid) == 0) {
01185       m_hba = sgid.host_no;
01186     }
01187     else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER, &m_hba) != 0) {
01188       int err = errno;
01189       linux_smart_device::close();
01190       return set_err(err, "can't get bus number");
01191     } // we dont need this device anymore
01192     linux_smart_device::close();
01193   }
01194   /* Perform mknod of device ioctl node */
01195   FILE * fp = fopen("/proc/devices", "r");
01196   while (fgets(line, sizeof(line), fp) != NULL) {
01197     int n1 = 0;
01198     if (sscanf(line, "%d megaraid_sas_ioctl%n", &mjr, &n1) == 1 && n1 == 22) {
01199       n1=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR, makedev(mjr, 0));
01200       if(report > 0)
01201         pout("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1 >= 0 ? 0 : errno);
01202       if (n1 >= 0 || errno == EEXIST)
01203         break;
01204     }
01205     else if (sscanf(line, "%d megadev%n", &mjr, &n1) == 1 && n1 == 11) {
01206       n1=mknod("/dev/megadev0", S_IFCHR, makedev(mjr, 0));
01207       if(report > 0)
01208         pout("Creating /dev/megadev0 = %d\n", n1 >= 0 ? 0 : errno);
01209       if (n1 >= 0 || errno == EEXIST)
01210         break;
01211     }
01212   }
01213   fclose(fp);
01214 
01215   /* Open Device IOCTL node */
01216   if ((m_fd = ::open("/dev/megaraid_sas_ioctl_node", O_RDWR)) >= 0) {
01217     pt_cmd = &linux_megaraid_device::megasas_cmd;
01218   }
01219   else if ((m_fd = ::open("/dev/megadev0", O_RDWR)) >= 0) {
01220     pt_cmd = &linux_megaraid_device::megadev_cmd;
01221   }
01222   else {
01223     int err = errno;
01224     linux_smart_device::close();
01225     return set_err(err, "cannot open /dev/megaraid_sas_ioctl_node or /dev/megadev0");
01226   }
01227   set_fd(m_fd);
01228   return true;
01229 }
01230 
01231 bool linux_megaraid_device::close()
01232 {
01233   if (m_fd >= 0)
01234     ::close(m_fd);
01235   m_fd = -1; m_hba = 0; pt_cmd = 0;
01236   set_fd(m_fd);
01237   return true;
01238 }
01239 
01240 bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io *iop)
01241 {
01242   int report = scsi_debugmode;
01243 
01244   if (report > 0) {
01245         int k, j;
01246         const unsigned char * ucp = iop->cmnd;
01247         const char * np;
01248         char buff[256];
01249         const int sz = (int)sizeof(buff);
01250 
01251         np = scsi_get_opcode_name(ucp[0]);
01252         j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
01253         for (k = 0; k < (int)iop->cmnd_len; ++k)
01254             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
01255         if ((report > 1) &&
01256             (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
01257             int trunc = (iop->dxfer_len > 256) ? 1 : 0;
01258 
01259             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
01260                           "data, len=%d%s:\n", (int)iop->dxfer_len,
01261                           (trunc ? " [only first 256 bytes shown]" : ""));
01262             dStrHex((const char *)iop->dxferp,
01263                     (trunc ? 256 : iop->dxfer_len) , 1);
01264         }
01265         else
01266             j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
01267         pout("%s", buff);
01268   }
01269 
01270   // Controller rejects Test Unit Ready
01271   if (iop->cmnd[0] == 0x00)
01272     return true;
01273 
01274   if (iop->cmnd[0] == SAT_ATA_PASSTHROUGH_12 || iop->cmnd[0] == SAT_ATA_PASSTHROUGH_16) { 
01275     // Controller does not return ATA output registers in SAT sense data
01276     if (iop->cmnd[2] & (1 << 5)) // chk_cond
01277       return set_err(ENOSYS, "ATA return descriptor not supported by controller firmware");
01278   }
01279   // SMART WRITE LOG SECTOR causing media errors
01280   if ((iop->cmnd[0] == SAT_ATA_PASSTHROUGH_16 // SAT16 WRITE LOG
01281       && iop->cmnd[14] == ATA_SMART_CMD && iop->cmnd[3]==0 && iop->cmnd[4] == ATA_SMART_WRITE_LOG_SECTOR) ||
01282       (iop->cmnd[0] == SAT_ATA_PASSTHROUGH_12 // SAT12 WRITE LOG
01283        && iop->cmnd[9] == ATA_SMART_CMD && iop->cmnd[3] == ATA_SMART_WRITE_LOG_SECTOR)) 
01284   {
01285     if(!failuretest_permissive)
01286        return set_err(ENOSYS, "SMART WRITE LOG SECTOR may cause problems, try with -T permissive to force"); 
01287   }
01288   if (pt_cmd == NULL)
01289     return false;
01290   return (this->*pt_cmd)(iop->cmnd_len, iop->cmnd,
01291     iop->dxfer_len, iop->dxferp,
01292     iop->max_sense_len, iop->sensep, report, iop->dxfer_dir);
01293 }
01294 
01295 /* Issue passthrough scsi command to PERC5/6 controllers */
01296 bool linux_megaraid_device::megasas_cmd(int cdbLen, void *cdb, 
01297   int dataLen, void *data,
01298   int /*senseLen*/, void * /*sense*/, int /*report*/, int dxfer_dir)
01299 {
01300   struct megasas_pthru_frame    *pthru;
01301   struct megasas_iocpacket      uio;
01302   int rc;
01303 
01304   memset(&uio, 0, sizeof(uio));
01305   pthru = &uio.frame.pthru;
01306   pthru->cmd = MFI_CMD_PD_SCSI_IO;
01307   pthru->cmd_status = 0xFF;
01308   pthru->scsi_status = 0x0;
01309   pthru->target_id = m_disknum;
01310   pthru->lun = 0;
01311   pthru->cdb_len = cdbLen;
01312   pthru->timeout = 0;
01313   switch (dxfer_dir) {
01314     case DXFER_NONE:
01315       pthru->flags = MFI_FRAME_DIR_NONE;
01316       break;
01317     case DXFER_FROM_DEVICE:
01318       pthru->flags = MFI_FRAME_DIR_READ;
01319       break;
01320     case DXFER_TO_DEVICE:
01321       pthru->flags = MFI_FRAME_DIR_WRITE;
01322       break;
01323     default:
01324       pout("megasas_cmd: bad dxfer_dir\n");
01325       return set_err(EINVAL, "megasas_cmd: bad dxfer_dir\n");
01326   }
01327 
01328   if (dataLen > 0) {
01329     pthru->sge_count = 1;
01330     pthru->data_xfer_len = dataLen;
01331     pthru->sgl.sge32[0].phys_addr = (intptr_t)data;
01332     pthru->sgl.sge32[0].length = (uint32_t)dataLen;
01333   }
01334   memcpy(pthru->cdb, cdb, cdbLen);
01335 
01336   uio.host_no = m_hba;
01337   if (dataLen > 0) {
01338     uio.sge_count = 1;
01339     uio.sgl_off = offsetof(struct megasas_pthru_frame, sgl);
01340     uio.sgl[0].iov_base = data;
01341     uio.sgl[0].iov_len = dataLen;
01342   }
01343 
01344   rc = 0;
01345   errno = 0;
01346   rc = ioctl(m_fd, MEGASAS_IOC_FIRMWARE, &uio);
01347   if (pthru->cmd_status || rc != 0) {
01348     if (pthru->cmd_status == 12) {
01349       return set_err(EIO, "megasas_cmd: Device %d does not exist\n", m_disknum);
01350     }
01351     return set_err((errno ? errno : EIO), "megasas_cmd result: %d.%d = %d/%d",
01352                    m_hba, m_disknum, errno,
01353                    pthru->cmd_status);
01354   }
01355   return true;
01356 }
01357 
01358 /* Issue passthrough scsi commands to PERC2/3/4 controllers */
01359 bool linux_megaraid_device::megadev_cmd(int cdbLen, void *cdb, 
01360   int dataLen, void *data,
01361   int /*senseLen*/, void * /*sense*/, int /*report*/, int /* dir */)
01362 {
01363   struct uioctl_t uio;
01364   int rc;
01365 
01366   /* Don't issue to the controller */
01367   if (m_disknum == 7)
01368     return false;
01369 
01370   memset(&uio, 0, sizeof(uio));
01371   uio.inlen  = dataLen;
01372   uio.outlen = dataLen;
01373 
01374   memset(data, 0, dataLen);
01375   uio.ui.fcs.opcode = 0x80;             // M_RD_IOCTL_CMD
01376   uio.ui.fcs.adapno = MKADAP(m_hba);
01377 
01378   uio.data.pointer = (uint8_t *)data;
01379 
01380   uio.mbox.cmd = MEGA_MBOXCMD_PASSTHRU;
01381   uio.mbox.xferaddr = (intptr_t)&uio.pthru;
01382 
01383   uio.pthru.ars     = 1;
01384   uio.pthru.timeout = 2;
01385   uio.pthru.channel = 0;
01386   uio.pthru.target  = m_disknum;
01387   uio.pthru.cdblen  = cdbLen;
01388   uio.pthru.reqsenselen  = MAX_REQ_SENSE_LEN;
01389   uio.pthru.dataxferaddr = (intptr_t)data;
01390   uio.pthru.dataxferlen  = dataLen;
01391   memcpy(uio.pthru.cdb, cdb, cdbLen);
01392 
01393   rc=ioctl(m_fd, MEGAIOCCMD, &uio);
01394   if (uio.pthru.scsistatus || rc != 0) {
01395     return set_err((errno ? errno : EIO), "megadev_cmd result: %d.%d =  %d/%d",
01396                    m_hba, m_disknum, errno,
01397                    uio.pthru.scsistatus);
01398   }
01399   return true;
01400 }
01401 
01402 /////////////////////////////////////////////////////////////////////////////
01403 /// CCISS RAID support
01404 
01405 #ifdef HAVE_LINUX_CCISS_IOCTL_H
01406 
01407 class linux_cciss_device
01408 : public /*implements*/ scsi_device,
01409   public /*extends*/ linux_smart_device
01410 {
01411 public:
01412   linux_cciss_device(smart_interface * intf, const char * name, unsigned char disknum);
01413 
01414   virtual bool scsi_pass_through(scsi_cmnd_io * iop);
01415 
01416 private:
01417   unsigned char m_disknum; ///< Disk number.
01418 };
01419 
01420 linux_cciss_device::linux_cciss_device(smart_interface * intf,
01421   const char * dev_name, unsigned char disknum)
01422 : smart_device(intf, dev_name, "cciss", "cciss"),
01423   linux_smart_device(O_RDWR | O_NONBLOCK),
01424   m_disknum(disknum)
01425 {
01426   set_info().info_name = strprintf("%s [cciss_disk_%02d]", dev_name, disknum);
01427 }
01428 
01429 bool linux_cciss_device::scsi_pass_through(scsi_cmnd_io * iop)
01430 {
01431   int status = cciss_io_interface(get_fd(), m_disknum, iop, scsi_debugmode);
01432   if (status < 0)
01433       return set_err(-status);
01434   return true;
01435 }
01436 
01437 #endif // HAVE_LINUX_CCISS_IOCTL_H
01438 
01439 /////////////////////////////////////////////////////////////////////////////
01440 /// AMCC/3ware RAID support
01441 
01442 class linux_escalade_device
01443 : public /*implements*/ ata_device,
01444   public /*extends*/ linux_smart_device
01445 {
01446 public:
01447   enum escalade_type_t {
01448     AMCC_3WARE_678K,
01449     AMCC_3WARE_678K_CHAR,
01450     AMCC_3WARE_9000_CHAR,
01451     AMCC_3WARE_9700_CHAR
01452   };
01453 
01454   linux_escalade_device(smart_interface * intf, const char * dev_name,
01455     escalade_type_t escalade_type, int disknum);
01456 
01457   virtual bool open();
01458 
01459   virtual bool ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out);
01460 
01461 private:
01462   escalade_type_t m_escalade_type; ///< Controller type
01463   int m_disknum; ///< Disk number.
01464 };
01465 
01466 linux_escalade_device::linux_escalade_device(smart_interface * intf, const char * dev_name,
01467     escalade_type_t escalade_type, int disknum)
01468 : smart_device(intf, dev_name, "3ware", "3ware"),
01469   linux_smart_device(O_RDONLY | O_NONBLOCK),
01470   m_escalade_type(escalade_type), m_disknum(disknum)
01471 {
01472   set_info().info_name = strprintf("%s [3ware_disk_%02d]", dev_name, disknum);
01473 }
01474 
01475 /* This function will setup and fix device nodes for a 3ware controller. */
01476 #define MAJOR_STRING_LENGTH 3
01477 #define DEVICE_STRING_LENGTH 32
01478 #define NODE_STRING_LENGTH 16
01479 static int setup_3ware_nodes(const char *nodename, const char *driver_name)
01480 {
01481   int              tw_major      = 0;
01482   int              index         = 0;
01483   char             majorstring[MAJOR_STRING_LENGTH+1];
01484   char             device_name[DEVICE_STRING_LENGTH+1];
01485   char             nodestring[NODE_STRING_LENGTH];
01486   struct stat      stat_buf;
01487   FILE             *file;
01488   int              retval = 0;
01489 #ifdef WITH_SELINUX
01490   security_context_t orig_context = NULL;
01491   security_context_t node_context = NULL;
01492   int                selinux_enabled  = is_selinux_enabled();
01493   int                selinux_enforced = security_getenforce();
01494 #endif
01495 
01496   /* First try to open up /proc/devices */
01497   if (!(file = fopen("/proc/devices", "r"))) {
01498     pout("Error opening /proc/devices to check/create 3ware device nodes\n");
01499     syserror("fopen");
01500     return 0;  // don't fail here: user might not have /proc !
01501   }
01502 
01503   /* Attempt to get device major number */
01504   while (EOF != fscanf(file, "%3s %32s", majorstring, device_name)) {
01505     majorstring[MAJOR_STRING_LENGTH]='\0';
01506     device_name[DEVICE_STRING_LENGTH]='\0';
01507     if (!strncmp(device_name, nodename, DEVICE_STRING_LENGTH)) {
01508       tw_major = atoi(majorstring);
01509       break;
01510     }
01511   }
01512   fclose(file);
01513 
01514   /* See if we found a major device number */
01515   if (!tw_major) {
01516     pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename, driver_name);
01517     return 2;
01518   }
01519 #ifdef WITH_SELINUX
01520   /* Prepare a database of contexts for files in /dev
01521    * and save the current context */
01522   if (selinux_enabled) {
01523     if (matchpathcon_init_prefix(NULL, "/dev") < 0)
01524       pout("Error initializing contexts database for /dev");
01525     if (getfscreatecon(&orig_context) < 0) {
01526       pout("Error retrieving original SELinux fscreate context");
01527       if (selinux_enforced)
01528         matchpathcon_fini();
01529         return 6;
01530       }
01531   }
01532 #endif
01533   /* Now check if nodes are correct */
01534   for (index=0; index<16; index++) {
01535     snprintf(nodestring, sizeof(nodestring), "/dev/%s%d", nodename, index);
01536 #ifdef WITH_SELINUX
01537     /* Get context of the node and set it as the default */
01538     if (selinux_enabled) {
01539       if (matchpathcon(nodestring, S_IRUSR | S_IWUSR, &node_context) < 0) {
01540         pout("Could not retrieve context for %s", nodestring);
01541         if (selinux_enforced) {
01542           retval = 6;
01543           break;
01544         }
01545       }
01546       if (setfscreatecon(node_context) < 0) {
01547         pout ("Error setting default fscreate context");
01548         if (selinux_enforced) {
01549           retval = 6;
01550           break;
01551         }
01552       }
01553     }
01554 #endif
01555     /* Try to stat the node */
01556     if ((stat(nodestring, &stat_buf))) {
01557       pout("Node %s does not exist and must be created. Check the udev rules.\n", nodestring);
01558       /* Create a new node if it doesn't exist */
01559       if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
01560         pout("problem creating 3ware device nodes %s", nodestring);
01561         syserror("mknod");
01562         retval = 3;
01563         break;
01564       } else {
01565 #ifdef WITH_SELINUX
01566         if (selinux_enabled && node_context) {
01567           freecon(node_context);
01568           node_context = NULL;
01569         }
01570 #endif
01571         continue;
01572       }
01573     }
01574 
01575     /* See if nodes major and minor numbers are correct */
01576     if ((tw_major != (int)(major(stat_buf.st_rdev))) ||
01577         (index    != (int)(minor(stat_buf.st_rdev))) ||
01578         (!S_ISCHR(stat_buf.st_mode))) {
01579       pout("Node %s has wrong major/minor number and must be created anew."
01580           " Check the udev rules.\n", nodestring);
01581       /* Delete the old node */
01582       if (unlink(nodestring)) {
01583         pout("problem unlinking stale 3ware device node %s", nodestring);
01584         syserror("unlink");
01585         retval = 4;
01586         break;
01587       }
01588 
01589       /* Make a new node */
01590       if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
01591         pout("problem creating 3ware device nodes %s", nodestring);
01592         syserror("mknod");
01593         retval = 5;
01594         break;
01595       }
01596     }
01597 #ifdef WITH_SELINUX
01598     if (selinux_enabled && node_context) {
01599       freecon(node_context);
01600       node_context = NULL;
01601     }
01602 #endif
01603   }
01604 
01605 #ifdef WITH_SELINUX
01606   if (selinux_enabled) {
01607     if(setfscreatecon(orig_context) < 0) {
01608       pout("Error re-setting original fscreate context");
01609       if (selinux_enforced)
01610         retval = 6;
01611     }
01612     if(orig_context)
01613       freecon(orig_context);
01614     if(node_context)
01615       freecon(node_context);
01616     matchpathcon_fini();
01617   }
01618 #endif
01619   return retval;
01620 }
01621 
01622 bool linux_escalade_device::open()
01623 {
01624   if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR ||
01625       m_escalade_type == AMCC_3WARE_678K_CHAR) {
01626     // the device nodes for these controllers are dynamically assigned,
01627     // so we need to check that they exist with the correct major
01628     // numbers and if not, create them
01629     const char * node   = (m_escalade_type == AMCC_3WARE_9700_CHAR ? "twl"     :
01630                            m_escalade_type == AMCC_3WARE_9000_CHAR ? "twa"     :
01631                                                                      "twe"      );
01632     const char * driver = (m_escalade_type == AMCC_3WARE_9700_CHAR ? "3w-sas"  :
01633                            m_escalade_type == AMCC_3WARE_9000_CHAR ? "3w-9xxx" :
01634                                                                      "3w-xxxx"  );
01635     if (setup_3ware_nodes(node, driver))
01636       return set_err((errno ? errno : ENXIO), "setup_3ware_nodes(\"%s\", \"%s\") failed", node, driver);
01637   }
01638   // Continue with default open
01639   return linux_smart_device::open();
01640 }
01641 
01642 // TODO: Function no longer useful
01643 //void printwarning(smart_command_set command);
01644 
01645 // PURPOSE
01646 //   This is an interface routine meant to isolate the OS dependent
01647 //   parts of the code, and to provide a debugging interface.  Each
01648 //   different port and OS needs to provide it's own interface.  This
01649 //   is the linux interface to the 3ware 3w-xxxx driver.  It allows ATA
01650 //   commands to be passed through the SCSI driver.
01651 // DETAILED DESCRIPTION OF ARGUMENTS
01652 //   fd: is the file descriptor provided by open()
01653 //   disknum is the disk number (0 to 15) in the RAID array
01654 //   escalade_type indicates the type of controller type, and if scsi or char interface is used
01655 //   command: defines the different operations.
01656 //   select: additional input data if needed (which log, which type of
01657 //           self-test).
01658 //   data:   location to write output data, if needed (512 bytes).
01659 //   Note: not all commands use all arguments.
01660 // RETURN VALUES
01661 //  -1 if the command failed
01662 //   0 if the command succeeded,
01663 //   STATUS_CHECK routine:
01664 //  -1 if the command failed
01665 //   0 if the command succeeded and disk SMART status is "OK"
01666 //   1 if the command succeeded and disk SMART status is "FAILING"
01667 
01668 /* 512 is the max payload size: increase if needed */
01669 #define BUFFER_LEN_678K      ( sizeof(TW_Ioctl)                  ) // 1044 unpacked, 1041 packed
01670 #define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1        ) // 1539 unpacked, 1536 packed
01671 #define BUFFER_LEN_9000      ( sizeof(TW_Ioctl_Buf_Apache)+512-1 ) // 2051 unpacked, 2048 packed
01672 #define TW_IOCTL_BUFFER_SIZE ( MAX(MAX(BUFFER_LEN_678K, BUFFER_LEN_9000), BUFFER_LEN_678K_CHAR) )
01673 
01674 bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out)
01675 {
01676   if (!ata_cmd_is_ok(in,
01677     true, // data_out_support
01678     false, // TODO: multi_sector_support
01679     true) // ata_48bit_support
01680   )
01681     return false;
01682 
01683   // Used by both the SCSI and char interfaces
01684   TW_Passthru *passthru=NULL;
01685   char ioctl_buffer[TW_IOCTL_BUFFER_SIZE];
01686 
01687   // only used for SCSI device interface
01688   TW_Ioctl   *tw_ioctl=NULL;
01689   TW_Output *tw_output=NULL;
01690 
01691   // only used for 6000/7000/8000 char device interface
01692   TW_New_Ioctl *tw_ioctl_char=NULL;
01693 
01694   // only used for 9000 character device interface
01695   TW_Ioctl_Buf_Apache *tw_ioctl_apache=NULL;
01696 
01697   memset(ioctl_buffer, 0, TW_IOCTL_BUFFER_SIZE);
01698 
01699   // TODO: Handle controller differences by different classes
01700   if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR) {
01701     tw_ioctl_apache                               = (TW_Ioctl_Buf_Apache *)ioctl_buffer;
01702     tw_ioctl_apache->driver_command.control_code  = TW_IOCTL_FIRMWARE_PASS_THROUGH;
01703     tw_ioctl_apache->driver_command.buffer_length = 512; /* payload size */
01704     passthru                                      = (TW_Passthru *)&(tw_ioctl_apache->firmware_command.command.oldcommand);
01705   }
01706   else if (m_escalade_type==AMCC_3WARE_678K_CHAR) {
01707     tw_ioctl_char                                 = (TW_New_Ioctl *)ioctl_buffer;
01708     tw_ioctl_char->data_buffer_length             = 512;
01709     passthru                                      = (TW_Passthru *)&(tw_ioctl_char->firmware_command);
01710   }
01711   else if (m_escalade_type==AMCC_3WARE_678K) {
01712     tw_ioctl                                      = (TW_Ioctl *)ioctl_buffer;
01713     tw_ioctl->cdb[0]                              = TW_IOCTL;
01714     tw_ioctl->opcode                              = TW_ATA_PASSTHRU;
01715     tw_ioctl->input_length                        = 512; // correct even for non-data commands
01716     tw_ioctl->output_length                       = 512; // correct even for non-data commands
01717     tw_output                                     = (TW_Output *)tw_ioctl;
01718     passthru                                      = (TW_Passthru *)&(tw_ioctl->input_data);
01719   }
01720   else {
01721     return set_err(ENOSYS,
01722       "Unrecognized escalade_type %d in linux_3ware_command_interface(disk %d)\n"
01723       "Please contact " PACKAGE_BUGREPORT "\n", (int)m_escalade_type, m_disknum);
01724   }
01725 
01726   // Same for (almost) all commands - but some reset below
01727   passthru->byte0.opcode  = TW_OP_ATA_PASSTHRU;
01728   passthru->request_id    = 0xFF;
01729   passthru->unit          = m_disknum;
01730   passthru->status        = 0;
01731   passthru->flags         = 0x1;
01732 
01733   // Set registers
01734   {
01735     const ata_in_regs_48bit & r = in.in_regs;
01736     passthru->features     = r.features_16;
01737     passthru->sector_count = r.sector_count_16;
01738     passthru->sector_num   = r.lba_low_16;
01739     passthru->cylinder_lo  = r.lba_mid_16;
01740     passthru->cylinder_hi  = r.lba_high_16;
01741     passthru->drive_head   = r.device;
01742     passthru->command      = r.command;
01743   }
01744 
01745   // Is this a command that reads or returns 512 bytes?
01746   // passthru->param values are:
01747   // 0x0 - non data command without TFR write check,
01748   // 0x8 - non data command with TFR write check,
01749   // 0xD - data command that returns data to host from device
01750   // 0xF - data command that writes data from host to device
01751   // passthru->size values are 0x5 for non-data and 0x07 for data
01752   bool readdata = false;
01753   if (in.direction == ata_cmd_in::data_in) {
01754     readdata=true;
01755     passthru->byte0.sgloff = 0x5;
01756     passthru->size         = 0x7; // TODO: Other value for multi-sector ?
01757     passthru->param        = 0xD;
01758     // For 64-bit to work correctly, up the size of the command packet
01759     // in dwords by 1 to account for the 64-bit single sgl 'address'
01760     // field. Note that this doesn't agree with the typedefs but it's
01761     // right (agree with kernel driver behavior/typedefs).
01762     if ((m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
01763         && sizeof(long) == 8)
01764       passthru->size++;
01765   }
01766   else if (in.direction == ata_cmd_in::no_data) {
01767     // Non data command -- but doesn't use large sector
01768     // count register values.
01769     passthru->byte0.sgloff = 0x0;
01770     passthru->size         = 0x5;
01771     passthru->param        = 0x8;
01772     passthru->sector_count = 0x0;
01773   }
01774   else if (in.direction == ata_cmd_in::data_out) {
01775     if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
01776       memcpy(tw_ioctl_apache->data_buffer, in.buffer, in.size);
01777     else if (m_escalade_type == AMCC_3WARE_678K_CHAR)
01778       memcpy(tw_ioctl_char->data_buffer,   in.buffer, in.size);
01779     else {
01780       // COMMAND NOT SUPPORTED VIA SCSI IOCTL INTERFACE
01781       // memcpy(tw_output->output_data, data, 512);
01782       // printwarning(command); // TODO: Parameter no longer valid
01783       return set_err(ENOTSUP, "DATA OUT not supported for this 3ware controller type");
01784     }
01785     passthru->byte0.sgloff = 0x5;
01786     passthru->size         = 0x7;  // TODO: Other value for multi-sector ?
01787     passthru->param        = 0xF;  // PIO data write
01788     if ((m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
01789         && sizeof(long) == 8)
01790       passthru->size++;
01791   }
01792   else
01793     return set_err(EINVAL);
01794 
01795   // Now send the command down through an ioctl()
01796   int ioctlreturn;
01797   if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
01798     ioctlreturn=ioctl(get_fd(), TW_IOCTL_FIRMWARE_PASS_THROUGH, tw_ioctl_apache);
01799   else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
01800     ioctlreturn=ioctl(get_fd(), TW_CMD_PACKET_WITH_DATA, tw_ioctl_char);
01801   else
01802     ioctlreturn=ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND, tw_ioctl);
01803 
01804   // Deal with the different error cases
01805   if (ioctlreturn) {
01806     if (AMCC_3WARE_678K==m_escalade_type
01807         && in.in_regs.command==ATA_SMART_CMD
01808         && (   in.in_regs.features == ATA_SMART_AUTO_OFFLINE
01809             || in.in_regs.features == ATA_SMART_AUTOSAVE    )
01810         && in.in_regs.lba_low) {
01811       // error here is probably a kernel driver whose version is too old
01812       // printwarning(command); // TODO: Parameter no longer valid
01813       return set_err(ENOTSUP, "Probably kernel driver too old");
01814     }
01815     return set_err(EIO);
01816   }
01817 
01818   // The passthru structure is valid after return from an ioctl if:
01819   // - we are using the character interface OR
01820   // - we are using the SCSI interface and this is a NON-READ-DATA command
01821   // For SCSI interface, note that we set passthru to a different
01822   // value after ioctl().
01823   if (AMCC_3WARE_678K==m_escalade_type) {
01824     if (readdata)
01825       passthru=NULL;
01826     else
01827       passthru=(TW_Passthru *)&(tw_output->output_data);
01828   }
01829 
01830   // See if the ATA command failed.  Now that we have returned from
01831   // the ioctl() call, if passthru is valid, then:
01832   // - passthru->status contains the 3ware controller STATUS
01833   // - passthru->command contains the ATA STATUS register
01834   // - passthru->features contains the ATA ERROR register
01835   //
01836   // Check bits 0 (error bit) and 5 (device fault) of the ATA STATUS
01837   // If bit 0 (error bit) is set, then ATA ERROR register is valid.
01838   // While we *might* decode the ATA ERROR register, at the moment it
01839   // doesn't make much sense: we don't care in detail why the error
01840   // happened.
01841 
01842   if (passthru && (passthru->status || (passthru->command & 0x21))) {
01843     return set_err(EIO);
01844   }
01845 
01846   // If this is a read data command, copy data to output buffer
01847   if (readdata) {
01848     if (m_escalade_type == AMCC_3WARE_9700_CHAR || m_escalade_type == AMCC_3WARE_9000_CHAR)
01849       memcpy(in.buffer, tw_ioctl_apache->data_buffer, in.size);
01850     else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
01851       memcpy(in.buffer, tw_ioctl_char->data_buffer, in.size);
01852     else
01853       memcpy(in.buffer, tw_output->output_data, in.size);
01854   }
01855 
01856   // Return register values
01857   if (passthru) {
01858     ata_out_regs_48bit & r = out.out_regs;
01859     r.error           = passthru->features;
01860     r.sector_count_16 = passthru->sector_count;
01861     r.lba_low_16      = passthru->sector_num;
01862     r.lba_mid_16      = passthru->cylinder_lo;
01863     r.lba_high_16     = passthru->cylinder_hi;
01864     r.device          = passthru->drive_head;
01865     r.status          = passthru->command;
01866   }
01867 
01868   // look for nonexistent devices/ports
01869   if (   in.in_regs.command == ATA_IDENTIFY_DEVICE
01870       && !nonempty(in.buffer, in.size)) {
01871     return set_err(ENODEV, "No drive on port %d", m_disknum);
01872   }
01873 
01874   return true;
01875 }
01876 
01877 /////////////////////////////////////////////////////////////////////////////
01878 /// Areca RAID support
01879 
01880 ///////////////////////////////////////////////////////////////////
01881 // SATA(ATA) device behind Areca RAID Controller
01882 class linux_areca_ata_device
01883 : public /*implements*/ areca_ata_device,
01884   public /*extends*/ linux_smart_device
01885 {
01886 public:
01887   linux_areca_ata_device(smart_interface * intf, const char * dev_name, int disknum, int encnum = 1);
01888   virtual smart_device * autodetect_open();
01889   virtual bool arcmsr_lock();
01890   virtual bool arcmsr_unlock();
01891   virtual int arcmsr_do_scsi_io(struct scsi_cmnd_io * iop);
01892 };
01893 
01894 ///////////////////////////////////////////////////////////////////
01895 // SAS(SCSI) device behind Areca RAID Controller
01896 class linux_areca_scsi_device
01897 : public /*implements*/ areca_scsi_device,
01898   public /*extends*/ linux_smart_device
01899 {
01900 public:
01901   linux_areca_scsi_device(smart_interface * intf, const char * dev_name, int disknum, int encnum = 1);
01902   virtual smart_device * autodetect_open();
01903   virtual bool arcmsr_lock();
01904   virtual bool arcmsr_unlock();
01905   virtual int arcmsr_do_scsi_io(struct scsi_cmnd_io * iop);
01906 };
01907 
01908 // Looks in /proc/scsi to suggest correct areca devices
01909 static int find_areca_in_proc()
01910 {
01911     const char* proc_format_string="host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n";
01912 
01913     // check data formwat
01914     FILE *fp=fopen("/proc/scsi/sg/device_hdr", "r");
01915     if (!fp) {
01916         pout("Unable to open /proc/scsi/sg/device_hdr for reading\n");
01917         return 1;
01918      }
01919 
01920      // get line, compare to format
01921      char linebuf[256];
01922      linebuf[255]='\0';
01923      char *out = fgets(linebuf, 256, fp);
01924      fclose(fp);
01925      if (!out) {
01926          pout("Unable to read contents of /proc/scsi/sg/device_hdr\n");
01927          return 2;
01928      }
01929 
01930      if (strcmp(linebuf, proc_format_string)) {
01931         // wrong format!
01932         // Fix this by comparing only tokens not white space!!
01933         pout("Unexpected format %s in /proc/scsi/sg/device_hdr\n", proc_format_string);
01934         return 3;
01935      }
01936 
01937     // Format is understood, now search for correct device
01938     fp=fopen("/proc/scsi/sg/devices", "r");
01939     if (!fp) return 1;
01940     int host, chan, id, lun, type, opens, qdepth, busy, online;
01941     int dev=-1;
01942     int found=0;
01943     // search all lines of /proc/scsi/sg/devices
01944     while (9 == fscanf(fp, "%d %d %d %d %d %d %d %d %d", &host, &chan, &id, &lun, &type, &opens, &qdepth, &busy, &online)) {
01945         dev++;
01946         if (id == 16 && type == 3) {
01947            // devices with id=16 and type=3 might be Areca controllers
01948            pout("Device /dev/sg%d appears to be an Areca controller.\n", dev);
01949            found++;
01950         }
01951     }
01952     fclose(fp);
01953     return 0;
01954 }
01955 
01956 // Areca RAID Controller(SATA Disk)
01957 linux_areca_ata_device::linux_areca_ata_device(smart_interface * intf, const char * dev_name, int disknum, int encnum)
01958 : smart_device(intf, dev_name, "areca", "areca"),
01959   linux_smart_device(O_RDWR | O_EXCL | O_NONBLOCK)
01960 {
01961   set_disknum(disknum);
01962   set_encnum(encnum);
01963   set_info().info_name = strprintf("%s [areca_disk#%02d_enc#%02d]", dev_name, disknum, encnum);
01964 }
01965 
01966 smart_device * linux_areca_ata_device::autodetect_open()
01967 {
01968   int is_ata = 1;
01969 
01970   // autodetect device type
01971   is_ata = arcmsr_get_dev_type();
01972   if(is_ata < 0)
01973   {
01974     set_err(EIO);
01975     return this;
01976   }
01977 
01978   if(is_ata == 1)
01979   {
01980     // SATA device
01981     return this;
01982   }
01983 
01984   // SAS device
01985   smart_device_auto_ptr newdev(new linux_areca_scsi_device(smi(), get_dev_name(), get_disknum(), get_encnum()));
01986   close();
01987   delete this;
01988   newdev->open();       // TODO: Can possibly pass open fd
01989 
01990   return newdev.release();
01991 }
01992 
01993 int linux_areca_ata_device::arcmsr_do_scsi_io(struct scsi_cmnd_io * iop)
01994 {
01995   int ioctlreturn = 0;
01996 
01997   if(!is_open()) {
01998       if(!open()){
01999           find_areca_in_proc();
02000       }
02001   }
02002 
02003   ioctlreturn = do_normal_scsi_cmnd_io(get_fd(), iop, scsi_debugmode);
02004   if ( ioctlreturn || iop->scsi_status )
02005   {
02006     // errors found
02007     return -1;
02008   }
02009 
02010   return ioctlreturn;
02011 }
02012 
02013 bool linux_areca_ata_device::arcmsr_lock()
02014 {
02015   return true;
02016 }
02017 
02018 bool linux_areca_ata_device::arcmsr_unlock()
02019 {
02020   return true;
02021 }
02022 
02023 // Areca RAID Controller(SAS Device)
02024 linux_areca_scsi_device::linux_areca_scsi_device(smart_interface * intf, const char * dev_name, int disknum, int encnum)
02025 : smart_device(intf, dev_name, "areca", "areca"),
02026   linux_smart_device(O_RDWR | O_EXCL | O_NONBLOCK)
02027 {
02028   set_disknum(disknum);
02029   set_encnum(encnum);
02030   set_info().info_name = strprintf("%s [areca_disk#%02d_enc#%02d]", dev_name, disknum, encnum);
02031 }
02032 
02033 smart_device * linux_areca_scsi_device::autodetect_open()
02034 {
02035   return this;
02036 }
02037 
02038 int linux_areca_scsi_device::arcmsr_do_scsi_io(struct scsi_cmnd_io * iop)
02039 {
02040   int ioctlreturn = 0;
02041 
02042   if(!is_open()) {
02043       if(!open()){
02044           find_areca_in_proc();
02045       }
02046   }
02047 
02048   ioctlreturn = do_normal_scsi_cmnd_io(get_fd(), iop, scsi_debugmode);
02049   if ( ioctlreturn || iop->scsi_status )
02050   {
02051     // errors found
02052     return -1;
02053   }
02054 
02055   return ioctlreturn;
02056 }
02057 
02058 bool linux_areca_scsi_device::arcmsr_lock()
02059 {
02060   return true;
02061 }
02062 
02063 bool linux_areca_scsi_device::arcmsr_unlock()
02064 {
02065   return true;
02066 }
02067 
02068 /////////////////////////////////////////////////////////////////////////////
02069 /// Marvell support
02070 
02071 class linux_marvell_device
02072 : public /*implements*/ ata_device_with_command_set,
02073   public /*extends*/ linux_smart_device
02074 {
02075 public:
02076   linux_marvell_device(smart_interface * intf, const char * dev_name, const char * req_type);
02077 
02078 protected:
02079   virtual int ata_command_interface(smart_command_set command, int select, char * data);
02080 };
02081 
02082 linux_marvell_device::linux_marvell_device(smart_interface * intf,
02083   const char * dev_name, const char * req_type)
02084 : smart_device(intf, dev_name, "marvell", req_type),
02085   linux_smart_device(O_RDONLY | O_NONBLOCK)
02086 {
02087 }
02088 
02089 int linux_marvell_device::ata_command_interface(smart_command_set command, int select, char * data)
02090 {
02091   typedef struct {
02092     int  inlen;
02093     int  outlen;
02094     char cmd[540];
02095   } mvsata_scsi_cmd;
02096 
02097   int copydata = 0;
02098   mvsata_scsi_cmd  smart_command;
02099   unsigned char *buff = (unsigned char *)&smart_command.cmd[6];
02100   // See struct hd_drive_cmd_hdr in hdreg.h
02101   // buff[0]: ATA COMMAND CODE REGISTER
02102   // buff[1]: ATA SECTOR NUMBER REGISTER
02103   // buff[2]: ATA FEATURES REGISTER
02104   // buff[3]: ATA SECTOR COUNT REGISTER
02105 
02106   // clear out buff.  Large enough for HDIO_DRIVE_CMD (4+512 bytes)
02107   memset(&smart_command, 0, sizeof(smart_command));
02108   smart_command.inlen = 540;
02109   smart_command.outlen = 540;
02110   smart_command.cmd[0] = 0xC;  //Vendor-specific code
02111   smart_command.cmd[4] = 6;     //command length
02112 
02113   buff[0] = ATA_SMART_CMD;
02114   switch (command){
02115   case CHECK_POWER_MODE:
02116     buff[0]=ATA_CHECK_POWER_MODE;
02117     break;
02118   case READ_VALUES:
02119     buff[2]=ATA_SMART_READ_VALUES;
02120     copydata=buff[3]=1;
02121     break;
02122   case READ_THRESHOLDS:
02123     buff[2]=ATA_SMART_READ_THRESHOLDS;
02124     copydata=buff[1]=buff[3]=1;
02125     break;
02126   case READ_LOG:
02127     buff[2]=ATA_SMART_READ_LOG_SECTOR;
02128     buff[1]=select;
02129     copydata=buff[3]=1;
02130     break;
02131   case IDENTIFY:
02132     buff[0]=ATA_IDENTIFY_DEVICE;
02133     copydata=buff[3]=1;
02134     break;
02135   case PIDENTIFY:
02136     buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
02137     copydata=buff[3]=1;
02138     break;
02139   case ENABLE:
02140     buff[2]=ATA_SMART_ENABLE;
02141     buff[1]=1;
02142     break;
02143   case DISABLE:
02144     buff[2]=ATA_SMART_DISABLE;
02145     buff[1]=1;
02146     break;
02147   case STATUS:
02148   case STATUS_CHECK:
02149     // this command only says if SMART is working.  It could be
02150     // replaced with STATUS_CHECK below.
02151     buff[2] = ATA_SMART_STATUS;
02152     break;
02153   case AUTO_OFFLINE:
02154     buff[2]=ATA_SMART_AUTO_OFFLINE;
02155     buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
02156     break;
02157   case AUTOSAVE:
02158     buff[2]=ATA_SMART_AUTOSAVE;
02159     buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
02160     break;
02161   case IMMEDIATE_OFFLINE:
02162     buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
02163     buff[1]=select;
02164     break;
02165   default:
02166     pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command);
02167     EXIT(1);
02168     break;
02169   }
02170   // There are two different types of ioctls().  The HDIO_DRIVE_TASK
02171   // one is this:
02172   // We are now doing the HDIO_DRIVE_CMD type ioctl.
02173   if (ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND, (void *)&smart_command))
02174       return -1;
02175 
02176   if (command==CHECK_POWER_MODE) {
02177     // LEON -- CHECK THIS PLEASE.  THIS SHOULD BE THE SECTOR COUNT
02178     // REGISTER, AND IT MIGHT BE buff[2] NOT buff[3].  Bruce
02179     data[0]=buff[3];
02180     return 0;
02181   }
02182 
02183   // Always succeed on a SMART status, as a disk that failed returned
02184   // buff[4]=0xF4, buff[5]=0x2C, i.e. "Bad SMART status" (see below).
02185   if (command == STATUS)
02186     return 0;
02187   //Data returned is starting from 0 offset
02188   if (command == STATUS_CHECK)
02189   {
02190     // Cyl low and Cyl high unchanged means "Good SMART status"
02191     if (buff[4] == 0x4F && buff[5] == 0xC2)
02192       return 0;
02193     // These values mean "Bad SMART status"
02194     if (buff[4] == 0xF4 && buff[5] == 0x2C)
02195       return 1;
02196     // We haven't gotten output that makes sense; print out some debugging info
02197     syserror("Error SMART Status command failed");
02198     pout("Please get assistance from %s\n",PACKAGE_BUGREPORT);
02199     pout("Register values returned from SMART Status command are:\n");
02200     pout("CMD =0x%02x\n",(int)buff[0]);
02201     pout("FR =0x%02x\n",(int)buff[1]);
02202     pout("NS =0x%02x\n",(int)buff[2]);
02203     pout("SC =0x%02x\n",(int)buff[3]);
02204     pout("CL =0x%02x\n",(int)buff[4]);
02205     pout("CH =0x%02x\n",(int)buff[5]);
02206     pout("SEL=0x%02x\n",(int)buff[6]);
02207     return -1;
02208   }
02209 
02210   if (copydata)
02211     memcpy(data, buff, 512);
02212   return 0;
02213 }
02214 
02215 /////////////////////////////////////////////////////////////////////////////
02216 /// Highpoint RAID support
02217 
02218 class linux_highpoint_device
02219 : public /*implements*/ ata_device_with_command_set,
02220   public /*extends*/ linux_smart_device
02221 {
02222 public:
02223   linux_highpoint_device(smart_interface * intf, const char * dev_name,
02224     unsigned char controller, unsigned char channel, unsigned char port);
02225 
02226 protected:
02227   virtual int ata_command_interface(smart_command_set command, int select, char * data);
02228 
02229 private:
02230   unsigned char m_hpt_data[3]; ///< controller/channel/port
02231 };
02232 
02233 linux_highpoint_device::linux_highpoint_device(smart_interface * intf, const char * dev_name,
02234   unsigned char controller, unsigned char channel, unsigned char port)
02235 : smart_device(intf, dev_name, "hpt", "hpt"),
02236   linux_smart_device(O_RDONLY | O_NONBLOCK)
02237 {
02238   m_hpt_data[0] = controller; m_hpt_data[1] = channel; m_hpt_data[2] = port;
02239   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]);
02240 }
02241 
02242 // this implementation is derived from ata_command_interface with a header
02243 // packing for highpoint linux driver ioctl interface
02244 //
02245 // ioctl(fd,HPTIO_CTL,buff)
02246 //          ^^^^^^^^^
02247 //
02248 // structure of hpt_buff
02249 // +----+----+----+----+--------------------.....---------------------+
02250 // | 1  | 2  | 3  | 4  | 5                                            |
02251 // +----+----+----+----+--------------------.....---------------------+
02252 //
02253 // 1: The target controller                     [ int    ( 4 Bytes ) ]
02254 // 2: The channel of the target controllee      [ int    ( 4 Bytes ) ]
02255 // 3: HDIO_ ioctl call                          [ int    ( 4 Bytes ) ]
02256 //    available from ${LINUX_KERNEL_SOURCE}/Documentation/ioctl/hdio
02257 // 4: the pmport that disk attached,            [ int    ( 4 Bytes ) ]
02258 //    if no pmport device, set to 1 or leave blank
02259 // 5: data                                      [ void * ( var leangth ) ]
02260 //
02261 #define STRANGE_BUFFER_LENGTH (4+512*0xf8)
02262 
02263 int linux_highpoint_device::ata_command_interface(smart_command_set command, int select, char * data)
02264 {
02265   unsigned char hpt_buff[4*sizeof(int) + STRANGE_BUFFER_LENGTH];
02266   unsigned int *hpt = (unsigned int *)hpt_buff;
02267   unsigned char *buff = &hpt_buff[4*sizeof(int)];
02268   int copydata = 0;
02269   const int HDIO_DRIVE_CMD_OFFSET = 4;
02270 
02271   memset(hpt_buff, 0, 4*sizeof(int) + STRANGE_BUFFER_LENGTH);
02272   hpt[0] = m_hpt_data[0]; // controller id
02273   hpt[1] = m_hpt_data[1]; // channel number
02274   hpt[3] = m_hpt_data[2]; // pmport number
02275 
02276   buff[0]=ATA_SMART_CMD;
02277   switch (command){
02278   case CHECK_POWER_MODE:
02279     buff[0]=ATA_CHECK_POWER_MODE;
02280     copydata=1;
02281     break;
02282   case READ_VALUES:
02283     buff[2]=ATA_SMART_READ_VALUES;
02284     buff[3]=1;
02285     copydata=512;
02286     break;
02287   case READ_THRESHOLDS:
02288     buff[2]=ATA_SMART_READ_THRESHOLDS;
02289     buff[1]=buff[3]=1;
02290     copydata=512;
02291     break;
02292   case READ_LOG:
02293     buff[2]=ATA_SMART_READ_LOG_SECTOR;
02294     buff[1]=select;
02295     buff[3]=1;
02296     copydata=512;
02297     break;
02298   case WRITE_LOG:
02299     break;
02300   case IDENTIFY:
02301     buff[0]=ATA_IDENTIFY_DEVICE;
02302     buff[3]=1;
02303     copydata=512;
02304     break;
02305   case PIDENTIFY:
02306     buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
02307     buff[3]=1;
02308     copydata=512;
02309     break;
02310   case ENABLE:
02311     buff[2]=ATA_SMART_ENABLE;
02312     buff[1]=1;
02313     break;
02314   case DISABLE:
02315     buff[2]=ATA_SMART_DISABLE;
02316     buff[1]=1;
02317     break;
02318   case STATUS:
02319     buff[2]=ATA_SMART_STATUS;
02320     break;
02321   case AUTO_OFFLINE:
02322     buff[2]=ATA_SMART_AUTO_OFFLINE;
02323     buff[3]=select;
02324     break;
02325   case AUTOSAVE:
02326     buff[2]=ATA_SMART_AUTOSAVE;
02327     buff[3]=select;
02328     break;
02329   case IMMEDIATE_OFFLINE:
02330     buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
02331     buff[1]=select;
02332     break;
02333   case STATUS_CHECK:
02334     buff[1]=ATA_SMART_STATUS;
02335     break;
02336   default:
02337     pout("Unrecognized command %d in linux_highpoint_command_interface()\n"
02338          "Please contact " PACKAGE_BUGREPORT "\n", command);
02339     errno=ENOSYS;
02340     return -1;
02341   }
02342 
02343   if (command==WRITE_LOG) {
02344     unsigned char task[4*sizeof(int)+sizeof(ide_task_request_t)+512];
02345     unsigned int *hpt_tf = (unsigned int *)task;
02346     ide_task_request_t *reqtask = (ide_task_request_t *)(&task[4*sizeof(int)]);
02347     task_struct_t *taskfile = (task_struct_t *)reqtask->io_ports;
02348     int retval;
02349 
02350     memset(task, 0, sizeof(task));
02351 
02352     hpt_tf[0] = m_hpt_data[0]; // controller id
02353     hpt_tf[1] = m_hpt_data[1]; // channel number
02354     hpt_tf[3] = m_hpt_data[2]; // pmport number
02355     hpt_tf[2] = HDIO_DRIVE_TASKFILE; // real hd ioctl
02356 
02357     taskfile->data           = 0;
02358     taskfile->feature        = ATA_SMART_WRITE_LOG_SECTOR;
02359     taskfile->sector_count   = 1;
02360     taskfile->sector_number  = select;
02361     taskfile->low_cylinder   = 0x4f;
02362     taskfile->high_cylinder  = 0xc2;
02363     taskfile->device_head    = 0;
02364     taskfile->command        = ATA_SMART_CMD;
02365 
02366     reqtask->data_phase      = TASKFILE_OUT;
02367     reqtask->req_cmd         = IDE_DRIVE_TASK_OUT;
02368     reqtask->out_size        = 512;
02369     reqtask->in_size         = 0;
02370 
02371     memcpy(task+sizeof(ide_task_request_t)+4*sizeof(int), data, 512);
02372 
02373     if ((retval=ioctl(get_fd(), HPTIO_CTL, task))) {
02374       if (retval==-EINVAL)
02375         pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
02376       return -1;
02377     }
02378     return 0;
02379   }
02380 
02381   if (command==STATUS_CHECK){
02382     int retval;
02383     unsigned const char normal_lo=0x4f, normal_hi=0xc2;
02384     unsigned const char failed_lo=0xf4, failed_hi=0x2c;
02385     buff[4]=normal_lo;
02386     buff[5]=normal_hi;
02387 
02388     hpt[2] = HDIO_DRIVE_TASK;
02389 
02390     if ((retval=ioctl(get_fd(), HPTIO_CTL, hpt_buff))) {
02391       if (retval==-EINVAL) {
02392         pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
02393         pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
02394       }
02395       else
02396         syserror("Error SMART Status command failed");
02397       return -1;
02398     }
02399 
02400     if (buff[4]==normal_lo && buff[5]==normal_hi)
02401       return 0;
02402 
02403     if (buff[4]==failed_lo && buff[5]==failed_hi)
02404       return 1;
02405 
02406     syserror("Error SMART Status command failed");
02407     pout("Please get assistance from " PACKAGE_HOMEPAGE "\n");
02408     pout("Register values returned from SMART Status command are:\n");
02409     pout("CMD=0x%02x\n",(int)buff[0]);
02410     pout("FR =0x%02x\n",(int)buff[1]);
02411     pout("NS =0x%02x\n",(int)buff[2]);
02412     pout("SC =0x%02x\n",(int)buff[3]);
02413     pout("CL =0x%02x\n",(int)buff[4]);
02414     pout("CH =0x%02x\n",(int)buff[5]);
02415     pout("SEL=0x%02x\n",(int)buff[6]);
02416     return -1;
02417   }
02418 
02419 #if 1
02420   if (command==IDENTIFY || command==PIDENTIFY) {
02421     unsigned char deviceid[4*sizeof(int)+512*sizeof(char)];
02422     unsigned int *hpt_id = (unsigned int *)deviceid;
02423 
02424     hpt_id[0] = m_hpt_data[0]; // controller id
02425     hpt_id[1] = m_hpt_data[1]; // channel number
02426     hpt_id[3] = m_hpt_data[2]; // pmport number
02427 
02428     hpt_id[2] = HDIO_GET_IDENTITY;
02429     if (!ioctl(get_fd(), HPTIO_CTL, deviceid) && (deviceid[4*sizeof(int)] & 0x8000))
02430       buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
02431   }
02432 #endif
02433 
02434   hpt[2] = HDIO_DRIVE_CMD;
02435   if ((ioctl(get_fd(), HPTIO_CTL, hpt_buff)))
02436     return -1;
02437 
02438   if (command==CHECK_POWER_MODE)
02439     buff[HDIO_DRIVE_CMD_OFFSET]=buff[2];
02440 
02441   if (copydata)
02442     memcpy(data, buff+HDIO_DRIVE_CMD_OFFSET, copydata);
02443 
02444   return 0;
02445 }
02446 
02447 #if 0 // TODO: Migrate from 'smart_command_set' to 'ata_in_regs' OR remove the function
02448 // Utility function for printing warnings
02449 void printwarning(smart_command_set command){
02450   static int printed[4]={0,0,0,0};
02451   const char* message=
02452     "can not be passed through the 3ware 3w-xxxx driver.  This can be fixed by\n"
02453     "applying a simple 3w-xxxx driver patch that can be found here:\n"
02454     PACKAGE_HOMEPAGE "\n"
02455     "Alternatively, upgrade your 3w-xxxx driver to version 1.02.00.037 or greater.\n\n";
02456 
02457   if (command==AUTO_OFFLINE && !printed[0]) {
02458     printed[0]=1;
02459     pout("The SMART AUTO-OFFLINE ENABLE command (smartmontools -o on option/Directive)\n%s", message);
02460   }
02461   else if (command==AUTOSAVE && !printed[1]) {
02462     printed[1]=1;
02463     pout("The SMART AUTOSAVE ENABLE command (smartmontools -S on option/Directive)\n%s", message);
02464   }
02465   else if (command==STATUS_CHECK && !printed[2]) {
02466     printed[2]=1;
02467     pout("The SMART RETURN STATUS return value (smartmontools -H option/Directive)\n%s", message);
02468   }
02469   else if (command==WRITE_LOG && !printed[3])  {
02470     printed[3]=1;
02471     pout("The SMART WRITE LOG command (smartmontools -t selective) only supported via char /dev/tw[ae] interface\n");
02472   }
02473 
02474   return;
02475 }
02476 #endif
02477 
02478 /////////////////////////////////////////////////////////////////////////////
02479 /// SCSI open with autodetection support
02480 
02481 smart_device * linux_scsi_device::autodetect_open()
02482 {
02483   // Open device
02484   if (!open())
02485     return this;
02486 
02487   // No Autodetection if device type was specified by user
02488   bool sat_only = false;
02489   if (*get_req_type()) {
02490     // Detect SAT if device object was created by scan_smart_devices().
02491     if (!(m_scanning && !strcmp(get_req_type(), "sat")))
02492       return this;
02493     sat_only = true;
02494   }
02495 
02496   // The code below is based on smartd.cpp:SCSIFilterKnown()
02497 
02498   // Get INQUIRY
02499   unsigned char req_buff[64] = {0, };
02500   int req_len = 36;
02501   if (scsiStdInquiry(this, req_buff, req_len)) {
02502     // Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices
02503     // watch this spot ... other devices could lock up here
02504     req_len = 64;
02505     if (scsiStdInquiry(this, req_buff, req_len)) {
02506       // device doesn't like INQUIRY commands
02507       close();
02508       set_err(EIO, "INQUIRY failed");
02509       return this;
02510     }
02511   }
02512 
02513   int avail_len = req_buff[4] + 5;
02514   int len = (avail_len < req_len ? avail_len : req_len);
02515   if (len < 36) {
02516     if (sat_only) {
02517       close();
02518       set_err(EIO, "INQUIRY too short for SAT");
02519     }
02520     return this;
02521   }
02522 
02523   // Use INQUIRY to detect type
02524   if (!sat_only) {
02525 
02526     // 3ware ?
02527     if (!memcmp(req_buff + 8, "3ware", 5) || !memcmp(req_buff + 8, "AMCC", 4)) {
02528       close();
02529       set_err(EINVAL, "AMCC/3ware controller, please try adding '-d 3ware,N',\n"
02530                       "you may need to replace %s with /dev/twlN, /dev/twaN or /dev/tweN", get_dev_name());
02531       return this;
02532     }
02533 
02534     // DELL?
02535     if (!memcmp(req_buff + 8, "DELL    PERC", 12) || !memcmp(req_buff + 8, "MegaRAID", 8)
02536         || !memcmp(req_buff + 16, "PERC H700", 9) || !memcmp(req_buff + 8, "LSI\0",4)
02537     ) {
02538       close();
02539       set_err(EINVAL, "DELL or MegaRaid controller, please try adding '-d megaraid,N'");
02540       return this;
02541     }
02542 
02543     // Marvell ?
02544     if (len >= 42 && !memcmp(req_buff + 36, "MVSATA", 6)) {
02545       //pout("Device %s: using '-d marvell' for ATA disk with Marvell driver\n", get_dev_name());
02546       close();
02547       smart_device_auto_ptr newdev(
02548         new linux_marvell_device(smi(), get_dev_name(), get_req_type())
02549       );
02550       newdev->open(); // TODO: Can possibly pass open fd
02551       delete this;
02552       return newdev.release();
02553     }
02554   }
02555 
02556   // SAT or USB ?
02557   {
02558     smart_device * newdev = smi()->autodetect_sat_device(this, req_buff, len);
02559     if (newdev)
02560       // NOTE: 'this' is now owned by '*newdev'
02561       return newdev;
02562   }
02563 
02564   // Nothing special found
02565 
02566   if (sat_only) {
02567     close();
02568     set_err(EIO, "Not a SAT device");
02569   }
02570   return this;
02571 }
02572 
02573 //////////////////////////////////////////////////////////////////////
02574 // USB bridge ID detection
02575 
02576 // Read USB ID from /sys file
02577 static bool read_id(const std::string & path, unsigned short & id)
02578 {
02579   FILE * f = fopen(path.c_str(), "r");
02580   if (!f)
02581     return false;
02582   int n = -1;
02583   bool ok = (fscanf(f, "%hx%n", &id, &n) == 1 && n == 4);
02584   fclose(f);
02585   return ok;
02586 }
02587 
02588 // Get USB bridge ID for "sdX"
02589 static bool get_usb_id(const char * name, unsigned short & vendor_id,
02590                        unsigned short & product_id, unsigned short & version)
02591 {
02592   // Only "sdX" supported
02593   if (!(!strncmp(name, "sd", 2) && !strchr(name, '/')))
02594     return false;
02595 
02596   // Start search at dir referenced by symlink "/sys/block/sdX/device"
02597   // -> "/sys/devices/.../usb*/.../host*/target*/..."
02598   std::string dir = strprintf("/sys/block/%s/device", name);
02599 
02600   // Stop search at "/sys/devices"
02601   struct stat st;
02602   if (stat("/sys/devices", &st))
02603     return false;
02604   ino_t stop_ino = st.st_ino;
02605 
02606   // Search in parent directories until "idVendor" is found,
02607   // fail if "/sys/devices" reached or too many iterations
02608   int cnt = 0;
02609   do {
02610     dir += "/..";
02611     if (!(++cnt < 10 && !stat(dir.c_str(), &st) && st.st_ino != stop_ino))
02612       return false;
02613   } while (access((dir + "/idVendor").c_str(), 0));
02614 
02615   // Read IDs
02616   if (!(   read_id(dir + "/idVendor", vendor_id)
02617         && read_id(dir + "/idProduct", product_id)
02618         && read_id(dir + "/bcdDevice", version)   ))
02619     return false;
02620 
02621   if (scsi_debugmode > 1)
02622     pout("USB ID = 0x%04x:0x%04x (0x%03x)\n", vendor_id, product_id, version);
02623   return true;
02624 }
02625 
02626 //////////////////////////////////////////////////////////////////////
02627 /// Linux interface
02628 
02629 class linux_smart_interface
02630 : public /*implements*/ smart_interface
02631 {
02632 public:
02633   virtual std::string get_os_version_str();
02634 
02635   virtual std::string get_app_examples(const char * appname);
02636 
02637   virtual bool scan_smart_devices(smart_device_list & devlist, const char * type,
02638     const char * pattern = 0);
02639 
02640 protected:
02641   virtual ata_device * get_ata_device(const char * name, const char * type);
02642 
02643   virtual scsi_device * get_scsi_device(const char * name, const char * type);
02644 
02645   virtual smart_device * autodetect_smart_device(const char * name);
02646 
02647   virtual smart_device * get_custom_smart_device(const char * name, const char * type);
02648 
02649   virtual std::string get_valid_custom_dev_types_str();
02650 
02651 private:
02652   bool get_dev_list(smart_device_list & devlist, const char * pattern,
02653     bool scan_ata, bool scan_scsi, const char * req_type, bool autodetect);
02654   bool get_dev_megasas(smart_device_list & devlist);
02655   smart_device * missing_option(const char * opt);
02656   int megasas_dcmd_cmd(int bus_no, uint32_t opcode, void *buf,
02657     size_t bufsize, uint8_t *mbox, size_t mboxlen, uint8_t *statusp);
02658   int megasas_pd_add_list(int bus_no, smart_device_list & devlist);
02659 };
02660 
02661 std::string linux_smart_interface::get_os_version_str()
02662 {
02663   struct utsname u;
02664   if (!uname(&u))
02665     return strprintf("%s-linux-%s", u.machine, u.release);
02666   else
02667     return SMARTMONTOOLS_BUILD_HOST;
02668 }
02669 
02670 std::string linux_smart_interface::get_app_examples(const char * appname)
02671 {
02672   if (!strcmp(appname, "smartctl"))
02673     return smartctl_examples;
02674   return "";
02675 }
02676 
02677 // we are going to take advantage of the fact that Linux's devfs will only
02678 // have device entries for devices that exist.  So if we get the equivalent of
02679 // ls /dev/hd[a-t], we have all the ATA devices on the system
02680 bool linux_smart_interface::get_dev_list(smart_device_list & devlist,
02681   const char * pattern, bool scan_ata, bool scan_scsi,
02682   const char * req_type, bool autodetect)
02683 {
02684   // Use glob to look for any directory entries matching the pattern
02685   glob_t globbuf;
02686   memset(&globbuf, 0, sizeof(globbuf));
02687   int retglob = glob(pattern, GLOB_ERR, NULL, &globbuf);
02688   if (retglob) {
02689     //  glob failed: free memory and return
02690     globfree(&globbuf);
02691 
02692     if (retglob==GLOB_NOMATCH){
02693       pout("glob(3) found no matches for pattern %s\n", pattern);
02694       return true;
02695     }
02696 
02697     if (retglob==GLOB_NOSPACE)
02698       set_err(ENOMEM, "glob(3) ran out of memory matching pattern %s", pattern);
02699 #ifdef GLOB_ABORTED // missing in old versions of glob.h
02700     else if (retglob==GLOB_ABORTED)
02701       set_err(EINVAL, "glob(3) aborted matching pattern %s", pattern);
02702 #endif
02703     else
02704       set_err(EINVAL, "Unexplained error in glob(3) of pattern %s", pattern);
02705 
02706     return false;
02707   }
02708 
02709   // did we find too many paths?
02710   const int max_pathc = 1024;
02711   int n = (int)globbuf.gl_pathc;
02712   if (n > max_pathc) {
02713     pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n",
02714          n, max_pathc, pattern, n - max_pathc);
02715     n = max_pathc;
02716   }
02717 
02718   // now step through the list returned by glob.  If not a link, copy
02719   // to list.  If it is a link, evaluate it and see if the path ends
02720   // in "disc".
02721   for (int i = 0; i < n; i++){
02722     // see if path is a link
02723     char linkbuf[1024];
02724     int retlink = readlink(globbuf.gl_pathv[i], linkbuf, sizeof(linkbuf)-1);
02725 
02726     char tmpname[1024]={0};
02727     const char * name = 0;
02728     bool is_scsi = scan_scsi;
02729     // if not a link (or a strange link), keep it
02730     if (retlink<=0 || retlink>1023)
02731       name = globbuf.gl_pathv[i];
02732     else {
02733       // or if it's a link that points to a disc, follow it
02734       linkbuf[retlink] = 0;
02735       const char *p;
02736       if ((p=strrchr(linkbuf, '/')) && !strcmp(p+1, "disc"))
02737         // This is the branch of the code that gets followed if we are
02738         // using devfs WITH traditional compatibility links. In this
02739         // case, we add the traditional device name to the list that
02740         // is returned.
02741         name = globbuf.gl_pathv[i];
02742       else {
02743         // This is the branch of the code that gets followed if we are
02744         // using devfs WITHOUT traditional compatibility links.  In
02745         // this case, we check that the link to the directory is of
02746         // the correct type, and then append "disc" to it.
02747         bool match_ata  = strstr(linkbuf, "ide");
02748         bool match_scsi = strstr(linkbuf, "scsi");
02749         if (((match_ata && scan_ata) || (match_scsi && scan_scsi)) && !(match_ata && match_scsi)) {
02750           is_scsi = match_scsi;
02751           snprintf(tmpname, sizeof(tmpname), "%s/disc", globbuf.gl_pathv[i]);
02752           name = tmpname;
02753         }
02754       }
02755     }
02756 
02757     if (name) {
02758       // Found a name, add device to list.
02759       smart_device * dev;
02760       if (autodetect)
02761         dev = autodetect_smart_device(name);
02762       else if (is_scsi)
02763         dev = new linux_scsi_device(this, name, req_type, true /*scanning*/);
02764       else
02765         dev = new linux_ata_device(this, name, req_type);
02766       if (dev) // autodetect_smart_device() may return nullptr.
02767         devlist.push_back(dev);
02768     }
02769   }
02770 
02771   // free memory
02772   globfree(&globbuf);
02773   return true;
02774 }
02775 
02776 // getting devices from LSI SAS MegaRaid, if available
02777 bool linux_smart_interface::get_dev_megasas(smart_device_list & devlist)
02778 {
02779   /* Scanning of disks on MegaRaid device */
02780   /* Perform mknod of device ioctl node */
02781   int   mjr, n1;
02782   char line[128];
02783   bool scan_megasas = false;
02784   FILE * fp = fopen("/proc/devices", "r");
02785   while (fgets(line, sizeof(line), fp) != NULL) {
02786     n1=0;
02787     if (sscanf(line, "%d megaraid_sas_ioctl%n", &mjr, &n1) == 1 && n1 == 22) {
02788       scan_megasas = true;
02789       n1=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR, makedev(mjr, 0));
02790       if(scsi_debugmode > 0)
02791         pout("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1 >= 0 ? 0 : errno);
02792       if (n1 >= 0 || errno == EEXIST)
02793         break;
02794     }
02795   }
02796   fclose(fp);
02797 
02798   if(!scan_megasas)
02799     return false;
02800 
02801   // getting bus numbers with megasas devices
02802   struct dirent *ep;
02803   unsigned int host_no = 0;
02804   char sysfsdir[256];
02805 
02806   /* we are using sysfs to get list of all scsi hosts */
02807   DIR * dp = opendir ("/sys/class/scsi_host/");
02808   if (dp != NULL)
02809   {
02810     while ((ep = readdir (dp)) != NULL) {
02811       if (!sscanf(ep->d_name, "host%d", &host_no)) 
02812         continue;
02813       /* proc_name should be megaraid_sas */
02814       snprintf(sysfsdir, sizeof(sysfsdir) - 1,
02815         "/sys/class/scsi_host/host%d/proc_name", host_no);
02816       if((fp = fopen(sysfsdir, "r")) == NULL)
02817         continue;
02818       if(fgets(line, sizeof(line), fp) != NULL && !strncmp(line,"megaraid_sas",12)) {
02819         megasas_pd_add_list(host_no, devlist);
02820       }
02821       fclose(fp);
02822     }
02823     (void) closedir (dp);
02824   } else { /* sysfs not mounted ? */
02825     for(unsigned i = 0; i <=16; i++) // trying to add devices on first 16 buses
02826       megasas_pd_add_list(i, devlist);
02827   }
02828   return true;
02829 }
02830 
02831 bool linux_smart_interface::scan_smart_devices(smart_device_list & devlist,
02832   const char * type, const char * pattern /*= 0*/)
02833 {
02834   if (pattern) {
02835     set_err(EINVAL, "DEVICESCAN with pattern not implemented yet");
02836     return false;
02837   }
02838 
02839   if (!type)
02840     type = "";
02841 
02842   bool scan_ata  = (!*type || !strcmp(type, "ata" ));
02843   // "sat" detection will be later handled in linux_scsi_device::autodetect_open()
02844   bool scan_scsi = (!*type || !strcmp(type, "scsi") || !strcmp(type, "sat"));
02845   if (!(scan_ata || scan_scsi))
02846     return true;
02847 
02848   if (scan_ata)
02849     get_dev_list(devlist, "/dev/hd[a-t]", true, false, type, false);
02850   if (scan_scsi) {
02851     bool autodetect = !*type; // Try USB autodetection if no type specifed
02852     get_dev_list(devlist, "/dev/sd[a-z]", false, true, type, autodetect);
02853     // Support up to 104 devices
02854     get_dev_list(devlist, "/dev/sd[a-c][a-z]", false, true, type, autodetect);
02855     // get device list from the megaraid device
02856     get_dev_megasas(devlist);
02857   }
02858 
02859   // if we found traditional links, we are done
02860   if (devlist.size() > 0)
02861     return true;
02862 
02863   // else look for devfs entries without traditional links
02864   // TODO: Add udev support
02865   return get_dev_list(devlist, "/dev/discs/disc*", scan_ata, scan_scsi, type, false);
02866 }
02867 
02868 ata_device * linux_smart_interface::get_ata_device(const char * name, const char * type)
02869 {
02870   return new linux_ata_device(this, name, type);
02871 }
02872 
02873 scsi_device * linux_smart_interface::get_scsi_device(const char * name, const char * type)
02874 {
02875   return new linux_scsi_device(this, name, type);
02876 }
02877 
02878 smart_device * linux_smart_interface::missing_option(const char * opt)
02879 {
02880   set_err(EINVAL, "requires option '%s'", opt);
02881   return 0;
02882 }
02883 
02884 int
02885 linux_smart_interface::megasas_dcmd_cmd(int bus_no, uint32_t opcode, void *buf,
02886   size_t bufsize, uint8_t *mbox, size_t mboxlen, uint8_t *statusp)
02887 {
02888   struct megasas_iocpacket ioc;
02889 
02890   if ((mbox != NULL && (mboxlen == 0 || mboxlen > MFI_MBOX_SIZE)) ||
02891     (mbox == NULL && mboxlen != 0)) 
02892   {
02893     errno = EINVAL;
02894     return (-1);
02895   }
02896 
02897   bzero(&ioc, sizeof(ioc));
02898   struct megasas_dcmd_frame * dcmd = &ioc.frame.dcmd;
02899   ioc.host_no = bus_no;
02900   if (mbox)
02901     bcopy(mbox, dcmd->mbox.w, mboxlen);
02902   dcmd->cmd = MFI_CMD_DCMD;
02903   dcmd->timeout = 0;
02904   dcmd->flags = 0;
02905   dcmd->data_xfer_len = bufsize;
02906   dcmd->opcode = opcode;
02907 
02908   if (bufsize > 0) {
02909     dcmd->sge_count = 1;
02910     dcmd->data_xfer_len = bufsize;
02911     dcmd->sgl.sge32[0].phys_addr = (intptr_t)buf;
02912     dcmd->sgl.sge32[0].length = (uint32_t)bufsize;
02913     ioc.sge_count = 1;
02914     ioc.sgl_off = offsetof(struct megasas_dcmd_frame, sgl);
02915     ioc.sgl[0].iov_base = buf;
02916     ioc.sgl[0].iov_len = bufsize;
02917   }
02918 
02919   int fd;
02920   if ((fd = ::open("/dev/megaraid_sas_ioctl_node", O_RDWR)) <= 0) {
02921     return (errno);
02922   }
02923 
02924   int r = ioctl(fd, MEGASAS_IOC_FIRMWARE, &ioc);
02925   if (r < 0) {
02926     return (r);
02927   }
02928 
02929   if (statusp != NULL)
02930     *statusp = dcmd->cmd_status;
02931   else if (dcmd->cmd_status != MFI_STAT_OK) {
02932     fprintf(stderr, "command %x returned error status %x\n",
02933       opcode, dcmd->cmd_status);
02934     errno = EIO;
02935     return (-1);
02936   }
02937   return (0);
02938 }
02939 
02940 int
02941 linux_smart_interface::megasas_pd_add_list(int bus_no, smart_device_list & devlist)
02942 {
02943   /*
02944   * Keep fetching the list in a loop until we have a large enough
02945   * buffer to hold the entire list.
02946   */
02947   megasas_pd_list * list = 0;
02948   for (unsigned list_size = 1024; ; ) {
02949     list = (megasas_pd_list *)realloc(list, list_size);
02950     if (!list)
02951       throw std::bad_alloc();
02952     bzero(list, list_size);
02953     if (megasas_dcmd_cmd(bus_no, MFI_DCMD_PD_GET_LIST, list, list_size, NULL, 0,
02954       NULL) < 0) 
02955     {
02956       free(list);
02957       return (-1);
02958     }
02959     if (list->size <= list_size)
02960       break;
02961     list_size = list->size;
02962   }
02963 
02964   // adding all SCSI devices
02965   for (unsigned i = 0; i < list->count; i++) {
02966     if(list->addr[i].scsi_dev_type)
02967       continue; /* non disk device found */
02968     char line[128];
02969     snprintf(line, sizeof(line) - 1, "/dev/bus/%d", bus_no);
02970     smart_device * dev = new linux_megaraid_device(this, line, 0, list->addr[i].device_id);
02971     devlist.push_back(dev);
02972   }
02973   free(list);
02974   return (0);
02975 }
02976 
02977 // Return kernel release as integer ("2.6.31" -> 206031)
02978 static unsigned get_kernel_release()
02979 {
02980   struct utsname u;
02981   if (uname(&u))
02982     return 0;
02983   unsigned x = 0, y = 0, z = 0;
02984   if (!(sscanf(u.release, "%u.%u.%u", &x, &y, &z) == 3
02985         && x < 100 && y < 100 && z < 1000             ))
02986     return 0;
02987   return x * 100000 + y * 1000 + z;
02988 }
02989 
02990 // Guess device type (ata or scsi) based on device name (Linux
02991 // specific) SCSI device name in linux can be sd, sr, scd, st, nst,
02992 // osst, nosst and sg.
02993 smart_device * linux_smart_interface::autodetect_smart_device(const char * name)
02994 {
02995   const char * test_name = name;
02996 
02997   // Dereference symlinks
02998   struct stat st;
02999   std::string pathbuf;
03000   if (!lstat(name, &st) && S_ISLNK(st.st_mode)) {
03001     char * p = realpath(name, (char *)0);
03002     if (p) {
03003       pathbuf = p;
03004       free(p);
03005       test_name = pathbuf.c_str();
03006     }
03007   }
03008 
03009   // Remove the leading /dev/... if it's there
03010   static const char dev_prefix[] = "/dev/";
03011   if (str_starts_with(test_name, dev_prefix))
03012     test_name += strlen(dev_prefix);
03013 
03014   // form /dev/h* or h*
03015   if (str_starts_with(test_name, "h"))
03016     return new linux_ata_device(this, name, "");
03017 
03018   // form /dev/ide/* or ide/*
03019   if (str_starts_with(test_name, "ide/"))
03020     return new linux_ata_device(this, name, "");
03021 
03022   // form /dev/s* or s*
03023   if (str_starts_with(test_name, "s")) {
03024 
03025     // Try to detect possible USB->(S)ATA bridge
03026     unsigned short vendor_id = 0, product_id = 0, version = 0;
03027     if (get_usb_id(test_name, vendor_id, product_id, version)) {
03028       const char * usbtype = get_usb_dev_type_by_id(vendor_id, product_id, version);
03029       if (!usbtype)
03030         return 0;
03031 
03032       // Kernels before 2.6.29 do not support the sense data length
03033       // required for SAT ATA PASS-THROUGH(16)
03034       if (!strcmp(usbtype, "sat") && get_kernel_release() < 206029)
03035         usbtype = "sat,12";
03036 
03037       // Return SAT/USB device for this type
03038       // (Note: linux_scsi_device::autodetect_open() will not be called in this case)
03039       return get_sat_device(usbtype, new linux_scsi_device(this, name, ""));
03040     }
03041 
03042     // No USB bridge found, assume regular SCSI device
03043     return new linux_scsi_device(this, name, "");
03044   }
03045 
03046   // form /dev/scsi/* or scsi/*
03047   if (str_starts_with(test_name, "scsi/"))
03048     return new linux_scsi_device(this, name, "");
03049 
03050   // form /dev/ns* or ns*
03051   if (str_starts_with(test_name, "ns"))
03052     return new linux_scsi_device(this, name, "");
03053 
03054   // form /dev/os* or os*
03055   if (str_starts_with(test_name, "os"))
03056     return new linux_scsi_device(this, name, "");
03057 
03058   // form /dev/nos* or nos*
03059   if (str_starts_with(test_name, "nos"))
03060     return new linux_scsi_device(this, name, "");
03061 
03062   // form /dev/tw[ael]* or tw[ael]*
03063   if (str_starts_with(test_name, "tw") && strchr("ael", test_name[2]))
03064     return missing_option("-d 3ware,N");
03065 
03066   // form /dev/cciss/* or cciss/*
03067   if (str_starts_with(test_name, "cciss/"))
03068     return missing_option("-d cciss,N");
03069 
03070   // we failed to recognize any of the forms
03071   return 0;
03072 }
03073 
03074 smart_device * linux_smart_interface::get_custom_smart_device(const char * name, const char * type)
03075 {
03076   // Marvell ?
03077   if (!strcmp(type, "marvell"))
03078     return new linux_marvell_device(this, name, type);
03079 
03080   // 3Ware ?
03081   int disknum = -1, n1 = -1, n2 = -1;
03082   if (sscanf(type, "3ware,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
03083     if (n2 != (int)strlen(type)) {
03084       set_err(EINVAL, "Option -d 3ware,N requires N to be a non-negative integer");
03085       return 0;
03086     }
03087     if (!(0 <= disknum && disknum <= 127)) {
03088       set_err(EINVAL, "Option -d 3ware,N (N=%d) must have 0 <= N <= 127", disknum);
03089       return 0;
03090     }
03091 
03092     if (!strncmp(name, "/dev/twl", 8))
03093       return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_9700_CHAR, disknum);
03094     else if (!strncmp(name, "/dev/twa", 8))
03095       return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_9000_CHAR, disknum);
03096     else if (!strncmp(name, "/dev/twe", 8))
03097       return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_678K_CHAR, disknum);
03098     else
03099       return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_678K, disknum);
03100   }
03101 
03102   // Areca?
03103   disknum = n1 = n2 = -1;
03104   int encnum = 1;
03105   if (sscanf(type, "areca,%n%d/%d%n", &n1, &disknum, &encnum, &n2) >= 1 || n1 == 6) {
03106     if (!(1 <= disknum && disknum <= 128)) {
03107       set_err(EINVAL, "Option -d areca,N/E (N=%d) must have 1 <= N <= 128", disknum);
03108       return 0;
03109     }
03110     if (!(1 <= encnum && encnum <= 8)) {
03111       set_err(EINVAL, "Option -d areca,N/E (E=%d) must have 1 <= E <= 8", encnum);
03112       return 0;
03113     }
03114     return new linux_areca_ata_device(this, name, disknum, encnum);
03115   }
03116 
03117   // Highpoint ?
03118   int controller = -1, channel = -1; disknum = 1;
03119   n1 = n2 = -1; int n3 = -1;
03120   if (sscanf(type, "hpt,%n%d/%d%n/%d%n", &n1, &controller, &channel, &n2, &disknum, &n3) >= 2 || n1 == 4) {
03121     int len = strlen(type);
03122     if (!(n2 == len || n3 == len)) {
03123       set_err(EINVAL, "Option '-d hpt,L/M/N' supports 2-3 items");
03124       return 0;
03125     }
03126     if (!(1 <= controller && controller <= 8)) {
03127       set_err(EINVAL, "Option '-d hpt,L/M/N' invalid controller id L supplied");
03128       return 0;
03129     }
03130     if (!(1 <= channel && channel <= 128)) {
03131       set_err(EINVAL, "Option '-d hpt,L/M/N' invalid channel number M supplied");
03132       return 0;
03133     }
03134     if (!(1 <= disknum && disknum <= 15)) {
03135       set_err(EINVAL, "Option '-d hpt,L/M/N' invalid pmport number N supplied");
03136       return 0;
03137     }
03138     return new linux_highpoint_device(this, name, controller, channel, disknum);
03139   }
03140 
03141 #ifdef HAVE_LINUX_CCISS_IOCTL_H
03142   // CCISS ?
03143   disknum = n1 = n2 = -1;
03144   if (sscanf(type, "cciss,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
03145     if (n2 != (int)strlen(type)) {
03146       set_err(EINVAL, "Option -d cciss,N requires N to be a non-negative integer");
03147       return 0;
03148     }
03149     if (!(0 <= disknum && disknum <= 127)) {
03150       set_err(EINVAL, "Option -d cciss,N (N=%d) must have 0 <= N <= 127", disknum);
03151       return 0;
03152     }
03153     return get_sat_device("sat,auto", new linux_cciss_device(this, name, disknum));
03154   }
03155 #endif // HAVE_LINUX_CCISS_IOCTL_H
03156 
03157   // MegaRAID ?
03158   if (sscanf(type, "megaraid,%d", &disknum) == 1) {
03159     return new linux_megaraid_device(this, name, 0, disknum);
03160   }
03161 
03162   //aacraid?
03163   unsigned int device;
03164   unsigned int host;
03165   if(sscanf(type, "aacraid,%d,%d,%d", &host, &channel, &device)==3) {
03166     //return new linux_aacraid_device(this,name,channel,device);
03167     return get_sat_device("sat,auto",
03168       new linux_aacraid_device(this, name, host, channel, device));
03169 
03170   }
03171 
03172   return 0;
03173 }
03174 
03175 std::string linux_smart_interface::get_valid_custom_dev_types_str()
03176 {
03177   return "marvell, areca,N/E, 3ware,N, hpt,L/M/N, megaraid,N, aacraid,H,L,ID"
03178 #ifdef HAVE_LINUX_CCISS_IOCTL_H
03179                                               ", cciss,N"
03180 #endif
03181     ;
03182 }
03183 
03184 } // namespace
03185 
03186 /////////////////////////////////////////////////////////////////////////////
03187 /// Initialize platform interface and register with smi()
03188 
03189 void smart_interface::init()
03190 {
03191   static os_linux::linux_smart_interface the_interface;
03192   smart_interface::set(&the_interface);
03193 }