1. Summary
  2. Files
  3. Support
  4. Report Spam
  5. Create account
  6. Log in

root/branches/RELEASE_5_39_BRANCH/smartmontools/os_linux.cpp @ 3053

Revision 3053, 102.0 KB (checked in by chrfranke, 3 years ago)

Merge r3051, r3052 into 5.39.1.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 *  os_linux.cpp
3 *
4 * Home page of code is: http://smartmontools.sourceforge.net
5 *
6 * Copyright (C) 2003-8 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2003-8 Doug Gilbert <dougg@torque.net>
8 * Copyright (C) 2008   Hank Wu <hank@areca.com.tw>
9 * Copyright (C) 2008   Oliver Bock <brevilo@users.sourceforge.net>
10 * Copyright (C) 2008-9 Christian Franke <smartmontools-support@lists.sourceforge.net>
11 * Copyright (C) 2008   Jordan Hargrave <jordan_hargrave@dell.com>
12 *
13 *  Parts of this file are derived from code that was
14 *
15 *  Written By: Adam Radford <linux@3ware.com>
16 *  Modifications By: Joel Jacobson <linux@3ware.com>
17 *                   Arnaldo Carvalho de Melo <acme@conectiva.com.br>
18 *                    Brad Strand <linux@3ware.com>
19 *
20 *  Copyright (C) 1999-2003 3ware Inc.
21 *
22 *  Kernel compatablity By:     Andre Hedrick <andre@suse.com>
23 *  Non-Copyright (C) 2000      Andre Hedrick <andre@suse.com>
24 *
25 * Other ars of this file are derived from code that was
26 *
27 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
28 * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
29 *
30 * This program is free software; you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation; either version 2, or (at your option)
33 * any later version.
34 *
35 * You should have received a copy of the GNU General Public License
36 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
37 *
38 * This code was originally developed as a Senior Thesis by Michael Cornwell
39 * at the Concurrent Systems Laboratory (now part of the Storage Systems
40 * Research Center), Jack Baskin School of Engineering, University of
41 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
42 *
43 */
44
45// This file contains the linux-specific IOCTL parts of
46// smartmontools. It includes one interface routine for ATA devices,
47// one for SCSI devices, and one for ATA devices behind escalade
48// controllers.
49
50#include "config.h"
51
52#include <errno.h>
53#include <fcntl.h>
54#include <glob.h>
55
56#include <scsi/scsi.h>
57#include <scsi/scsi_ioctl.h>
58#include <scsi/sg.h>
59#include <stdlib.h>
60#include <string.h>
61#include <sys/ioctl.h>
62#include <sys/stat.h>
63#include <sys/file.h>
64#include <unistd.h>
65#include <sys/uio.h>
66#include <sys/types.h>
67#ifndef makedev // old versions of types.h do not include sysmacros.h
68#include <sys/sysmacros.h>
69#endif
70#ifdef WITH_SELINUX
71#include <selinux/selinux.h>
72#endif
73
74#include "int64.h"
75#include "atacmds.h"
76#include "extern.h"
77#include "os_linux.h"
78#include "scsicmds.h"
79#include "utility.h"
80#include "extern.h"
81#include "cciss.h"
82#include "megaraid.h"
83
84#include "dev_interface.h"
85#include "dev_ata_cmd_set.h"
86
87#ifndef ENOTSUP
88#define ENOTSUP ENOSYS
89#endif
90
91#define ARGUSED(x) ((void)(x))
92
93const char *os_XXXX_c_cvsid="$Id$" \
94ATACMDS_H_CVSID CONFIG_H_CVSID INT64_H_CVSID OS_LINUX_H_CVSID SCSICMDS_H_CVSID UTILITY_H_CVSID;
95
96/* for passing global control variables */
97// (con->reportscsiioctl only)
98extern smartmonctrl *con;
99
100
101namespace os_linux { // No need to publish anything, name provided for Doxygen
102
103/////////////////////////////////////////////////////////////////////////////
104/// Shared open/close routines
105
106class linux_smart_device
107: virtual public /*implements*/ smart_device
108{
109public:
110  explicit linux_smart_device(int flags, int retry_flags = -1)
111    : smart_device(never_called),
112      m_fd(-1),
113      m_flags(flags), m_retry_flags(retry_flags)
114      { }
115
116  virtual ~linux_smart_device() throw();
117
118  virtual bool is_open() const;
119
120  virtual bool open();
121
122  virtual bool close();
123
124protected:
125  /// Return filedesc for derived classes.
126  int get_fd() const
127    { return m_fd; }
128
129private:
130  int m_fd; ///< filedesc, -1 if not open.
131  int m_flags; ///< Flags for ::open()
132  int m_retry_flags; ///< Flags to retry ::open(), -1 if no retry
133};
134
135
136linux_smart_device::~linux_smart_device() throw()
137{
138  if (m_fd >= 0)
139    ::close(m_fd);
140}
141
142bool linux_smart_device::is_open() const
143{
144  return (m_fd >= 0);
145}
146
147bool linux_smart_device::open()
148{
149  m_fd = ::open(get_dev_name(), m_flags);
150
151  if (m_fd < 0 && errno == EROFS && m_retry_flags != -1)
152    // Retry
153    m_fd = ::open(get_dev_name(), m_retry_flags);
154
155  if (m_fd < 0) {
156    if (errno == EBUSY && (m_flags & O_EXCL))
157      // device is locked
158      return set_err(EBUSY,
159        "The requested controller is used exclusively by another process!\n"
160        "(e.g. smartctl or smartd)\n"
161        "Please quit the impeding process or try again later...");
162    return set_err((errno==ENOENT || errno==ENOTDIR) ? ENODEV : errno);
163  }
164
165  if (m_fd >= 0) {
166    // sets FD_CLOEXEC on the opened device file descriptor.  The
167    // descriptor is otherwise leaked to other applications (mail
168    // sender) which may be considered a security risk and may result
169    // in AVC messages on SELinux-enabled systems.
170    if (-1 == fcntl(m_fd, F_SETFD, FD_CLOEXEC))
171      // TODO: Provide an error printing routine in class smart_interface
172      pout("fcntl(set  FD_CLOEXEC) failed, errno=%d [%s]\n", errno, strerror(errno));
173  }
174
175  return true;
176}
177
178// equivalent to close(file descriptor)
179bool linux_smart_device::close()
180{
181  int fd = m_fd; m_fd = -1;
182  if (::close(fd) < 0)
183    return set_err(errno);
184  return true;
185}
186
187// examples for smartctl
188static const char  smartctl_examples[] =
189                  "=================================================== SMARTCTL EXAMPLES =====\n\n"
190                  "  smartctl --all /dev/hda                    (Prints all SMART information)\n\n"
191                  "  smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda\n"
192                  "                                              (Enables SMART on first disk)\n\n"
193                  "  smartctl --test=long /dev/hda          (Executes extended disk self-test)\n\n"
194                  "  smartctl --attributes --log=selftest --quietmode=errorsonly /dev/hda\n"
195                  "                                      (Prints Self-Test & Attribute errors)\n"
196                  "  smartctl --all --device=3ware,2 /dev/sda\n"
197                  "  smartctl --all --device=3ware,2 /dev/twe0\n"
198                  "  smartctl --all --device=3ware,2 /dev/twa0\n"
199                  "          (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
200                  "  smartctl --all --device=hpt,1/1/3 /dev/sda\n"
201                  "          (Prints all SMART info for the SATA disk attached to the 3rd PMPort\n"
202                  "           of the 1st channel on the 1st HighPoint RAID controller)\n"
203                  "  smartctl --all --device=areca,3 /dev/sg2\n"
204                  "          (Prints all SMART info for 3rd ATA disk on Areca RAID controller)\n"
205  ;
206
207
208/////////////////////////////////////////////////////////////////////////////
209/// Linux ATA support
210
211class linux_ata_device
212: public /*implements*/ ata_device_with_command_set,
213  public /*extends*/ linux_smart_device
214{
215public:
216  linux_ata_device(smart_interface * intf, const char * dev_name, const char * req_type);
217
218protected:
219  virtual int ata_command_interface(smart_command_set command, int select, char * data);
220};
221
222linux_ata_device::linux_ata_device(smart_interface * intf, const char * dev_name, const char * req_type)
223: smart_device(intf, dev_name, "ata", req_type),
224  linux_smart_device(O_RDONLY | O_NONBLOCK)
225{
226}
227
228// PURPOSE
229//   This is an interface routine meant to isolate the OS dependent
230//   parts of the code, and to provide a debugging interface.  Each
231//   different port and OS needs to provide it's own interface.  This
232//   is the linux one.
233// DETAILED DESCRIPTION OF ARGUMENTS
234//   device: is the file descriptor provided by open()
235//   command: defines the different operations.
236//   select: additional input data if needed (which log, which type of
237//           self-test).
238//   data:   location to write output data, if needed (512 bytes).
239//   Note: not all commands use all arguments.
240// RETURN VALUES
241//  -1 if the command failed
242//   0 if the command succeeded,
243//   STATUS_CHECK routine:
244//  -1 if the command failed
245//   0 if the command succeeded and disk SMART status is "OK"
246//   1 if the command succeeded and disk SMART status is "FAILING"
247
248
249#define BUFFER_LENGTH (4+512)
250
251int linux_ata_device::ata_command_interface(smart_command_set command, int select, char * data)
252{
253  unsigned char buff[BUFFER_LENGTH];
254  // positive: bytes to write to caller.  negative: bytes to READ from
255  // caller. zero: non-data command
256  int copydata=0;
257
258  const int HDIO_DRIVE_CMD_OFFSET = 4;
259
260  // See struct hd_drive_cmd_hdr in hdreg.h.  Before calling ioctl()
261  // buff[0]: ATA COMMAND CODE REGISTER
262  // buff[1]: ATA SECTOR NUMBER REGISTER == LBA LOW REGISTER
263  // buff[2]: ATA FEATURES REGISTER
264  // buff[3]: ATA SECTOR COUNT REGISTER
265
266  // Note that on return:
267  // buff[2] contains the ATA SECTOR COUNT REGISTER
268
269  // clear out buff.  Large enough for HDIO_DRIVE_CMD (4+512 bytes)
270  memset(buff, 0, BUFFER_LENGTH);
271
272  buff[0]=ATA_SMART_CMD;
273  switch (command){
274  case CHECK_POWER_MODE:
275    buff[0]=ATA_CHECK_POWER_MODE;
276    copydata=1;
277    break;
278  case READ_VALUES:
279    buff[2]=ATA_SMART_READ_VALUES;
280    buff[3]=1;
281    copydata=512;
282    break;
283  case READ_THRESHOLDS:
284    buff[2]=ATA_SMART_READ_THRESHOLDS;
285    buff[1]=buff[3]=1;
286    copydata=512;
287    break;
288  case READ_LOG:
289    buff[2]=ATA_SMART_READ_LOG_SECTOR;
290    buff[1]=select;
291    buff[3]=1;
292    copydata=512;
293    break;
294  case WRITE_LOG:
295    break;
296  case IDENTIFY:
297    buff[0]=ATA_IDENTIFY_DEVICE;
298    buff[3]=1;
299    copydata=512;
300    break;
301  case PIDENTIFY:
302    buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
303    buff[3]=1;
304    copydata=512;
305    break;
306  case ENABLE:
307    buff[2]=ATA_SMART_ENABLE;
308    buff[1]=1;
309    break;
310  case DISABLE:
311    buff[2]=ATA_SMART_DISABLE;
312    buff[1]=1;
313    break;
314  case STATUS:
315    // this command only says if SMART is working.  It could be
316    // replaced with STATUS_CHECK below.
317    buff[2]=ATA_SMART_STATUS;
318    break;
319  case AUTO_OFFLINE:
320    // NOTE: According to ATAPI 4 and UP, this command is obsolete
321    // select == 241 for enable but no data transfer.  Use TASK ioctl.
322    buff[1]=ATA_SMART_AUTO_OFFLINE;
323    buff[2]=select;
324    break;
325  case AUTOSAVE:
326    // select == 248 for enable but no data transfer.  Use TASK ioctl.
327    buff[1]=ATA_SMART_AUTOSAVE;
328    buff[2]=select;
329    break;
330  case IMMEDIATE_OFFLINE:
331    buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
332    buff[1]=select;
333    break;
334  case STATUS_CHECK:
335    // This command uses HDIO_DRIVE_TASK and has different syntax than
336    // the other commands.
337    buff[1]=ATA_SMART_STATUS;
338    break;
339  default:
340    pout("Unrecognized command %d in linux_ata_command_interface()\n"
341         "Please contact " PACKAGE_BUGREPORT "\n", command);
342    errno=ENOSYS;
343    return -1;
344  }
345
346  // This command uses the HDIO_DRIVE_TASKFILE ioctl(). This is the
347  // only ioctl() that can be used to WRITE data to the disk.
348  if (command==WRITE_LOG) {
349    unsigned char task[sizeof(ide_task_request_t)+512];
350    ide_task_request_t *reqtask=(ide_task_request_t *) task;
351    task_struct_t      *taskfile=(task_struct_t *) reqtask->io_ports;
352    int retval;
353
354    memset(task,      0, sizeof(task));
355
356    taskfile->data           = 0;
357    taskfile->feature        = ATA_SMART_WRITE_LOG_SECTOR;
358    taskfile->sector_count   = 1;
359    taskfile->sector_number  = select;
360    taskfile->low_cylinder   = 0x4f;
361    taskfile->high_cylinder  = 0xc2;
362    taskfile->device_head    = 0;
363    taskfile->command        = ATA_SMART_CMD;
364
365    reqtask->data_phase      = TASKFILE_OUT;
366    reqtask->req_cmd         = IDE_DRIVE_TASK_OUT;
367    reqtask->out_size        = 512;
368    reqtask->in_size         = 0;
369
370    // copy user data into the task request structure
371    memcpy(task+sizeof(ide_task_request_t), data, 512);
372
373    if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASKFILE, task))) {
374      if (retval==-EINVAL)
375        pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
376      return -1;
377    }
378    return 0;
379  }
380
381  // There are two different types of ioctls().  The HDIO_DRIVE_TASK
382  // one is this:
383  if (command==STATUS_CHECK || command==AUTOSAVE || command==AUTO_OFFLINE){
384    int retval;
385
386    // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
387    // have to read the IDE driver source code.  Sigh.
388    // buff[0]: ATA COMMAND CODE REGISTER
389    // buff[1]: ATA FEATURES REGISTER
390    // buff[2]: ATA SECTOR_COUNT
391    // buff[3]: ATA SECTOR NUMBER
392    // buff[4]: ATA CYL LO REGISTER
393    // buff[5]: ATA CYL HI REGISTER
394    // buff[6]: ATA DEVICE HEAD
395
396    unsigned const char normal_lo=0x4f, normal_hi=0xc2;
397    unsigned const char failed_lo=0xf4, failed_hi=0x2c;
398    buff[4]=normal_lo;
399    buff[5]=normal_hi;
400
401    if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASK, buff))) {
402      if (retval==-EINVAL) {
403        pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
404        pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
405      }
406      else
407        syserror("Error SMART Status command failed");
408      return -1;
409    }
410
411    // Cyl low and Cyl high unchanged means "Good SMART status"
412    if (buff[4]==normal_lo && buff[5]==normal_hi)
413      return 0;
414
415    // These values mean "Bad SMART status"
416    if (buff[4]==failed_lo && buff[5]==failed_hi)
417      return 1;
418
419    // We haven't gotten output that makes sense; print out some debugging info
420    syserror("Error SMART Status command failed");
421    pout("Please get assistance from " PACKAGE_HOMEPAGE "\n");
422    pout("Register values returned from SMART Status command are:\n");
423    pout("ST =0x%02x\n",(int)buff[0]);
424    pout("ERR=0x%02x\n",(int)buff[1]);
425    pout("NS =0x%02x\n",(int)buff[2]);
426    pout("SC =0x%02x\n",(int)buff[3]);
427    pout("CL =0x%02x\n",(int)buff[4]);
428    pout("CH =0x%02x\n",(int)buff[5]);
429    pout("SEL=0x%02x\n",(int)buff[6]);
430    return -1;
431  }
432
433#if 1
434  // Note to people doing ports to other OSes -- don't worry about
435  // this block -- you can safely ignore it.  I have put it here
436  // because under linux when you do IDENTIFY DEVICE to a packet
437  // device, it generates an ugly kernel syslog error message.  This
438  // is harmless but frightens users.  So this block detects packet
439  // devices and make IDENTIFY DEVICE fail "nicely" without a syslog
440  // error message.
441  //
442  // If you read only the ATA specs, it appears as if a packet device
443  // *might* respond to the IDENTIFY DEVICE command.  This is
444  // misleading - it's because around the time that SFF-8020 was
445  // incorporated into the ATA-3/4 standard, the ATA authors were
446  // sloppy. See SFF-8020 and you will see that ATAPI devices have
447  // *always* had IDENTIFY PACKET DEVICE as a mandatory part of their
448  // command set, and return 'Command Aborted' to IDENTIFY DEVICE.
449  if (command==IDENTIFY || command==PIDENTIFY){
450    unsigned short deviceid[256];
451    // check the device identity, as seen when the system was booted
452    // or the device was FIRST registered.  This will not be current
453    // if the user has subsequently changed some of the parameters. If
454    // device is a packet device, swap the command interpretations.
455    if (!ioctl(get_fd(), HDIO_GET_IDENTITY, deviceid) && (deviceid[0] & 0x8000))
456      buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
457  }
458#endif
459
460  // We are now doing the HDIO_DRIVE_CMD type ioctl.
461  if ((ioctl(get_fd(), HDIO_DRIVE_CMD, buff)))
462    return -1;
463
464  // CHECK POWER MODE command returns information in the Sector Count
465  // register (buff[3]).  Copy to return data buffer.
466  if (command==CHECK_POWER_MODE)
467    buff[HDIO_DRIVE_CMD_OFFSET]=buff[2];
468
469  // if the command returns data then copy it back
470  if (copydata)
471    memcpy(data, buff+HDIO_DRIVE_CMD_OFFSET, copydata);
472
473  return 0;
474}
475
476// >>>>>> Start of general SCSI specific linux code
477
478/* Linux specific code.
479 * Historically smartmontools (and smartsuite before it) used the
480 * SCSI_IOCTL_SEND_COMMAND ioctl which is available to all linux device
481 * nodes that use the SCSI subsystem. A better interface has been available
482 * via the SCSI generic (sg) driver but this involves the extra step of
483 * mapping disk devices (e.g. /dev/sda) to the corresponding sg device
484 * (e.g. /dev/sg2). In the linux kernel 2.6 series most of the facilities of
485 * the sg driver have become available via the SG_IO ioctl which is available
486 * on all SCSI devices (on SCSI tape devices from lk 2.6.6).
487 * So the strategy below is to find out if the SG_IO ioctl is available and
488 * if so use it; failing that use the older SCSI_IOCTL_SEND_COMMAND ioctl.
489 * Should work in 2.0, 2.2, 2.4 and 2.6 series linux kernels. */
490
491#define MAX_DXFER_LEN 1024      /* can be increased if necessary */
492#define SEND_IOCTL_RESP_SENSE_LEN 16    /* ioctl limitation */
493#define SG_IO_RESP_SENSE_LEN 64 /* large enough see buffer */
494#define LSCSI_DRIVER_MASK  0xf /* mask out "suggestions" */
495#define LSCSI_DRIVER_SENSE  0x8 /* alternate CHECK CONDITION indication */
496#define LSCSI_DID_ERROR 0x7 /* Need to work around aacraid driver quirk */
497#define LSCSI_DRIVER_TIMEOUT  0x6
498#define LSCSI_DID_TIME_OUT  0x3
499#define LSCSI_DID_BUS_BUSY  0x2
500#define LSCSI_DID_NO_CONNECT  0x1
501
502#ifndef SCSI_IOCTL_SEND_COMMAND
503#define SCSI_IOCTL_SEND_COMMAND 1
504#endif
505
506#define SG_IO_PRESENT_UNKNOWN 0
507#define SG_IO_PRESENT_YES 1
508#define SG_IO_PRESENT_NO 2
509
510static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
511                         int unknown);
512static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report);
513
514static int sg_io_state = SG_IO_PRESENT_UNKNOWN;
515
516/* Preferred implementation for issuing SCSI commands in linux. This
517 * function uses the SG_IO ioctl. Return 0 if command issued successfully
518 * (various status values should still be checked). If the SCSI command
519 * cannot be issued then a negative errno value is returned. */
520static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
521                         int unknown)
522{
523#ifndef SG_IO
524    ARGUSED(dev_fd); ARGUSED(iop); ARGUSED(report);
525    return -ENOTTY;
526#else
527    struct sg_io_hdr io_hdr;
528
529    if (report > 0) {
530        int k, j;
531        const unsigned char * ucp = iop->cmnd;
532        const char * np;
533        char buff[256];
534        const int sz = (int)sizeof(buff);
535
536        np = scsi_get_opcode_name(ucp[0]);
537        j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
538        for (k = 0; k < (int)iop->cmnd_len; ++k)
539            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
540        if ((report > 1) &&
541            (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
542            int trunc = (iop->dxfer_len > 256) ? 1 : 0;
543
544            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
545                          "data, len=%d%s:\n", (int)iop->dxfer_len,
546                          (trunc ? " [only first 256 bytes shown]" : ""));
547            dStrHex((const char *)iop->dxferp,
548                    (trunc ? 256 : iop->dxfer_len) , 1);
549        }
550        else
551            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
552        pout("%s", buff);
553    }
554    memset(&io_hdr, 0, sizeof(struct sg_io_hdr));
555    io_hdr.interface_id = 'S';
556    io_hdr.cmd_len = iop->cmnd_len;
557    io_hdr.mx_sb_len = iop->max_sense_len;
558    io_hdr.dxfer_len = iop->dxfer_len;
559    io_hdr.dxferp = iop->dxferp;
560    io_hdr.cmdp = iop->cmnd;
561    io_hdr.sbp = iop->sensep;
562    /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
563       defaults to 60 seconds. */
564    io_hdr.timeout = ((0 == iop->timeout) ? 60 : iop->timeout) * 1000;
565    switch (iop->dxfer_dir) {
566        case DXFER_NONE:
567            io_hdr.dxfer_direction = SG_DXFER_NONE;
568            break;
569        case DXFER_FROM_DEVICE:
570            io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
571            break;
572        case DXFER_TO_DEVICE:
573            io_hdr.dxfer_direction = SG_DXFER_TO_DEV;
574            break;
575        default:
576            pout("do_scsi_cmnd_io: bad dxfer_dir\n");
577            return -EINVAL;
578    }
579    iop->resp_sense_len = 0;
580    iop->scsi_status = 0;
581    iop->resid = 0;
582    if (ioctl(dev_fd, SG_IO, &io_hdr) < 0) {
583        if (report && (! unknown))
584            pout("  SG_IO ioctl failed, errno=%d [%s]\n", errno,
585                 strerror(errno));
586        return -errno;
587    }
588    iop->resid = io_hdr.resid;
589    iop->scsi_status = io_hdr.status;
590    if (report > 0) {
591        pout("  scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
592             "  info=0x%x  duration=%d milliseconds  resid=%d\n", io_hdr.status,
593             io_hdr.host_status, io_hdr.driver_status, io_hdr.info,
594             io_hdr.duration, io_hdr.resid);
595        if (report > 1) {
596            if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
597                int trunc, len;
598
599                len = iop->dxfer_len - iop->resid;
600                trunc = (len > 256) ? 1 : 0;
601                if (len > 0) {
602                    pout("  Incoming data, len=%d%s:\n", len,
603                         (trunc ? " [only first 256 bytes shown]" : ""));
604                    dStrHex((const char*)iop->dxferp, (trunc ? 256 : len),
605                            1);
606                } else
607                    pout("  Incoming data trimmed to nothing by resid\n");
608            }
609        }
610    }
611
612    if (io_hdr.info | SG_INFO_CHECK) { /* error or warning */
613        int masked_driver_status = (LSCSI_DRIVER_MASK & io_hdr.driver_status);
614
615        if (0 != io_hdr.host_status) {
616            if ((LSCSI_DID_NO_CONNECT == io_hdr.host_status) ||
617                (LSCSI_DID_BUS_BUSY == io_hdr.host_status) ||
618                (LSCSI_DID_TIME_OUT == io_hdr.host_status))
619                return -ETIMEDOUT;
620            else
621               /* Check for DID_ERROR - workaround for aacraid driver quirk */
622               if (LSCSI_DID_ERROR != io_hdr.host_status) {
623                       return -EIO; /* catch all if not DID_ERR */
624               }
625        }
626        if (0 != masked_driver_status) {
627            if (LSCSI_DRIVER_TIMEOUT == masked_driver_status)
628                return -ETIMEDOUT;
629            else if (LSCSI_DRIVER_SENSE != masked_driver_status)
630                return -EIO;
631        }
632        if (LSCSI_DRIVER_SENSE == masked_driver_status)
633            iop->scsi_status = SCSI_STATUS_CHECK_CONDITION;
634        iop->resp_sense_len = io_hdr.sb_len_wr;
635        if ((SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) &&
636            iop->sensep && (iop->resp_sense_len > 0)) {
637            if (report > 1) {
638                pout("  >>> Sense buffer, len=%d:\n",
639                     (int)iop->resp_sense_len);
640                dStrHex((const char *)iop->sensep, iop->resp_sense_len , 1);
641            }
642        }
643        if (report) {
644            if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) {
645                if ((iop->sensep[0] & 0x7f) > 0x71)
646                    pout("  status=%x: [desc] sense_key=%x asc=%x ascq=%x\n",
647                         iop->scsi_status, iop->sensep[1] & 0xf,
648                         iop->sensep[2], iop->sensep[3]);
649                else
650                    pout("  status=%x: sense_key=%x asc=%x ascq=%x\n",
651                         iop->scsi_status, iop->sensep[2] & 0xf,
652                         iop->sensep[12], iop->sensep[13]);
653            }
654            else
655                pout("  status=0x%x\n", iop->scsi_status);
656        }
657    }
658    return 0;
659#endif
660}
661
662struct linux_ioctl_send_command
663{
664    int inbufsize;
665    int outbufsize;
666    UINT8 buff[MAX_DXFER_LEN + 16];
667};
668
669/* The Linux SCSI_IOCTL_SEND_COMMAND ioctl is primitive and it doesn't
670 * support: CDB length (guesses it from opcode), resid and timeout.
671 * Patches in Linux 2.4.21 and 2.5.70 to extend SEND DIAGNOSTIC timeout
672 * to 2 hours in order to allow long foreground extended self tests. */
673static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report)
674{
675    struct linux_ioctl_send_command wrk;
676    int status, buff_offset;
677    size_t len;
678
679    memcpy(wrk.buff, iop->cmnd, iop->cmnd_len);
680    buff_offset = iop->cmnd_len;
681    if (report > 0) {
682        int k, j;
683        const unsigned char * ucp = iop->cmnd;
684        const char * np;
685        char buff[256];
686        const int sz = (int)sizeof(buff);
687
688        np = scsi_get_opcode_name(ucp[0]);
689        j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
690        for (k = 0; k < (int)iop->cmnd_len; ++k)
691            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
692        if ((report > 1) &&
693            (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
694            int trunc = (iop->dxfer_len > 256) ? 1 : 0;
695
696            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
697                          "data, len=%d%s:\n", (int)iop->dxfer_len,
698                          (trunc ? " [only first 256 bytes shown]" : ""));
699            dStrHex((const char *)iop->dxferp,
700                    (trunc ? 256 : iop->dxfer_len) , 1);
701        }
702        else
703            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
704        pout("%s", buff);
705    }
706    switch (iop->dxfer_dir) {
707        case DXFER_NONE:
708            wrk.inbufsize = 0;
709            wrk.outbufsize = 0;
710            break;
711        case DXFER_FROM_DEVICE:
712            wrk.inbufsize = 0;
713            if (iop->dxfer_len > MAX_DXFER_LEN)
714                return -EINVAL;
715            wrk.outbufsize = iop->dxfer_len;
716            break;
717        case DXFER_TO_DEVICE:
718            if (iop->dxfer_len > MAX_DXFER_LEN)
719                return -EINVAL;
720            memcpy(wrk.buff + buff_offset, iop->dxferp, iop->dxfer_len);
721            wrk.inbufsize = iop->dxfer_len;
722            wrk.outbufsize = 0;
723            break;
724        default:
725            pout("do_scsi_cmnd_io: bad dxfer_dir\n");
726            return -EINVAL;
727    }
728    iop->resp_sense_len = 0;
729    iop->scsi_status = 0;
730    iop->resid = 0;
731    status = ioctl(dev_fd, SCSI_IOCTL_SEND_COMMAND, &wrk);
732    if (-1 == status) {
733        if (report)
734            pout("  SCSI_IOCTL_SEND_COMMAND ioctl failed, errno=%d [%s]\n",
735                 errno, strerror(errno));
736        return -errno;
737    }
738    if (0 == status) {
739        if (report > 0)
740            pout("  status=0\n");
741        if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
742            memcpy(iop->dxferp, wrk.buff, iop->dxfer_len);
743            if (report > 1) {
744                int trunc = (iop->dxfer_len > 256) ? 1 : 0;
745
746                pout("  Incoming data, len=%d%s:\n", (int)iop->dxfer_len,
747                     (trunc ? " [only first 256 bytes shown]" : ""));
748                dStrHex((const char*)iop->dxferp,
749                        (trunc ? 256 : iop->dxfer_len) , 1);
750            }
751        }
752        return 0;
753    }
754    iop->scsi_status = status & 0x7e; /* bits 0 and 7 used to be for vendors */
755    if (LSCSI_DRIVER_SENSE == ((status >> 24) & 0xf))
756        iop->scsi_status = SCSI_STATUS_CHECK_CONDITION;
757    len = (SEND_IOCTL_RESP_SENSE_LEN < iop->max_sense_len) ?
758                SEND_IOCTL_RESP_SENSE_LEN : iop->max_sense_len;
759    if ((SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) &&
760        iop->sensep && (len > 0)) {
761        memcpy(iop->sensep, wrk.buff, len);
762        iop->resp_sense_len = len;
763        if (report > 1) {
764            pout("  >>> Sense buffer, len=%d:\n", (int)len);
765            dStrHex((const char *)wrk.buff, len , 1);
766        }
767    }
768    if (report) {
769        if (SCSI_STATUS_CHECK_CONDITION == iop->scsi_status) {
770            pout("  status=%x: sense_key=%x asc=%x ascq=%x\n", status & 0xff,
771                 wrk.buff[2] & 0xf, wrk.buff[12], wrk.buff[13]);
772        }
773        else
774            pout("  status=0x%x\n", status);
775    }
776    if (iop->scsi_status > 0)
777        return 0;
778    else {
779        if (report > 0)
780            pout("  ioctl status=0x%x but scsi status=0, fail with EIO\n",
781                 status);
782        return -EIO;      /* give up, assume no device there */
783    }
784}
785
786/* SCSI command transmission interface function, linux version.
787 * Returns 0 if SCSI command successfully launched and response
788 * received. Even when 0 is returned the caller should check
789 * scsi_cmnd_io::scsi_status for SCSI defined errors and warnings
790 * (e.g. CHECK CONDITION). If the SCSI command could not be issued
791 * (e.g. device not present or timeout) or some other problem
792 * (e.g. timeout) then returns a negative errno value */
793static int do_normal_scsi_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop,
794                                  int report)
795{
796    int res;
797
798    /* implementation relies on static sg_io_state variable. If not
799     * previously set tries the SG_IO ioctl. If that succeeds assume
800     * that SG_IO ioctl functional. If it fails with an errno value
801     * other than ENODEV (no device) or permission then assume
802     * SCSI_IOCTL_SEND_COMMAND is the only option. */
803    switch (sg_io_state) {
804    case SG_IO_PRESENT_UNKNOWN:
805        /* ignore report argument */
806        if (0 == (res = sg_io_cmnd_io(dev_fd, iop, report, 1))) {
807            sg_io_state = SG_IO_PRESENT_YES;
808            return 0;
809        } else if ((-ENODEV == res) || (-EACCES == res) || (-EPERM == res))
810            return res;         /* wait until we see a device */
811        sg_io_state = SG_IO_PRESENT_NO;
812        /* drop through by design */
813    case SG_IO_PRESENT_NO:
814        return sisc_cmnd_io(dev_fd, iop, report);
815    case SG_IO_PRESENT_YES:
816        return sg_io_cmnd_io(dev_fd, iop, report, 0);
817    default:
818        pout(">>>> do_scsi_cmnd_io: bad sg_io_state=%d\n", sg_io_state);
819        sg_io_state = SG_IO_PRESENT_UNKNOWN;
820        return -EIO;    /* report error and reset state */
821    }
822}
823
824// >>>>>> End of general SCSI specific linux code
825
826/////////////////////////////////////////////////////////////////////////////
827/// Standard SCSI support
828
829class linux_scsi_device
830: public /*implements*/ scsi_device,
831  public /*extends*/ linux_smart_device
832{
833public:
834  linux_scsi_device(smart_interface * intf, const char * dev_name,
835                    const char * req_type, bool scanning = false);
836
837  virtual smart_device * autodetect_open();
838
839  virtual bool scsi_pass_through(scsi_cmnd_io * iop);
840
841private:
842  bool m_scanning; ///< true if created within scan_smart_devices
843};
844
845linux_scsi_device::linux_scsi_device(smart_interface * intf,
846  const char * dev_name, const char * req_type, bool scanning /*= false*/)
847: smart_device(intf, dev_name, "scsi", req_type),
848  // If opened with O_RDWR, a SATA disk in standby mode
849  // may spin-up after device close().
850  linux_smart_device(O_RDONLY | O_NONBLOCK),
851  m_scanning(scanning)
852{
853}
854
855
856bool linux_scsi_device::scsi_pass_through(scsi_cmnd_io * iop)
857{
858  int status = do_normal_scsi_cmnd_io(get_fd(), iop, con->reportscsiioctl);
859  if (status < 0)
860      return set_err(-status);
861  return true;
862}
863
864/////////////////////////////////////////////////////////////////////////////
865/// LSI MegaRAID support
866
867class linux_megaraid_device
868: public /* implements */ scsi_device,
869  public /* extends */ linux_smart_device
870{
871public:
872  linux_megaraid_device(smart_interface *intf, const char *name, 
873    unsigned int bus, unsigned int tgt);
874
875  virtual ~linux_megaraid_device() throw();
876
877  virtual smart_device * autodetect_open();
878
879  virtual bool open();
880  virtual bool close();
881 
882  virtual bool scsi_pass_through(scsi_cmnd_io *iop);
883
884private:
885  unsigned int m_disknum;
886  unsigned int m_busnum;
887  unsigned int m_hba;
888  int m_fd;
889
890  bool (linux_megaraid_device::*pt_cmd)(int cdblen, void *cdb, int dataLen, void *data,
891    int senseLen, void *sense, int report);
892  bool megasas_cmd(int cdbLen, void *cdb, int dataLen, void *data,
893    int senseLen, void *sense, int report);
894  bool megadev_cmd(int cdbLen, void *cdb, int dataLen, void *data,
895    int senseLen, void *sense, int report);
896};
897
898linux_megaraid_device::linux_megaraid_device(smart_interface *intf,
899  const char *dev_name, unsigned int bus, unsigned int tgt)
900 : smart_device(intf, dev_name, "megaraid", "megaraid"),
901   linux_smart_device(O_RDWR | O_NONBLOCK),
902   m_disknum(tgt), m_busnum(bus), m_hba(0),
903   m_fd(-1), pt_cmd(0)
904{
905  set_info().info_name = strprintf("%s [megaraid_disk_%02d]", dev_name, m_disknum);
906}
907
908linux_megaraid_device::~linux_megaraid_device() throw()
909{
910  if (m_fd >= 0)
911    ::close(m_fd);
912}
913
914smart_device * linux_megaraid_device::autodetect_open()
915{
916  int report = con->reportscsiioctl; 
917
918  // Open device
919  if (!open())
920    return this;
921
922  // The code below is based on smartd.cpp:SCSIFilterKnown()
923  if (strcmp(get_req_type(), "megaraid"))
924    return this;
925
926  // Get INQUIRY
927  unsigned char req_buff[64] = {0, };
928  int req_len = 36;
929  if (scsiStdInquiry(this, req_buff, req_len)) {
930      close();
931      set_err(EIO, "INQUIRY failed");
932      return this;
933  }
934
935  int avail_len = req_buff[4] + 5;
936  int len = (avail_len < req_len ? avail_len : req_len);
937  if (len < 36)
938      return this;
939
940  if (report)
941    printf("Got MegaRAID inquiry.. %s\n", req_buff+8);
942
943  // Use INQUIRY to detect type
944  {
945    // SAT or USB ?
946    ata_device * newdev = smi()->autodetect_sat_device(this, req_buff, len);
947    if (newdev)
948      // NOTE: 'this' is now owned by '*newdev'
949      return newdev;
950  }
951
952  // Nothing special found
953  return this;
954}
955
956
957bool linux_megaraid_device::open()
958{
959  char line[128];
960  int   mjr, n1;
961  FILE *fp;
962  int report = con->reportscsiioctl; 
963
964  if (!linux_smart_device::open())
965    return false;
966
967  /* Get device HBA */
968  struct sg_scsi_id sgid;
969  if (ioctl(get_fd(), SG_GET_SCSI_ID, &sgid) == 0) {
970    m_hba = sgid.host_no;
971  }
972  else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER, &m_hba) != 0) {
973    int err = errno;
974    linux_smart_device::close();
975    return set_err(err, "can't get bus number");
976  }
977
978  /* Perform mknod of device ioctl node */
979  fp = fopen("/proc/devices", "r");
980  while (fgets(line, sizeof(line), fp) != NULL) {
981        n1=0;
982        if (sscanf(line, "%d megaraid_sas_ioctl%n", &mjr, &n1) == 1 && n1 == 22) {
983           n1=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR, makedev(mjr, 0));
984           if(report > 0)
985             printf("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1 >= 0 ? 0 : errno);
986           if (n1 >= 0 || errno == EEXIST)
987              break;
988        }
989        else if (sscanf(line, "%d megadev%n", &mjr, &n1) == 1 && n1 == 11) {
990           n1=mknod("/dev/megadev0", S_IFCHR, makedev(mjr, 0));
991           if(report > 0)
992             printf("Creating /dev/megadev0 = %d\n", n1 >= 0 ? 0 : errno);
993           if (n1 >= 0 || errno == EEXIST)
994              break;
995        }
996  }
997  fclose(fp);
998
999  /* Open Device IOCTL node */
1000  if ((m_fd = ::open("/dev/megaraid_sas_ioctl_node", O_RDWR)) >= 0) {
1001    pt_cmd = &linux_megaraid_device::megasas_cmd;
1002  }
1003  else if ((m_fd = ::open("/dev/megadev0", O_RDWR)) >= 0) {
1004    pt_cmd = &linux_megaraid_device::megadev_cmd;
1005  }
1006  else {
1007    int err = errno;
1008    linux_smart_device::close();
1009    return set_err(err, "cannot open /dev/megaraid_sas_ioctl_node or /dev/megadev0");
1010  }
1011
1012  return true;
1013}
1014
1015bool linux_megaraid_device::close()
1016{
1017  if (m_fd >= 0)
1018    ::close(m_fd);
1019  m_fd = -1; m_hba = 0; pt_cmd = 0;
1020  return linux_smart_device::close();
1021}
1022
1023bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io *iop)
1024{
1025  int report = con->reportscsiioctl; 
1026
1027  if (report > 0) {
1028        int k, j;
1029        const unsigned char * ucp = iop->cmnd;
1030        const char * np;
1031        char buff[256];
1032        const int sz = (int)sizeof(buff);
1033
1034        np = scsi_get_opcode_name(ucp[0]);
1035        j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
1036        for (k = 0; k < (int)iop->cmnd_len; ++k)
1037            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
1038        if ((report > 1) &&
1039            (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
1040            int trunc = (iop->dxfer_len > 256) ? 1 : 0;
1041
1042            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n  Outgoing "
1043                          "data, len=%d%s:\n", (int)iop->dxfer_len,
1044                          (trunc ? " [only first 256 bytes shown]" : ""));
1045            dStrHex((const char *)iop->dxferp,
1046                    (trunc ? 256 : iop->dxfer_len) , 1);
1047        }
1048        else
1049            j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
1050        pout("%s", buff);
1051  }
1052
1053  /* Controller rejects Enable SMART and Test Unit Ready */
1054  if (iop->cmnd[0] == 0x00)
1055    return true;
1056  if (iop->cmnd[0] == 0x85 && iop->cmnd[1] == 0x06) {
1057    if(report > 0)
1058      pout("Rejecting SMART/ATA command to controller\n");
1059    // Emulate SMART STATUS CHECK drive reply
1060    // smartctl fail to work without this
1061    if(iop->cmnd[2]==0x2c) {
1062      iop->resp_sense_len=22; // copied from real response
1063      iop->sensep[0]=0x72; // descriptor format
1064      iop->sensep[7]=0x0e; // additional length
1065      iop->sensep[8]=0x09; // description pointer
1066      iop->sensep[17]=0x4f; // low cylinder GOOD smart status
1067      iop->sensep[19]=0xc2; // high cylinder GOOD smart status
1068    }
1069    return true;
1070  }
1071
1072  if (pt_cmd == NULL)
1073    return false;
1074  return (this->*pt_cmd)(iop->cmnd_len, iop->cmnd, 
1075    iop->dxfer_len, iop->dxferp,
1076    iop->max_sense_len, iop->sensep, report);
1077}
1078
1079/* Issue passthrough scsi command to PERC5/6 controllers */
1080bool linux_megaraid_device::megasas_cmd(int cdbLen, void *cdb, 
1081  int dataLen, void *data,
1082  int /*senseLen*/, void * /*sense*/, int /*report*/)
1083{
1084  struct megasas_pthru_frame    *pthru;
1085  struct megasas_iocpacket      uio;
1086  int rc;
1087
1088  memset(&uio, 0, sizeof(uio));
1089  pthru = (struct megasas_pthru_frame *)uio.frame.raw;
1090  pthru->cmd = MFI_CMD_PD_SCSI_IO;
1091  pthru->cmd_status = 0xFF;
1092  pthru->scsi_status = 0x0;
1093  pthru->target_id = m_disknum;
1094  pthru->lun = 0;
1095  pthru->cdb_len = cdbLen;
1096  pthru->timeout = 0;
1097  pthru->flags = MFI_FRAME_DIR_READ;
1098  pthru->sge_count = 1;
1099  pthru->data_xfer_len = dataLen;
1100  pthru->sgl.sge32[0].phys_addr = (intptr_t)data;
1101  pthru->sgl.sge32[0].length = (uint32_t)dataLen;
1102  memcpy(pthru->cdb, cdb, cdbLen);
1103
1104  uio.host_no = m_hba;
1105  uio.sge_count = 1;
1106  uio.sgl_off = offsetof(struct megasas_pthru_frame, sgl);
1107  uio.sgl[0].iov_base = data;
1108  uio.sgl[0].iov_len = dataLen;
1109
1110  rc = 0;
1111  errno = 0;
1112  rc = ioctl(m_fd, MEGASAS_IOC_FIRMWARE, &uio);
1113  if (pthru->cmd_status || rc != 0) {
1114    if (pthru->cmd_status == 12) {
1115      return set_err(EIO, "megasas_cmd: Device %d does not exist\n", m_disknum);
1116    }
1117    return set_err((errno ? errno : EIO), "megasas_cmd result: %d.%d = %d/%d",
1118                   m_hba, m_disknum, errno,
1119                   pthru->cmd_status);
1120  }
1121  return true;
1122}
1123
1124/* Issue passthrough scsi commands to PERC2/3/4 controllers */
1125bool linux_megaraid_device::megadev_cmd(int cdbLen, void *cdb, 
1126  int dataLen, void *data,
1127  int senseLen, void *sense, int /*report*/)
1128{
1129  struct uioctl_t uio;
1130  int rc;
1131
1132  sense = NULL;
1133  senseLen = 0;
1134
1135  /* Don't issue to the controller */
1136  if (m_disknum == 7)
1137    return false;
1138
1139  memset(&uio, 0, sizeof(uio));
1140  uio.inlen  = dataLen;
1141  uio.outlen = dataLen;
1142
1143  memset(data, 0, dataLen);
1144  uio.ui.fcs.opcode = 0x80;             // M_RD_IOCTL_CMD
1145  uio.ui.fcs.adapno = MKADAP(m_hba);
1146
1147  uio.data.pointer = (uint8_t *)data;
1148
1149  uio.mbox.cmd = MEGA_MBOXCMD_PASSTHRU;
1150  uio.mbox.xferaddr = (intptr_t)&uio.pthru;
1151
1152  uio.pthru.ars     = 1;
1153  uio.pthru.timeout = 2;
1154  uio.pthru.channel = 0;
1155  uio.pthru.target  = m_disknum;
1156  uio.pthru.cdblen  = cdbLen;
1157  uio.pthru.reqsenselen  = MAX_REQ_SENSE_LEN;
1158  uio.pthru.dataxferaddr = (intptr_t)data;
1159  uio.pthru.dataxferlen  = dataLen;
1160  memcpy(uio.pthru.cdb, cdb, cdbLen);
1161
1162  rc=ioctl(m_fd, MEGAIOCCMD, &uio);
1163  if (uio.pthru.scsistatus || rc != 0) {
1164    return set_err((errno ? errno : EIO), "megadev_cmd result: %d.%d =  %d/%d",
1165                   m_hba, m_disknum, errno,
1166                   uio.pthru.scsistatus);
1167  }
1168  return true;
1169}
1170
1171/////////////////////////////////////////////////////////////////////////////
1172/// CCISS RAID support
1173
1174#ifdef HAVE_LINUX_CCISS_IOCTL_H
1175
1176class linux_cciss_device
1177: public /*implements*/ scsi_device,
1178  public /*extends*/ linux_smart_device
1179{
1180public:
1181  linux_cciss_device(smart_interface * intf, const char * name, unsigned char disknum);
1182
1183  virtual bool scsi_pass_through(scsi_cmnd_io * iop);
1184
1185private:
1186  unsigned char m_disknum; ///< Disk number.
1187};
1188
1189linux_cciss_device::linux_cciss_device(smart_interface * intf,
1190  const char * dev_name, unsigned char disknum)
1191: smart_device(intf, dev_name, "cciss", "cciss"),
1192  linux_smart_device(O_RDWR | O_NONBLOCK),
1193  m_disknum(disknum)
1194{
1195  set_info().info_name = strprintf("%s [cciss_disk_%02d]", dev_name, disknum);
1196}
1197
1198bool linux_cciss_device::scsi_pass_through(scsi_cmnd_io * iop)
1199{
1200  int status = cciss_io_interface(get_fd(), m_disknum, iop, con->reportscsiioctl);
1201  if (status < 0)
1202      return set_err(-status);
1203  return true;
1204}
1205
1206#endif // HAVE_LINUX_CCISS_IOCTL_H
1207
1208/////////////////////////////////////////////////////////////////////////////
1209/// AMCC/3ware RAID support
1210
1211class linux_escalade_device
1212: public /*implements*/ ata_device,
1213  public /*extends*/ linux_smart_device
1214{
1215public:
1216  enum escalade_type_t {
1217    AMCC_3WARE_678K,
1218    AMCC_3WARE_678K_CHAR,
1219    AMCC_3WARE_9000_CHAR
1220  };
1221
1222  linux_escalade_device(smart_interface * intf, const char * dev_name,
1223    escalade_type_t escalade_type, int disknum);
1224
1225  virtual bool open();
1226
1227  virtual bool ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out);
1228
1229private:
1230  escalade_type_t m_escalade_type; ///< Controller type
1231  int m_disknum; ///< Disk number.
1232};
1233
1234linux_escalade_device::linux_escalade_device(smart_interface * intf, const char * dev_name,
1235    escalade_type_t escalade_type, int disknum)
1236: smart_device(intf, dev_name, "3ware", "3ware"),
1237  linux_smart_device(O_RDONLY | O_NONBLOCK),
1238  m_escalade_type(escalade_type), m_disknum(disknum)
1239{
1240  set_info().info_name = strprintf("%s [3ware_disk_%02d]", dev_name, disknum);
1241}
1242
1243/* This function will setup and fix device nodes for a 3ware controller. */
1244#define MAJOR_STRING_LENGTH 3
1245#define DEVICE_STRING_LENGTH 32
1246#define NODE_STRING_LENGTH 16
1247int setup_3ware_nodes(const char *nodename, const char *driver_name) {
1248  int              tw_major      = 0;
1249  int              index         = 0;
1250  char             majorstring[MAJOR_STRING_LENGTH+1];
1251  char             device_name[DEVICE_STRING_LENGTH+1];
1252  char             nodestring[NODE_STRING_LENGTH];
1253  struct stat      stat_buf;
1254  FILE             *file;
1255  int              retval = 0;
1256#ifdef WITH_SELINUX
1257  security_context_t orig_context = NULL;
1258  security_context_t node_context = NULL;
1259  int                selinux_enabled  = is_selinux_enabled();
1260  int                selinux_enforced = security_getenforce();
1261#endif
1262
1263
1264  /* First try to open up /proc/devices */
1265  if (!(file = fopen("/proc/devices", "r"))) {
1266    pout("Error opening /proc/devices to check/create 3ware device nodes\n");
1267    syserror("fopen");
1268    return 0;  // don't fail here: user might not have /proc !
1269  }
1270
1271  /* Attempt to get device major number */
1272  while (EOF != fscanf(file, "%3s %32s", majorstring, device_name)) {
1273    majorstring[MAJOR_STRING_LENGTH]='\0';
1274    device_name[DEVICE_STRING_LENGTH]='\0';
1275    if (!strncmp(device_name, nodename, DEVICE_STRING_LENGTH)) {
1276      tw_major = atoi(majorstring);
1277      break;
1278    }
1279  }
1280  fclose(file);
1281
1282  /* See if we found a major device number */
1283  if (!tw_major) {
1284    pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename, driver_name);
1285    return 2;
1286  }
1287#ifdef WITH_SELINUX
1288  /* Prepare a database of contexts for files in /dev
1289   * and save the current context */
1290  if (selinux_enabled) {
1291    if (matchpathcon_init_prefix(NULL, "/dev") < 0)
1292      pout("Error initializing contexts database for /dev");
1293    if (getfscreatecon(&orig_context) < 0) {
1294      pout("Error retrieving original SELinux fscreate context");
1295      if (selinux_enforced)
1296        matchpathcon_fini();
1297        return 6;
1298      }
1299  }
1300#endif
1301  /* Now check if nodes are correct */
1302  for (index=0; index<16; index++) {
1303    sprintf(nodestring, "/dev/%s%d", nodename, index);
1304#ifdef WITH_SELINUX
1305    /* Get context of the node and set it as the default */
1306    if (selinux_enabled) {
1307      if (matchpathcon(nodestring, S_IRUSR | S_IWUSR, &node_context) < 0) {
1308        pout("Could not retrieve context for %s", nodestring);
1309        if (selinux_enforced) {
1310          retval = 6;
1311          break;
1312        }
1313      }
1314      if (setfscreatecon(node_context) < 0) {
1315        pout ("Error setting default fscreate context");
1316        if (selinux_enforced) {
1317          retval = 6;
1318          break;
1319        }
1320      }
1321    }
1322#endif
1323    /* Try to stat the node */
1324    if ((stat(nodestring, &stat_buf))) {
1325      pout("Node %s does not exist and must be created. Check the udev rules.\n", nodestring);
1326      /* Create a new node if it doesn't exist */
1327      if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
1328        pout("problem creating 3ware device nodes %s", nodestring);
1329        syserror("mknod");
1330        retval = 3;
1331        break;
1332      } else {
1333#ifdef WITH_SELINUX
1334        if (selinux_enabled && node_context) {
1335          freecon(node_context);
1336          node_context = NULL;
1337        }
1338#endif
1339        continue;
1340      }
1341    }
1342
1343    /* See if nodes major and minor numbers are correct */
1344    if ((tw_major != (int)(major(stat_buf.st_rdev))) ||
1345        (index    != (int)(minor(stat_buf.st_rdev))) ||
1346        (!S_ISCHR(stat_buf.st_mode))) {
1347      pout("Node %s has wrong major/minor number and must be created anew."
1348          " Check the udev rules.\n", nodestring);
1349      /* Delete the old node */
1350      if (unlink(nodestring)) {
1351        pout("problem unlinking stale 3ware device node %s", nodestring);
1352        syserror("unlink");
1353        retval = 4;
1354        break;
1355      }
1356
1357      /* Make a new node */
1358      if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
1359        pout("problem creating 3ware device nodes %s", nodestring);
1360        syserror("mknod");
1361        retval = 5;
1362        break;
1363      }
1364    }
1365#ifdef WITH_SELINUX
1366    if (selinux_enabled && node_context) {
1367      freecon(node_context);
1368      node_context = NULL;
1369    }
1370#endif
1371  }
1372
1373#ifdef WITH_SELINUX
1374  if (selinux_enabled) {
1375    if(setfscreatecon(orig_context) < 0) {
1376      pout("Error re-setting original fscreate context");
1377      if (selinux_enforced)
1378        retval = 6;
1379    }
1380    if(orig_context)
1381      freecon(orig_context);
1382    if(node_context)
1383      freecon(node_context);
1384    matchpathcon_fini();
1385  }
1386#endif
1387  return retval;
1388}
1389
1390bool linux_escalade_device::open()
1391{
1392  if (m_escalade_type == AMCC_3WARE_9000_CHAR || m_escalade_type == AMCC_3WARE_678K_CHAR) {
1393    // the device nodes for these controllers are dynamically assigned,
1394    // so we need to check that they exist with the correct major
1395    // numbers and if not, create them
1396    const char * node   = (m_escalade_type == AMCC_3WARE_9000_CHAR ? "twa"    : "twe"    );
1397    const char * driver = (m_escalade_type == AMCC_3WARE_9000_CHAR ? "3w-9xxx": "3w-xxxx");
1398    if (setup_3ware_nodes(node, driver))
1399      return set_err((errno ? errno : ENXIO), "setup_3ware_nodes(\"%s\", \"%s\") failed", node, driver);
1400  }
1401  // Continue with default open
1402  return linux_smart_device::open();
1403}
1404
1405// TODO: Function no longer useful
1406//void printwarning(smart_command_set command);
1407
1408// PURPOSE
1409//   This is an interface routine meant to isolate the OS dependent
1410//   parts of the code, and to provide a debugging interface.  Each
1411//   different port and OS needs to provide it's own interface.  This
1412//   is the linux interface to the 3ware 3w-xxxx driver.  It allows ATA
1413//   commands to be passed through the SCSI driver.
1414// DETAILED DESCRIPTION OF ARGUMENTS
1415//   fd: is the file descriptor provided by open()
1416//   disknum is the disk number (0 to 15) in the RAID array
1417//   escalade_type indicates the type of controller type, and if scsi or char interface is used
1418//   command: defines the different operations.
1419//   select: additional input data if needed (which log, which type of
1420//           self-test).
1421//   data:   location to write output data, if needed (512 bytes).
1422//   Note: not all commands use all arguments.
1423// RETURN VALUES
1424//  -1 if the command failed
1425//   0 if the command succeeded,
1426//   STATUS_CHECK routine:
1427//  -1 if the command failed
1428//   0 if the command succeeded and disk SMART status is "OK"
1429//   1 if the command succeeded and disk SMART status is "FAILING"
1430
1431
1432/* 512 is the max payload size: increase if needed */
1433#define BUFFER_LEN_678K      ( sizeof(TW_Ioctl)                  ) // 1044 unpacked, 1041 packed
1434#define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1        ) // 1539 unpacked, 1536 packed
1435#define BUFFER_LEN_9000      ( sizeof(TW_Ioctl_Buf_Apache)+512-1 ) // 2051 unpacked, 2048 packed
1436#define TW_IOCTL_BUFFER_SIZE ( MAX(MAX(BUFFER_LEN_678K, BUFFER_LEN_9000), BUFFER_LEN_678K_CHAR) )
1437
1438bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out)
1439{
1440  if (!ata_cmd_is_ok(in,
1441    true, // data_out_support
1442    false, // TODO: multi_sector_support
1443    true) // ata_48bit_support
1444  )
1445    return false;
1446
1447  // Used by both the SCSI and char interfaces
1448  TW_Passthru *passthru=NULL;
1449  char ioctl_buffer[TW_IOCTL_BUFFER_SIZE];
1450
1451  // only used for SCSI device interface
1452  TW_Ioctl   *tw_ioctl=NULL;
1453  TW_Output *tw_output=NULL;
1454
1455  // only used for 6000/7000/8000 char device interface
1456  TW_New_Ioctl *tw_ioctl_char=NULL;
1457
1458  // only used for 9000 character device interface
1459  TW_Ioctl_Buf_Apache *tw_ioctl_apache=NULL;
1460
1461  memset(ioctl_buffer, 0, TW_IOCTL_BUFFER_SIZE);
1462
1463  // TODO: Handle controller differences by different classes
1464  if (m_escalade_type==AMCC_3WARE_9000_CHAR) {
1465    tw_ioctl_apache                               = (TW_Ioctl_Buf_Apache *)ioctl_buffer;
1466    tw_ioctl_apache->driver_command.control_code  = TW_IOCTL_FIRMWARE_PASS_THROUGH;
1467    tw_ioctl_apache->driver_command.buffer_length = 512; /* payload size */
1468    passthru                                      = (TW_Passthru *)&(tw_ioctl_apache->firmware_command.command.oldcommand);
1469  }
1470  else if (m_escalade_type==AMCC_3WARE_678K_CHAR) {
1471    tw_ioctl_char                                 = (TW_New_Ioctl *)ioctl_buffer;
1472    tw_ioctl_char->data_buffer_length             = 512;
1473    passthru                                      = (TW_Passthru *)&(tw_ioctl_char->firmware_command);
1474  }
1475  else if (m_escalade_type==AMCC_3WARE_678K) {
1476    tw_ioctl                                      = (TW_Ioctl *)ioctl_buffer;
1477    tw_ioctl->cdb[0]                              = TW_IOCTL;
1478    tw_ioctl->opcode                              = TW_ATA_PASSTHRU;
1479    tw_ioctl->input_length                        = 512; // correct even for non-data commands
1480    tw_ioctl->output_length                       = 512; // correct even for non-data commands
1481    tw_output                                     = (TW_Output *)tw_ioctl;
1482    passthru                                      = (TW_Passthru *)&(tw_ioctl->input_data);
1483  }
1484  else {
1485    return set_err(ENOSYS,
1486      "Unrecognized escalade_type %d in linux_3ware_command_interface(disk %d)\n"
1487      "Please contact " PACKAGE_BUGREPORT "\n", (int)m_escalade_type, m_disknum);
1488  }
1489
1490  // Same for (almost) all commands - but some reset below
1491  passthru->byte0.opcode  = TW_OP_ATA_PASSTHRU;
1492  passthru->request_id    = 0xFF;
1493  passthru->unit          = m_disknum;
1494  passthru->status        = 0;
1495  passthru->flags         = 0x1;
1496
1497  // Set registers
1498  {
1499    const ata_in_regs_48bit & r = in.in_regs;
1500    passthru->features     = r.features_16;
1501    passthru->sector_count = r.sector_count_16;
1502    passthru->sector_num   = r.lba_low_16;
1503    passthru->cylinder_lo  = r.lba_mid_16;
1504    passthru->cylinder_hi  = r.lba_high_16;
1505    passthru->drive_head   = r.device;
1506    passthru->command      = r.command;
1507  }
1508
1509  // Is this a command that reads or returns 512 bytes?
1510  // passthru->param values are:
1511  // 0x0 - non data command without TFR write check,
1512  // 0x8 - non data command with TFR write check,
1513  // 0xD - data command that returns data to host from device
1514  // 0xF - data command that writes data from host to device
1515  // passthru->size values are 0x5 for non-data and 0x07 for data
1516  bool readdata = false;
1517  if (in.direction == ata_cmd_in::data_in) {
1518    readdata=true;
1519    passthru->byte0.sgloff = 0x5;
1520    passthru->size         = 0x7; // TODO: Other value for multi-sector ?
1521    passthru->param        = 0xD;
1522    // For 64-bit to work correctly, up the size of the command packet
1523    // in dwords by 1 to account for the 64-bit single sgl 'address'
1524    // field. Note that this doesn't agree with the typedefs but it's
1525    // right (agree with kernel driver behavior/typedefs).
1526    if (m_escalade_type==AMCC_3WARE_9000_CHAR && sizeof(long)==8)
1527      passthru->size++;
1528  }
1529  else if (in.direction == ata_cmd_in::no_data) {
1530    // Non data command -- but doesn't use large sector
1531    // count register values.
1532    passthru->byte0.sgloff = 0x0;
1533    passthru->size         = 0x5;
1534    passthru->param        = 0x8;
1535    passthru->sector_count = 0x0;
1536  }
1537  else if (in.direction == ata_cmd_in::data_out) {
1538    if (m_escalade_type == AMCC_3WARE_9000_CHAR)
1539      memcpy(tw_ioctl_apache->data_buffer, in.buffer, in.size);
1540    else if (m_escalade_type == AMCC_3WARE_678K_CHAR)
1541      memcpy(tw_ioctl_char->data_buffer,   in.buffer, in.size);
1542    else {
1543      // COMMAND NOT SUPPORTED VIA SCSI IOCTL INTERFACE
1544      // memcpy(tw_output->output_data, data, 512);
1545      // printwarning(command); // TODO: Parameter no longer valid
1546      return set_err(ENOTSUP, "DATA OUT not supported for this 3ware controller type");
1547    }
1548    passthru->byte0.sgloff = 0x5;
1549    passthru->size         = 0x7;  // TODO: Other value for multi-sector ?
1550    passthru->param        = 0xF;  // PIO data write
1551    if (m_escalade_type==AMCC_3WARE_9000_CHAR && sizeof(long)==8)
1552      passthru->size++;
1553  }
1554  else
1555    return set_err(EINVAL);
1556
1557  // Now send the command down through an ioctl()
1558  int ioctlreturn;
1559  if (m_escalade_type==AMCC_3WARE_9000_CHAR)
1560    ioctlreturn=ioctl(get_fd(), TW_IOCTL_FIRMWARE_PASS_THROUGH, tw_ioctl_apache);
1561  else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
1562    ioctlreturn=ioctl(get_fd(), TW_CMD_PACKET_WITH_DATA, tw_ioctl_char);
1563  else
1564    ioctlreturn=ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND, tw_ioctl);
1565
1566  // Deal with the different error cases
1567  if (ioctlreturn) {
1568    if (AMCC_3WARE_678K==m_escalade_type
1569        && in.in_regs.command==ATA_SMART_CMD
1570        && (   in.in_regs.features == ATA_SMART_AUTO_OFFLINE
1571            || in.in_regs.features == ATA_SMART_AUTOSAVE    )
1572        && in.in_regs.lba_low) {
1573      // error here is probably a kernel driver whose version is too old
1574      // printwarning(command); // TODO: Parameter no longer valid
1575      return set_err(ENOTSUP, "Probably kernel driver too old");
1576    }
1577    return set_err(EIO);
1578  }
1579
1580  // The passthru structure is valid after return from an ioctl if:
1581  // - we are using the character interface OR
1582  // - we are using the SCSI interface and this is a NON-READ-DATA command
1583  // For SCSI interface, note that we set passthru to a different
1584  // value after ioctl().
1585  if (AMCC_3WARE_678K==m_escalade_type) {
1586    if (readdata)
1587      passthru=NULL;
1588    else
1589      passthru=(TW_Passthru *)&(tw_output->output_data);
1590  }
1591
1592  // See if the ATA command failed.  Now that we have returned from
1593  // the ioctl() call, if passthru is valid, then:
1594  // - passthru->status contains the 3ware controller STATUS
1595  // - passthru->command contains the ATA STATUS register
1596  // - passthru->features contains the ATA ERROR register
1597  //
1598  // Check bits 0 (error bit) and 5 (device fault) of the ATA STATUS
1599  // If bit 0 (error bit) is set, then ATA ERROR register is valid.
1600  // While we *might* decode the ATA ERROR register, at the moment it
1601  // doesn't make much sense: we don't care in detail why the error
1602  // happened.
1603
1604  if (passthru && (passthru->status || (passthru->command & 0x21))) {
1605    return set_err(EIO);
1606  }
1607
1608  // If this is a read data command, copy data to output buffer
1609  if (readdata) {
1610    if (m_escalade_type==AMCC_3WARE_9000_CHAR)
1611      memcpy(in.buffer, tw_ioctl_apache->data_buffer, in.size);
1612    else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
1613      memcpy(in.buffer, tw_ioctl_char->data_buffer, in.size);
1614    else
1615      memcpy(in.buffer, tw_output->output_data, in.size);
1616  }
1617
1618  // Return register values
1619  if (passthru) {
1620    ata_out_regs_48bit & r = out.out_regs;
1621    r.error           = passthru->features;
1622    r.sector_count_16 = passthru->sector_count;
1623    r.lba_low_16      = passthru->sector_num;
1624    r.lba_mid_16      = passthru->cylinder_lo;
1625    r.lba_high_16     = passthru->cylinder_hi;
1626    r.device          = passthru->drive_head;
1627    r.status          = passthru->command;
1628  }
1629
1630  // look for nonexistent devices/ports
1631  if (   in.in_regs.command == ATA_IDENTIFY_DEVICE
1632      && !nonempty((unsigned char *)in.buffer, in.size)) {
1633    return set_err(ENODEV, "No drive on port %d", m_disknum);
1634  }
1635
1636  return true;
1637}
1638
1639
1640/////////////////////////////////////////////////////////////////////////////
1641/// Areca RAID support
1642
1643class linux_areca_device
1644: public /*implements*/ ata_device_with_command_set,
1645  public /*extends*/ linux_smart_device
1646{
1647public:
1648  linux_areca_device(smart_interface * intf, const char * dev_name, int disknum);
1649
1650protected:
1651  virtual int ata_command_interface(smart_command_set command, int select, char * data);
1652
1653private:
1654  int m_disknum; ///< Disk number.
1655};
1656
1657
1658// PURPOSE
1659//   This is an interface routine meant to isolate the OS dependent
1660//   parts of the code, and to provide a debugging interface.  Each
1661//   different port and OS needs to provide it's own interface.  This
1662//   is the linux interface to the Areca "arcmsr" driver.  It allows ATA
1663//   commands to be passed through the SCSI driver.
1664// DETAILED DESCRIPTION OF ARGUMENTS
1665//   fd: is the file descriptor provided by open()
1666//   disknum is the disk number (0 to 15) in the RAID array
1667//   command: defines the different operations.
1668//   select: additional input data if needed (which log, which type of
1669//           self-test).
1670//   data:   location to write output data, if needed (512 bytes).
1671//   Note: not all commands use all arguments.
1672// RETURN VALUES
1673//  -1 if the command failed
1674//   0 if the command succeeded,
1675//   STATUS_CHECK routine:
1676//  -1 if the command failed
1677//   0 if the command succeeded and disk SMART status is "OK"
1678//   1 if the command succeeded and disk SMART status is "FAILING"
1679
1680
1681/*DeviceType*/
1682#define ARECA_SATA_RAID                         0x90000000
1683/*FunctionCode*/
1684#define FUNCTION_READ_RQBUFFER                  0x0801
1685#define FUNCTION_WRITE_WQBUFFER                 0x0802
1686#define FUNCTION_CLEAR_RQBUFFER                 0x0803
1687#define FUNCTION_CLEAR_WQBUFFER                 0x0804
1688
1689/* ARECA IO CONTROL CODE*/
1690#define ARCMSR_IOCTL_READ_RQBUFFER              (ARECA_SATA_RAID | FUNCTION_READ_RQBUFFER)
1691#define ARCMSR_IOCTL_WRITE_WQBUFFER             (ARECA_SATA_RAID | FUNCTION_WRITE_WQBUFFER)
1692#define ARCMSR_IOCTL_CLEAR_RQBUFFER             (ARECA_SATA_RAID | FUNCTION_CLEAR_RQBUFFER)
1693#define ARCMSR_IOCTL_CLEAR_WQBUFFER             (ARECA_SATA_RAID | FUNCTION_CLEAR_WQBUFFER)
1694#define ARECA_SIG_STR                                                   "ARCMSR"
1695
1696// The SRB_IO_CONTROL & SRB_BUFFER structures are used to communicate(to/from) to areca driver
1697typedef struct _SRB_IO_CONTROL
1698{
1699        unsigned int HeaderLength;
1700        unsigned char Signature[8];
1701        unsigned int Timeout;
1702        unsigned int ControlCode;
1703        unsigned int ReturnCode;
1704        unsigned int Length;
1705} sSRB_IO_CONTROL;
1706
1707typedef struct _SRB_BUFFER
1708{
1709        sSRB_IO_CONTROL srbioctl;
1710        unsigned char   ioctldatabuffer[1032]; // the buffer to put the command data to/from firmware
1711} sSRB_BUFFER;
1712
1713// Looks in /proc/scsi to suggest correct areca devices
1714// If hint not NULL, return device path guess
1715int find_areca_in_proc(char *hint) {
1716 
1717    const char* proc_format_string="host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n";
1718
1719    // check data formwat
1720    FILE *fp=fopen("/proc/scsi/sg/device_hdr", "r");
1721    if (!fp) {
1722        pout("Unable to open /proc/scsi/sg/device_hdr for reading\n");
1723        return 1;
1724     }
1725
1726     // get line, compare to format
1727     char linebuf[256];
1728     linebuf[255]='\0';
1729     char *out = fgets(linebuf, 256, fp);
1730     fclose(fp);
1731     if (!out) {
1732         pout("Unable to read contents of /proc/scsi/sg/device_hdr\n");
1733         return 2;
1734     }
1735
1736     if (strcmp(linebuf, proc_format_string)) {
1737        // wrong format!
1738        // Fix this by comparing only tokens not white space!!
1739        pout("Unexpected format %s in /proc/scsi/sg/device_hdr\n", proc_format_string);
1740        return 3;
1741     }
1742
1743    // Format is understood, now search for correct device
1744    fp=fopen("/proc/scsi/sg/devices", "r");
1745    if (!fp) return 1;
1746    int host, chan, id, lun, type, opens, qdepth, busy, online;
1747    int dev=-1;
1748    int found=0;
1749    // search all lines of /proc/scsi/sg/devices
1750    while (9 == fscanf(fp, "%d %d %d %d %d %d %d %d %d", &host, &chan, &id, &lun, &type, &opens, &qdepth, &busy, &online)) {
1751        dev++;
1752        if (id == 16 && type == 3) {
1753           // devices with id=16 and type=3 might be Areca controllers
1754           if (!found && hint) {
1755               sprintf(hint, "/dev/sg%d", dev);
1756           }
1757           pout("Device /dev/sg%d appears to be an Areca controller.\n", dev);
1758           found++;
1759        }
1760    }
1761    fclose(fp);
1762    return 0;
1763}
1764
1765
1766
1767void dumpdata( unsigned char *block, int len)
1768{
1769        int ln = (len / 16) + 1;         // total line#
1770        unsigned char c;
1771        int pos = 0;
1772
1773        printf(" Address = %p, Length = (0x%x)%d\n", block, len, len);
1774        printf("      0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F      ASCII      \n");
1775        printf("=====================================================================\n");
1776
1777        for ( int l = 0; l < ln && len; l++ )
1778        {
1779                // printf the line# and the HEX data
1780                // if a line data length < 16 then append the space to the tail of line to reach 16 chars
1781                printf("%02X | ", l);
1782                for ( pos = 0; pos < 16 && len; pos++, len-- )
1783                {
1784                        c = block[l*16+pos];   
1785                        printf("%02X ", c);
1786                }
1787
1788                if ( pos < 16 )
1789                {
1790                        for ( int loop = pos; loop < 16; loop++ )
1791                        {
1792                                printf("   ");
1793                        }
1794                }
1795
1796                // print ASCII char
1797                for ( int loop = 0; loop < pos; loop++ )
1798                {
1799                        c = block[l*16+loop];
1800                        if ( c >= 0x20 && c <= 0x7F )
1801                        {
1802                                printf("%c", c);
1803                        }
1804                        else
1805                        {
1806                                printf(".");
1807                        }
1808                }
1809                printf("\n");
1810        }   
1811        printf("=====================================================================\n");
1812}
1813
1814
1815
1816int arcmsr_command_handler(int fd, unsigned long arcmsr_cmd, unsigned char *data, int data_len, void *ext_data /* reserved for further use */)
1817{
1818        ARGUSED(ext_data);
1819
1820        int ioctlreturn = 0;
1821        sSRB_BUFFER sBuf;
1822        struct scsi_cmnd_io io_hdr; 
1823        int dir = DXFER_TO_DEVICE;
1824
1825        UINT8 cdb[10];
1826        UINT8 sense[32];
1827
1828        unsigned char *areca_return_packet;
1829        int total = 0;
1830        int expected = -1;
1831        unsigned char return_buff[2048];
1832        unsigned char *ptr = &return_buff[0];
1833        memset(return_buff, 0, sizeof(return_buff));
1834
1835        memset((unsigned char *)&sBuf, 0, sizeof(sBuf));
1836        memset(&io_hdr, 0, sizeof(io_hdr));
1837        memset(cdb, 0, sizeof(cdb));
1838        memset(sense, 0, sizeof(sense));
1839
1840
1841        sBuf.srbioctl.HeaderLength = sizeof(sSRB_IO_CONTROL);   
1842        memcpy(sBuf.srbioctl.Signature, ARECA_SIG_STR, strlen(ARECA_SIG_STR));
1843        sBuf.srbioctl.Timeout = 10000;     
1844        sBuf.srbioctl.ControlCode = ARCMSR_IOCTL_READ_RQBUFFER;
1845
1846        switch ( arcmsr_cmd )
1847        {
1848        // command for writing data to driver
1849        case ARCMSR_IOCTL_WRITE_WQBUFFER:   
1850                if ( data && data_len )
1851                {
1852                        sBuf.srbioctl.Length = data_len;   
1853                        memcpy((unsigned char *)sBuf.ioctldatabuffer, (unsigned char *)data, data_len);
1854                }
1855                // commands for clearing related buffer of driver
1856        case ARCMSR_IOCTL_CLEAR_RQBUFFER:
1857        case ARCMSR_IOCTL_CLEAR_WQBUFFER:
1858                cdb[0] = 0x3B; //SCSI_WRITE_BUF command;
1859                break;
1860                // command for reading data from driver
1861        case ARCMSR_IOCTL_READ_RQBUFFER:   
1862                cdb[0] = 0x3C; //SCSI_READ_BUF command;
1863                dir = DXFER_FROM_DEVICE;
1864                break;
1865        default:
1866                // unknown arcmsr commands
1867                return -1;
1868        }
1869
1870        cdb[1] = 0x01;
1871        cdb[2] = 0xf0;   
1872        //
1873        // cdb[5][6][7][8] areca defined command code( to/from driver )
1874        //   
1875        cdb[5] = (char)( arcmsr_cmd >> 24);
1876        cdb[6] = (char)( arcmsr_cmd >> 16);
1877        cdb[7] = (char)( arcmsr_cmd >> 8);
1878        cdb[8] = (char)( arcmsr_cmd & 0x0F );
1879
1880        io_hdr.dxfer_dir = dir;
1881        io_hdr.dxfer_len = sizeof(sBuf);
1882        io_hdr.dxferp = (unsigned char *)&sBuf; 
1883        io_hdr.cmnd = cdb;
1884        io_hdr.cmnd_len = sizeof(cdb);
1885        io_hdr.sensep = sense; 
1886        io_hdr.max_sense_len = sizeof(sense);
1887        io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
1888
1889        while ( 1 )
1890        {
1891                ioctlreturn = do_normal_scsi_cmnd_io(fd, &io_hdr, 0);
1892                if ( ioctlreturn || io_hdr.scsi_status )
1893                {
1894                        // errors found
1895                        break;
1896                }
1897
1898                if ( arcmsr_cmd != ARCMSR_IOCTL_READ_RQBUFFER )
1899                {
1900                        // if succeeded, just returns the length of outgoing data
1901                        return data_len;
1902                }
1903
1904                if ( sBuf.srbioctl.Length )
1905                {
1906                        //dumpdata(&sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
1907                        memcpy(ptr, &sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
1908                        ptr += sBuf.srbioctl.Length;
1909                        total += sBuf.srbioctl.Length;
1910                        // the returned bytes enough to compute payload length ?
1911                        if ( expected < 0 && total >= 5 )
1912                        {
1913                                areca_return_packet = (unsigned char *)&return_buff[0];
1914                                if ( areca_return_packet[0] == 0x5E && 
1915                                         areca_return_packet[1] == 0x01 && 
1916                                         areca_return_packet[2] == 0x61 )
1917                                {
1918                                        // valid header, let's compute the returned payload length,
1919                                        // we expected the total length is
1920                                        // payload + 3 bytes header + 2 bytes length + 1 byte checksum
1921                                        expected = areca_return_packet[4] * 256 + areca_return_packet[3] + 6;
1922                                }
1923                        }
1924
1925                        if ( total >= 7 && total >= expected )
1926                        {
1927                                //printf("total bytes received = %d, expected length = %d\n", total, expected);
1928
1929                                // ------ Okay! we received enough --------
1930                                break;
1931                        }
1932                }
1933        }
1934
1935        // Deal with the different error cases
1936        if ( ioctlreturn )
1937        {
1938                printf("do_scsi_cmnd_io with write buffer failed code = %x\n", ioctlreturn);
1939                return -2;
1940        }
1941
1942
1943        if ( io_hdr.scsi_status )
1944        {
1945                printf("io_hdr.scsi_status with write buffer failed code = %x\n", io_hdr.scsi_status);
1946                return -3;
1947        }
1948
1949
1950        if ( data )
1951        {
1952                memcpy(data, return_buff, total);
1953        }
1954
1955        return total;
1956}
1957
1958
1959linux_areca_device::linux_areca_device(smart_interface * intf, const char * dev_name, int disknum)
1960: smart_device(intf, dev_name, "areca", "areca"),
1961  linux_smart_device(O_RDWR | O_EXCL | O_NONBLOCK),
1962  m_disknum(disknum)
1963{
1964  set_info().info_name = strprintf("%s [areca_%02d]", dev_name, disknum);
1965}
1966
1967// Areca RAID Controller
1968int linux_areca_device::ata_command_interface(smart_command_set command, int select, char * data)
1969{
1970        // ATA input registers
1971        typedef struct _ATA_INPUT_REGISTERS
1972        {
1973                unsigned char features;
1974                unsigned char sector_count;
1975                unsigned char sector_number;
1976                unsigned char cylinder_low; 
1977                unsigned char cylinder_high;   
1978                unsigned char device_head; 
1979                unsigned char command;     
1980                unsigned char reserved[8];
1981                unsigned char data[512]; // [in/out] buffer for outgoing/incoming data
1982        } sATA_INPUT_REGISTERS;
1983
1984        // ATA output registers
1985        // Note: The output registers is re-sorted for areca internal use only
1986        typedef struct _ATA_OUTPUT_REGISTERS
1987        {
1988                unsigned char error;
1989                unsigned char status;
1990                unsigned char sector_count;
1991                unsigned char sector_number;
1992                unsigned char cylinder_low; 
1993                unsigned char cylinder_high;
1994        }sATA_OUTPUT_REGISTERS;
1995
1996        // Areca packet format for outgoing:
1997        // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
1998        // B[3~4] : 2 bytes command length + variant data length, little endian
1999        // B[5]   : 1 bytes areca defined command code, ATA passthrough command code is 0x1c
2000        // B[6~last-1] : variant bytes payload data
2001        // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
2002        //
2003        //
2004        //   header 3 bytes  length 2 bytes   cmd 1 byte    payload data x bytes  cs 1 byte
2005        // +--------------------------------------------------------------------------------+
2006        // + 0x5E 0x01 0x61 |   0x00 0x00   |     0x1c   | .................... |   0x00    |
2007        // +--------------------------------------------------------------------------------+
2008        //
2009
2010        //Areca packet format for incoming:
2011        // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
2012        // B[3~4] : 2 bytes payload length, little endian
2013        // B[5~last-1] : variant bytes returned payload data
2014        // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
2015        //
2016        //
2017        //   header 3 bytes  length 2 bytes   payload data x bytes  cs 1 byte
2018        // +-------------------------------------------------------------------+
2019        // + 0x5E 0x01 0x61 |   0x00 0x00   | .................... |   0x00    |
2020        // +-------------------------------------------------------------------+
2021        unsigned char    areca_packet[640];
2022        int areca_packet_len = sizeof(areca_packet);
2023        unsigned char cs = 0;   
2024
2025        sATA_INPUT_REGISTERS *ata_cmd;
2026
2027        // For debugging
2028#if 0
2029        memset(sInq, 0, sizeof(sInq));
2030        scsiStdInquiry(fd, (unsigned char *)sInq, (int)sizeof(sInq));
2031        dumpdata((unsigned char *)sInq, sizeof(sInq));
2032#endif
2033        memset(areca_packet, 0, areca_packet_len);
2034
2035        // ----- BEGIN TO SETUP HEADERS -------
2036        areca_packet[0] = 0x5E;
2037        areca_packet[1] = 0x01;
2038        areca_packet[2] = 0x61;
2039        areca_packet[3] = (unsigned char)((areca_packet_len - 6) & 0xff);
2040        areca_packet[4] = (unsigned char)(((areca_packet_len - 6) >> 8) & 0xff);
2041        areca_packet[5] = 0x1c; // areca defined code for ATA passthrough command
2042
2043
2044        // ----- BEGIN TO SETUP PAYLOAD DATA -----
2045
2046        memcpy(&areca_packet[7], "SmrT", 4);    // areca defined password
2047
2048        ata_cmd = (sATA_INPUT_REGISTERS *)&areca_packet[12];
2049        ata_cmd->cylinder_low    = 0x4F;
2050        ata_cmd->cylinder_high   = 0xC2;
2051
2052
2053        if ( command == READ_VALUES     ||
2054                 command == READ_THRESHOLDS ||
2055                 command == READ_LOG ||
2056                 command == IDENTIFY ||
2057                 command == PIDENTIFY )
2058        {
2059                // the commands will return data
2060                areca_packet[6] = 0x13;
2061                ata_cmd->sector_count = 0x1;
2062        }
2063        else if ( command == WRITE_LOG )
2064        {
2065                // the commands will write data
2066                areca_packet[6] = 0x14;
2067        }
2068        else
2069        {
2070                // the commands will return no data
2071                areca_packet[6] = 0x15;
2072        }
2073
2074
2075        ata_cmd->command = ATA_SMART_CMD;
2076        // Now set ATA registers depending upon command
2077        switch ( command )
2078        {
2079        case CHECK_POWER_MODE: 
2080                //printf("command = CHECK_POWER_MODE\n");
2081                ata_cmd->command = ATA_CHECK_POWER_MODE;       
2082                break;
2083        case READ_VALUES:
2084                //printf("command = READ_VALUES\n");
2085                ata_cmd->features = ATA_SMART_READ_VALUES;
2086                break;
2087        case READ_THRESHOLDS:   
2088                //printf("command = READ_THRESHOLDS\n");
2089                ata_cmd->features = ATA_SMART_READ_THRESHOLDS;
2090                break;
2091        case READ_LOG: 
2092                //printf("command = READ_LOG\n");
2093                ata_cmd->features = ATA_SMART_READ_LOG_SECTOR;
2094                ata_cmd->sector_number = select;       
2095                break;
2096        case WRITE_LOG:       
2097                //printf("command = WRITE_LOG\n");   
2098                ata_cmd->features = ATA_SMART_WRITE_LOG_SECTOR;
2099                memcpy(ata_cmd->data, data, 512);
2100                ata_cmd->sector_count = 1;
2101                ata_cmd->sector_number = select;
2102                break;
2103        case IDENTIFY:
2104                //printf("command = IDENTIFY\n");   
2105                ata_cmd->command = ATA_IDENTIFY_DEVICE;         
2106                break;
2107        case PIDENTIFY:
2108                //printf("command = PIDENTIFY\n");
2109                errno=ENODEV;
2110                return -1;
2111        case ENABLE:
2112                //printf("command = ENABLE\n");
2113                ata_cmd->features = ATA_SMART_ENABLE;
2114                break;
2115        case DISABLE:
2116                //printf("command = DISABLE\n");
2117                ata_cmd->features = ATA_SMART_DISABLE;
2118                break;
2119        case AUTO_OFFLINE:
2120                //printf("command = AUTO_OFFLINE\n");
2121                ata_cmd->features = ATA_SMART_AUTO_OFFLINE;
2122                // Enable or disable?
2123                ata_cmd->sector_count = select;
2124                break;
2125        case AUTOSAVE:
2126                //printf("command = AUTOSAVE\n");
2127                ata_cmd->features = ATA_SMART_AUTOSAVE;
2128                // Enable or disable?
2129                ata_cmd->sector_count = select;
2130                break;
2131        case IMMEDIATE_OFFLINE:
2132                //printf("command = IMMEDIATE_OFFLINE\n");
2133                ata_cmd->features = ATA_SMART_IMMEDIATE_OFFLINE;
2134                // What test type to run?
2135                ata_cmd->sector_number = select;
2136                break;
2137        case STATUS_CHECK:
2138                //printf("command = STATUS_CHECK\n");
2139                ata_cmd->features = ATA_SMART_STATUS;           
2140                break;
2141        case STATUS:
2142                //printf("command = STATUS\n");
2143                ata_cmd->features = ATA_SMART_STATUS;       
2144                break;
2145        default:
2146                //printf("command = UNKNOWN\n");
2147                errno=ENOSYS;
2148                return -1;
2149        };
2150
2151        areca_packet[11] = m_disknum - 1;                  // drive number
2152
2153        // ----- BEGIN TO SETUP CHECKSUM -----
2154        for ( int loop = 3; loop < areca_packet_len - 1; loop++ )
2155        {
2156                cs += areca_packet[loop]; 
2157        }
2158        areca_packet[areca_packet_len-1] = cs;
2159
2160        // ----- BEGIN TO SEND TO ARECA DRIVER ------
2161        int expected = 0;       
2162        unsigned char return_buff[2048];
2163        memset(return_buff, 0, sizeof(return_buff));
2164
2165        expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_RQBUFFER, NULL, 0, NULL);
2166        if (expected==-3) {
2167            find_areca_in_proc(NULL);
2168            return -1;
2169        }
2170
2171        expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_WQBUFFER, NULL, 0, NULL);
2172        expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_WRITE_WQBUFFER, areca_packet, areca_packet_len, NULL);
2173        if ( expected > 0 )
2174        {
2175                expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_READ_RQBUFFER, return_buff, sizeof(return_buff), NULL);
2176        }
2177        if ( expected < 0 )
2178        {
2179                return -1;
2180        }
2181
2182        // ----- VERIFY THE CHECKSUM -----
2183        cs = 0;
2184        for ( int loop = 3; loop < expected - 1; loop++ )
2185        {
2186                cs += return_buff[loop]; 
2187        }
2188
2189        if ( return_buff[expected - 1] != cs )
2190        {
2191                errno = EIO;
2192                return -1;
2193        }
2194
2195        sATA_OUTPUT_REGISTERS *ata_out = (sATA_OUTPUT_REGISTERS *)&return_buff[5] ;
2196        if ( ata_out->status )
2197        {
2198                if ( command == IDENTIFY )
2199                {
2200                        pout("The firmware of your Areca RAID controller appears to be outdated!\n" \
2201                                 "Please update your controller to firmware version 1.46 or later.\n" \
2202                                 "You may download it here: ftp://ftp.areca.com.tw/RaidCards/BIOS_Firmware\n\n");
2203                }
2204                errno = EIO;
2205                return -1;
2206        }
2207
2208        // returns with data
2209        if ( command == READ_VALUES     ||
2210                 command == READ_THRESHOLDS ||
2211                 command == READ_LOG ||
2212                 command == IDENTIFY ||
2213                 command == PIDENTIFY )
2214        {
2215                memcpy(data, &return_buff[7], 512); 
2216        }
2217
2218        if ( command == CHECK_POWER_MODE )
2219        {
2220                data[0] = ata_out->sector_count;
2221        }
2222
2223        if ( command == STATUS_CHECK &&
2224                 ( ata_out->cylinder_low == 0xF4 && ata_out->cylinder_high == 0x2C ) )
2225        {
2226                return 1;
2227        }
2228
2229        return 0;
2230}
2231
2232
2233/////////////////////////////////////////////////////////////////////////////
2234/// Marvell support
2235
2236class linux_marvell_device
2237: public /*implements*/ ata_device_with_command_set,
2238  public /*extends*/ linux_smart_device
2239{
2240public:
2241  linux_marvell_device(smart_interface * intf, const char * dev_name, const char * req_type);
2242
2243protected:
2244  virtual int ata_command_interface(smart_command_set command, int select, char * data);
2245};
2246
2247linux_marvell_device::linux_marvell_device(smart_interface * intf,
2248  const char * dev_name, const char * req_type)
2249: smart_device(intf, dev_name, "marvell", req_type),
2250  linux_smart_device(O_RDONLY | O_NONBLOCK)
2251{
2252}
2253
2254int linux_marvell_device::ata_command_interface(smart_command_set command, int select, char * data)
2255{
2256  typedef struct {
2257    int  inlen;
2258    int  outlen;
2259    char cmd[540];
2260  } mvsata_scsi_cmd;
2261
2262  int copydata = 0;
2263  mvsata_scsi_cmd  smart_command;
2264  unsigned char *buff = (unsigned char *)&smart_command.cmd[6];
2265  // See struct hd_drive_cmd_hdr in hdreg.h
2266  // buff[0]: ATA COMMAND CODE REGISTER
2267  // buff[1]: ATA SECTOR NUMBER REGISTER
2268  // buff[2]: ATA FEATURES REGISTER
2269  // buff[3]: ATA SECTOR COUNT REGISTER
2270
2271  // clear out buff.  Large enough for HDIO_DRIVE_CMD (4+512 bytes)
2272  memset(&smart_command, 0, sizeof(smart_command));
2273  smart_command.inlen = 540;
2274  smart_command.outlen = 540;
2275  smart_command.cmd[0] = 0xC;  //Vendor-specific code
2276  smart_command.cmd[4] = 6;     //command length
2277
2278  buff[0] = ATA_SMART_CMD;
2279  switch (command){
2280  case CHECK_POWER_MODE:
2281    buff[0]=ATA_CHECK_POWER_MODE;
2282    break;
2283  case READ_VALUES:
2284    buff[2]=ATA_SMART_READ_VALUES;
2285    copydata=buff[3]=1;
2286    break;
2287  case READ_THRESHOLDS:
2288    buff[2]=ATA_SMART_READ_THRESHOLDS;
2289    copydata=buff[1]=buff[3]=1;
2290    break;
2291  case READ_LOG:
2292    buff[2]=ATA_SMART_READ_LOG_SECTOR;
2293    buff[1]=select;
2294    copydata=buff[3]=1;
2295    break;
2296  case IDENTIFY:
2297    buff[0]=ATA_IDENTIFY_DEVICE;
2298    copydata=buff[3]=1;
2299    break;
2300  case PIDENTIFY:
2301    buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
2302    copydata=buff[3]=1;
2303    break;
2304  case ENABLE:
2305    buff[2]=ATA_SMART_ENABLE;
2306    buff[1]=1;
2307    break;
2308  case DISABLE:
2309    buff[2]=ATA_SMART_DISABLE;
2310    buff[1]=1;
2311    break;
2312  case STATUS:
2313  case STATUS_CHECK:
2314    // this command only says if SMART is working.  It could be
2315    // replaced with STATUS_CHECK below.
2316    buff[2] = ATA_SMART_STATUS;
2317    break;
2318  case AUTO_OFFLINE:
2319    buff[2]=ATA_SMART_AUTO_OFFLINE;
2320    buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
2321    break;
2322  case AUTOSAVE:
2323    buff[2]=ATA_SMART_AUTOSAVE;
2324    buff[3]=select;   // YET NOTE - THIS IS A NON-DATA COMMAND!!
2325    break;
2326  case IMMEDIATE_OFFLINE:
2327    buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
2328    buff[1]=select;
2329    break;
2330  default:
2331    pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command);
2332    EXIT(1);
2333    break;
2334  }
2335  // There are two different types of ioctls().  The HDIO_DRIVE_TASK
2336  // one is this:
2337  // We are now doing the HDIO_DRIVE_CMD type ioctl.
2338  if (ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND, (void *)&smart_command))
2339      return -1;
2340
2341  if (command==CHECK_POWER_MODE) {
2342    // LEON -- CHECK THIS PLEASE.  THIS SHOULD BE THE SECTOR COUNT
2343    // REGISTER, AND IT MIGHT BE buff[2] NOT buff[3].  Bruce
2344    data[0]=buff[3];
2345    return 0;
2346  }
2347
2348  // Always succeed on a SMART status, as a disk that failed returned
2349  // buff[4]=0xF4, buff[5]=0x2C, i.e. "Bad SMART status" (see below).
2350  if (command == STATUS)
2351    return 0;
2352  //Data returned is starting from 0 offset
2353  if (command == STATUS_CHECK)
2354  {
2355    // Cyl low and Cyl high unchanged means "Good SMART status"
2356    if (buff[4] == 0x4F && buff[5] == 0xC2)
2357      return 0;
2358    // These values mean "Bad SMART status"
2359    if (buff[4] == 0xF4 && buff[5] == 0x2C)
2360      return 1;
2361    // We haven't gotten output that makes sense; print out some debugging info
2362    syserror("Error SMART Status command failed");
2363    pout("Please get assistance from %s\n",PACKAGE_BUGREPORT);
2364    pout("Register values returned from SMART Status command are:\n");
2365    pout("CMD =0x%02x\n",(int)buff[0]);
2366    pout("FR =0x%02x\n",(int)buff[1]);
2367    pout("NS =0x%02x\n",(int)buff[2]);
2368    pout("SC =0x%02x\n",(int)buff[3]);
2369    pout("CL =0x%02x\n",(int)buff[4]);
2370    pout("CH =0x%02x\n",(int)buff[5]);
2371    pout("SEL=0x%02x\n",(int)buff[6]);
2372    return -1;
2373  }
2374
2375  if (copydata)
2376    memcpy(data, buff, 512);
2377  return 0;
2378}
2379
2380
2381/////////////////////////////////////////////////////////////////////////////
2382/// Highpoint RAID support
2383
2384class linux_highpoint_device
2385: public /*implements*/ ata_device_with_command_set,
2386  public /*extends*/ linux_smart_device
2387{
2388public:
2389  linux_highpoint_device(smart_interface * intf, const char * dev_name,
2390    unsigned char controller, unsigned char channel, unsigned char port);
2391
2392protected:
2393  virtual int ata_command_interface(smart_command_set command, int select, char * data);
2394
2395private:
2396  unsigned char m_hpt_data[3]; ///< controller/channel/port
2397};
2398
2399linux_highpoint_device::linux_highpoint_device(smart_interface * intf, const char * dev_name,
2400  unsigned char controller, unsigned char channel, unsigned char port)
2401: smart_device(intf, dev_name, "hpt", "hpt"),
2402  linux_smart_device(O_RDONLY | O_NONBLOCK)
2403{
2404  m_hpt_data[0] = controller; m_hpt_data[1] = channel; m_hpt_data[2] = port;
2405  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]);
2406}
2407
2408// this implementation is derived from ata_command_interface with a header
2409// packing for highpoint linux driver ioctl interface
2410//
2411// ioctl(fd,HPTIO_CTL,buff)
2412//          ^^^^^^^^^
2413//
2414// structure of hpt_buff
2415// +----+----+----+----+--------------------.....---------------------+
2416// | 1  | 2  | 3  | 4  | 5                                            |
2417// +----+----+----+----+--------------------.....---------------------+
2418//
2419// 1: The target controller                     [ int    ( 4 Bytes ) ]
2420// 2: The channel of the target controllee      [ int    ( 4 Bytes ) ]
2421// 3: HDIO_ ioctl call                          [ int    ( 4 Bytes ) ]
2422//    available from ${LINUX_KERNEL_SOURCE}/Documentation/ioctl/hdio
2423// 4: the pmport that disk attached,            [ int    ( 4 Bytes ) ]
2424//    if no pmport device, set to 1 or leave blank
2425// 5: data                                      [ void * ( var leangth ) ]
2426//
2427#define STRANGE_BUFFER_LENGTH (4+512*0xf8)
2428
2429int linux_highpoint_device::ata_command_interface(smart_command_set command, int select, char * data)
2430{
2431  unsigned char hpt_buff[4*sizeof(int) + STRANGE_BUFFER_LENGTH];
2432  unsigned int *hpt = (unsigned int *)hpt_buff;
2433  unsigned char *buff = &hpt_buff[4*sizeof(int)];
2434  int copydata = 0;
2435  const int HDIO_DRIVE_CMD_OFFSET = 4;
2436
2437  memset(hpt_buff, 0, 4*sizeof(int) + STRANGE_BUFFER_LENGTH);
2438  hpt[0] = m_hpt_data[0]; // controller id
2439  hpt[1] = m_hpt_data[1]; // channel number
2440  hpt[3] = m_hpt_data[2]; // pmport number
2441
2442  buff[0]=ATA_SMART_CMD;
2443  switch (command){
2444  case CHECK_POWER_MODE:
2445    buff[0]=ATA_CHECK_POWER_MODE;
2446    copydata=1;
2447    break;
2448  case READ_VALUES:
2449    buff[2]=ATA_SMART_READ_VALUES;
2450    buff[3]=1;
2451    copydata=512;
2452    break;
2453  case READ_THRESHOLDS:
2454    buff[2]=ATA_SMART_READ_THRESHOLDS;
2455    buff[1]=buff[3]=1;
2456    copydata=512;
2457    break;
2458  case READ_LOG:
2459    buff[2]=ATA_SMART_READ_LOG_SECTOR;
2460    buff[1]=select;
2461    buff[3]=1;
2462    copydata=512;
2463    break;
2464  case WRITE_LOG:
2465    break;
2466  case IDENTIFY:
2467    buff[0]=ATA_IDENTIFY_DEVICE;
2468    buff[3]=1;
2469    copydata=512;
2470    break;
2471  case PIDENTIFY:
2472    buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
2473    buff[3]=1;
2474    copydata=512;
2475    break;
2476  case ENABLE:
2477    buff[2]=ATA_SMART_ENABLE;
2478    buff[1]=1;
2479    break;
2480  case DISABLE:
2481    buff[2]=ATA_SMART_DISABLE;
2482    buff[1]=1;
2483    break;
2484  case STATUS:
2485    buff[2]=ATA_SMART_STATUS;
2486    break;
2487  case AUTO_OFFLINE:
2488    buff[2]=ATA_SMART_AUTO_OFFLINE;
2489    buff[3]=select;
2490    break;
2491  case AUTOSAVE:
2492    buff[2]=ATA_SMART_AUTOSAVE;
2493    buff[3]=select;
2494    break;
2495  case IMMEDIATE_OFFLINE:
2496    buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
2497    buff[1]=select;
2498    break;
2499  case STATUS_CHECK:
2500    buff[1]=ATA_SMART_STATUS;
2501    break;
2502  default:
2503    pout("Unrecognized command %d in linux_highpoint_command_interface()\n"
2504         "Please contact " PACKAGE_BUGREPORT "\n", command);
2505    errno=ENOSYS;
2506    return -1;
2507  }
2508
2509  if (command==WRITE_LOG) {
2510    unsigned char task[4*sizeof(int)+sizeof(ide_task_request_t)+512];
2511    unsigned int *hpt = (unsigned int *)task;
2512    ide_task_request_t *reqtask = (ide_task_request_t *)(&task[4*sizeof(int)]);
2513    task_struct_t *taskfile = (task_struct_t *)reqtask->io_ports;
2514    int retval;
2515
2516    memset(task, 0, sizeof(task));
2517
2518    hpt[0] = m_hpt_data[0]; // controller id
2519    hpt[1] = m_hpt_data[1]; // channel number
2520    hpt[3] = m_hpt_data[2]; // pmport number
2521    hpt[2] = HDIO_DRIVE_TASKFILE; // real hd ioctl
2522
2523    taskfile->data           = 0;
2524    taskfile->feature        = ATA_SMART_WRITE_LOG_SECTOR;
2525    taskfile->sector_count   = 1;
2526    taskfile->sector_number  = select;
2527    taskfile->low_cylinder   = 0x4f;
2528    taskfile->high_cylinder  = 0xc2;
2529    taskfile->device_head    = 0;
2530    taskfile->command        = ATA_SMART_CMD;
2531
2532    reqtask->data_phase      = TASKFILE_OUT;
2533    reqtask->req_cmd         = IDE_DRIVE_TASK_OUT;
2534    reqtask->out_size        = 512;
2535    reqtask->in_size         = 0;
2536
2537    memcpy(task+sizeof(ide_task_request_t)+4*sizeof(int), data, 512);
2538
2539    if ((retval=ioctl(get_fd(), HPTIO_CTL, task))) {
2540      if (retval==-EINVAL)
2541        pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
2542      return -1;
2543    }
2544    return 0;
2545  }
2546
2547  if (command==STATUS_CHECK){
2548    int retval;
2549    unsigned const char normal_lo=0x4f, normal_hi=0xc2;
2550    unsigned const char failed_lo=0xf4, failed_hi=0x2c;
2551    buff[4]=normal_lo;
2552    buff[5]=normal_hi;
2553
2554    hpt[2] = HDIO_DRIVE_TASK;
2555
2556    if ((retval=ioctl(get_fd(), HPTIO_CTL, hpt_buff))) {
2557      if (retval==-EINVAL) {
2558        pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
2559        pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
2560      }
2561      else
2562        syserror("Error SMART Status command failed");
2563      return -1;
2564    }
2565
2566    if (buff[4]==normal_lo && buff[5]==normal_hi)
2567      return 0;
2568
2569    if (buff[4]==failed_lo && buff[5]==failed_hi)
2570      return 1;
2571
2572    syserror("Error SMART Status command failed");
2573    pout("Please get assistance from " PACKAGE_HOMEPAGE "\n");
2574    pout("Register values returned from SMART Status command are:\n");
2575    pout("CMD=0x%02x\n",(int)buff[0]);
2576    pout("FR =0x%02x\n",(int)buff[1]);
2577    pout("NS =0x%02x\n",(int)buff[2]);
2578    pout("SC =0x%02x\n",(int)buff[3]);
2579    pout("CL =0x%02x\n",(int)buff[4]);
2580    pout("CH =0x%02x\n",(int)buff[5]);
2581    pout("SEL=0x%02x\n",(int)buff[6]);
2582    return -1;
2583  }
2584
2585#if 1
2586  if (command==IDENTIFY || command==PIDENTIFY) {
2587    unsigned char deviceid[4*sizeof(int)+512*sizeof(char)];
2588    unsigned int *hpt = (unsigned int *)deviceid;
2589
2590    hpt[0] = m_hpt_data[0]; // controller id
2591    hpt[1] = m_hpt_data[1]; // channel number
2592    hpt[3] = m_hpt_data[2]; // pmport number
2593
2594    hpt[2] = HDIO_GET_IDENTITY;
2595    if (!ioctl(get_fd(), HPTIO_CTL, deviceid) && (deviceid[4*sizeof(int)] & 0x8000))
2596      buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
2597  }
2598#endif
2599
2600  hpt[2] = HDIO_DRIVE_CMD;
2601  if ((ioctl(get_fd(), HPTIO_CTL, hpt_buff)))
2602    return -1;
2603
2604  if (command==CHECK_POWER_MODE)
2605    buff[HDIO_DRIVE_CMD_OFFSET]=buff[2];
2606
2607  if (copydata)
2608    memcpy(data, buff+HDIO_DRIVE_CMD_OFFSET, copydata);
2609
2610  return 0;
2611}
2612
2613
2614#if 0 // TODO: Migrate from 'smart_command_set' to 'ata_in_regs' OR remove the function
2615// Utility function for printing warnings
2616void printwarning(smart_command_set command){
2617  static int printed[4]={0,0,0,0};
2618  const char* message=
2619    "can not be passed through the 3ware 3w-xxxx driver.  This can be fixed by\n"
2620    "applying a simple 3w-xxxx driver patch that can be found here:\n"
2621    PACKAGE_HOMEPAGE "\n"
2622    "Alternatively, upgrade your 3w-xxxx driver to version 1.02.00.037 or greater.\n\n";
2623
2624  if (command==AUTO_OFFLINE && !printed[0]) {
2625    printed[0]=1;
2626    pout("The SMART AUTO-OFFLINE ENABLE command (smartmontools -o on option/Directive)\n%s", message);
2627  }
2628  else if (command==AUTOSAVE && !printed[1]) {
2629    printed[1]=1;
2630    pout("The SMART AUTOSAVE ENABLE command (smartmontools -S on option/Directive)\n%s", message);
2631  }
2632  else if (command==STATUS_CHECK && !printed[2]) {
2633    printed[2]=1;
2634    pout("The SMART RETURN STATUS return value (smartmontools -H option/Directive)\n%s", message);
2635  }
2636  else if (command==WRITE_LOG && !printed[3])  {
2637    printed[3]=1;
2638    pout("The SMART WRITE LOG command (smartmontools -t selective) only supported via char /dev/tw[ae] interface\n");
2639  }
2640
2641  return;
2642}
2643#endif
2644
2645
2646/////////////////////////////////////////////////////////////////////////////
2647/// SCSI open with autodetection support
2648
2649smart_device * linux_scsi_device::autodetect_open()
2650{
2651  // Open device
2652  if (!open())
2653    return this;
2654
2655  // No Autodetection if device type was specified by user
2656  bool sat_only = false;
2657  if (*get_req_type()) {
2658    // Detect SAT if device object was created by scan_smart_devices().
2659    if (!(m_scanning && !strcmp(get_req_type(), "sat")))
2660      return this;
2661    sat_only = true;
2662  }
2663
2664  // The code below is based on smartd.cpp:SCSIFilterKnown()
2665
2666  // Get INQUIRY
2667  unsigned char req_buff[64] = {0, };
2668  int req_len = 36;
2669  if (scsiStdInquiry(this, req_buff, req_len)) {
2670    // Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices
2671    // watch this spot ... other devices could lock up here
2672    req_len = 64;
2673    if (scsiStdInquiry(this, req_buff, req_len)) {
2674      // device doesn't like INQUIRY commands
2675      close();
2676      set_err(EIO, "INQUIRY failed");
2677      return this;
2678    }
2679  }
2680
2681  int avail_len = req_buff[4] + 5;
2682  int len = (avail_len < req_len ? avail_len : req_len);
2683  if (len < 36) {
2684    if (sat_only) {
2685      close();
2686      set_err(EIO, "INQUIRY too short for SAT");
2687    }
2688    return this;
2689  }
2690
2691  // Use INQUIRY to detect type
2692  if (!sat_only) {
2693
2694    // 3ware ?
2695    if (!memcmp(req_buff + 8, "3ware", 5) || !memcmp(req_buff + 8, "AMCC", 4)) {
2696      close();
2697      set_err(EINVAL, "AMCC/3ware controller, please try adding '-d 3ware,N',\n"
2698                      "you may need to replace %s with /dev/twaN or /dev/tweN", get_dev_name());
2699      return this;
2700    }
2701
2702    // DELL?
2703    if (!memcmp(req_buff + 8, "DELL    PERC", 12) || !memcmp(req_buff + 8, "MegaRAID", 8)) {
2704      close();
2705      set_err(EINVAL, "DELL or MegaRaid controller, please try adding '-d megaraid,N'");
2706      return this;
2707    }
2708
2709    // Marvell ?
2710    if (len >= 42 && !memcmp(req_buff + 36, "MVSATA", 6)) {
2711      //pout("Device %s: using '-d marvell' for ATA disk with Marvell driver\n", get_dev_name());
2712      close();
2713      smart_device_auto_ptr newdev(
2714        new linux_marvell_device(smi(), get_dev_name(), get_req_type())
2715      );
2716      newdev->open(); // TODO: Can possibly pass open fd
2717      delete this;
2718      return newdev.release();
2719    }
2720  }
2721
2722  // SAT or USB ?
2723  {
2724    smart_device * newdev = smi()->autodetect_sat_device(this, req_buff, len);
2725    if (newdev)
2726      // NOTE: 'this' is now owned by '*newdev'
2727      return newdev;
2728  }
2729
2730  // Nothing special found
2731
2732  if (sat_only) {
2733    close();
2734    set_err(EIO, "Not a SAT device");
2735  }
2736  return this;
2737}
2738
2739
2740//////////////////////////////////////////////////////////////////////
2741// USB bridge ID detection
2742
2743// Read USB ID from /sys file
2744static bool read_id(const std::string & path, unsigned short & id)
2745{
2746  FILE * f = fopen(path.c_str(), "r");
2747  if (!f)
2748    return false;
2749  int n = -1;
2750  bool ok = (fscanf(f, "%hx%n", &id, &n) == 1 && n == 4);
2751  fclose(f);
2752  return ok;
2753}
2754
2755// Get USB bridge ID for "sdX"
2756static bool get_usb_id(const char * name, unsigned short & vendor_id,
2757                       unsigned short & product_id, unsigned short & version)
2758{
2759  // Only "sdX" supported
2760  if (!(!strncmp(name, "sd", 2) && !strchr(name, '/')))
2761    return false;
2762
2763  // Start search at dir referenced by symlink "/sys/block/sdX/device"
2764  // -> "/sys/devices/.../usb*/.../host*/target*/..."
2765  std::string dir = strprintf("/sys/block/%s/device", name);
2766
2767  // Stop search at "/sys/devices"
2768  struct stat st;
2769  if (stat("/sys/devices", &st))
2770    return false;
2771  ino_t stop_ino = st.st_ino;
2772
2773  // Search in parent directories until "idVendor" is found,
2774  // fail if "/sys/devices" reached or too many iterations
2775  int cnt = 0;
2776  do {
2777    dir += "/..";
2778    if (!(++cnt < 10 && !stat(dir.c_str(), &st) && st.st_ino != stop_ino))
2779      return false;
2780  } while (access((dir + "/idVendor").c_str(), 0));
2781
2782  // Read IDs
2783  if (!(   read_id(dir + "/idVendor", vendor_id)
2784        && read_id(dir + "/idProduct", product_id)
2785        && read_id(dir + "/bcdDevice", version)   ))
2786    return false;
2787
2788  if (con->reportscsiioctl > 1)
2789    pout("USB ID = 0x%04x:0x%04x (0x%03x)\n", vendor_id, product_id, version);
2790  return true;
2791}
2792
2793
2794//////////////////////////////////////////////////////////////////////
2795/// Linux interface
2796
2797class linux_smart_interface
2798: public /*implements*/ smart_interface
2799{
2800public:
2801  virtual std::string get_app_examples(const char * appname);
2802
2803  virtual bool scan_smart_devices(smart_device_list & devlist, const char * type,
2804    const char * pattern = 0);
2805
2806protected:
2807  virtual ata_device * get_ata_device(const char * name, const char * type);
2808
2809  virtual scsi_device * get_scsi_device(const char * name, const char * type);
2810
2811  virtual smart_device * autodetect_smart_device(const char * name);
2812
2813  virtual smart_device * get_custom_smart_device(const char * name, const char * type);
2814
2815  virtual std::string get_valid_custom_dev_types_str();
2816
2817private:
2818  bool get_dev_list(smart_device_list & devlist, const char * pattern,
2819    bool scan_ata, bool scan_scsi, const char * req_type, bool autodetect);
2820
2821  smart_device * missing_option(const char * opt);
2822};
2823
2824std::string linux_smart_interface::get_app_examples(const char * appname)
2825{
2826  if (!strcmp(appname, "smartctl"))
2827    return smartctl_examples;
2828  return "";
2829}
2830
2831
2832// we are going to take advantage of the fact that Linux's devfs will only
2833// have device entries for devices that exist.  So if we get the equivalent of
2834// ls /dev/hd[a-t], we have all the ATA devices on the system
2835bool linux_smart_interface::get_dev_list(smart_device_list & devlist,
2836  const char * pattern, bool scan_ata, bool scan_scsi,
2837  const char * req_type, bool autodetect)
2838{
2839  // Use glob to look for any directory entries matching the pattern
2840  glob_t globbuf;
2841  memset(&globbuf, 0, sizeof(globbuf));
2842  int retglob = glob(pattern, GLOB_ERR, NULL, &globbuf);
2843  if (retglob) {
2844    //  glob failed: free memory and return
2845    globfree(&globbuf);
2846
2847    if (retglob==GLOB_NOMATCH){
2848      pout("glob(3) found no matches for pattern %s\n", pattern);
2849      return true;
2850    }
2851
2852    if (retglob==GLOB_NOSPACE)
2853      set_err(ENOMEM, "glob(3) ran out of memory matching pattern %s", pattern);
2854#ifdef GLOB_ABORTED // missing in old versions of glob.h
2855    else if (retglob==GLOB_ABORTED)
2856      set_err(EINVAL, "glob(3) aborted matching pattern %s", pattern);
2857#endif
2858    else
2859      set_err(EINVAL, "Unexplained error in glob(3) of pattern %s", pattern);
2860
2861    return false;
2862  }
2863
2864  // did we find too many paths?
2865  const int max_pathc = 32;
2866  int n = (int)globbuf.gl_pathc;
2867  if (n > max_pathc) {
2868    pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n",
2869         n, max_pathc, pattern, n - max_pathc);
2870    n = max_pathc;
2871  }
2872
2873  // now step through the list returned by glob.  If not a link, copy
2874  // to list.  If it is a link, evaluate it and see if the path ends
2875  // in "disc".
2876  for (int i = 0; i < n; i++){
2877    // see if path is a link
2878    char linkbuf[1024];
2879    int retlink = readlink(globbuf.gl_pathv[i], linkbuf, sizeof(linkbuf)-1);
2880
2881    char tmpname[1024]={0};
2882    const char * name = 0;
2883    bool is_scsi = scan_scsi;
2884    // if not a link (or a strange link), keep it
2885    if (retlink<=0 || retlink>1023)
2886      name = globbuf.gl_pathv[i];
2887    else {
2888      // or if it's a link that points to a disc, follow it
2889      linkbuf[retlink] = 0;
2890      const char *p;
2891      if ((p=strrchr(linkbuf, '/')) && !strcmp(p+1, "disc"))
2892        // This is the branch of the code that gets followed if we are
2893        // using devfs WITH traditional compatibility links. In this
2894        // case, we add the traditional device name to the list that
2895        // is returned.
2896        name = globbuf.gl_pathv[i];
2897      else {
2898        // This is the branch of the code that gets followed if we are
2899        // using devfs WITHOUT traditional compatibility links.  In
2900        // this case, we check that the link to the directory is of
2901        // the correct type, and then append "disc" to it.
2902        bool match_ata  = strstr(linkbuf, "ide");
2903        bool match_scsi = strstr(linkbuf, "scsi");
2904        if (((match_ata && scan_ata) || (match_scsi && scan_scsi)) && !(match_ata && match_scsi)) {
2905          is_scsi = match_scsi;
2906          snprintf(tmpname, sizeof(tmpname), "%s/disc", globbuf.gl_pathv[i]);
2907          name = tmpname;
2908        }
2909      }
2910    }
2911
2912    if (name) {
2913      // Found a name, add device to list.
2914      smart_device * dev;
2915      if (autodetect)
2916        dev = autodetect_smart_device(name);
2917      else if (is_scsi)
2918        dev = new linux_scsi_device(this, name, req_type, true /*scanning*/);
2919      else
2920        dev = new linux_ata_device(this, name, req_type);
2921      if (dev) // autodetect_smart_device() may return nullptr.
2922        devlist.push_back(dev);
2923    }
2924  }
2925
2926  // free memory
2927  globfree(&globbuf);
2928
2929  return true;
2930}
2931
2932bool linux_smart_interface::scan_smart_devices(smart_device_list & devlist,
2933  const char * type, const char * pattern /*= 0*/)
2934{
2935  if (pattern) {
2936    set_err(EINVAL, "DEVICESCAN with pattern not implemented yet");
2937    return false;
2938  }
2939
2940  if (!type)
2941    type = "";
2942
2943  bool scan_ata  = (!*type || !strcmp(type, "ata" ));
2944  // "sat" detection will be later handled in linux_scsi_device::autodetect_open()
2945  bool scan_scsi = (!*type || !strcmp(type, "scsi") || !strcmp(type, "sat"));
2946  if (!(scan_ata || scan_scsi))
2947    return true;
2948
2949  if (scan_ata)
2950    get_dev_list(devlist, "/dev/hd[a-t]", true, false, type, false);
2951  if (scan_scsi) // Try USB autodetection if no type specifed
2952    get_dev_list(devlist, "/dev/sd[a-z]", false, true, type, !*type);
2953
2954  // if we found traditional links, we are done
2955  if (devlist.size() > 0)
2956    return true;
2957
2958  // else look for devfs entries without traditional links
2959  // TODO: Add udev support
2960  return get_dev_list(devlist, "/dev/discs/disc*", scan_ata, scan_scsi, type, false);
2961}
2962
2963ata_device * linux_smart_interface::get_ata_device(const char * name, const char * type)
2964{
2965  return new linux_ata_device(this, name, type);
2966}
2967
2968scsi_device * linux_smart_interface::get_scsi_device(const char * name, const char * type)
2969{
2970  return new linux_scsi_device(this, name, type);
2971}
2972
2973smart_device * linux_smart_interface::missing_option(const char * opt)
2974{
2975  set_err(EINVAL, "requires option '%s'", opt);
2976  return 0;
2977}
2978
2979// Return true if STR starts with PREFIX.
2980static bool str_starts_with(const char * str, const char * prefix)
2981{
2982  return !strncmp(str, prefix, strlen(prefix));
2983}
2984
2985// Guess device type (ata or scsi) based on device name (Linux
2986// specific) SCSI device name in linux can be sd, sr, scd, st, nst,
2987// osst, nosst and sg.
2988static const char * lin_dev_prefix = "/dev/";
2989static const char * lin_dev_ata_disk_plus = "h";
2990static const char * lin_dev_ata_devfs_disk_plus = "ide/";
2991static const char * lin_dev_scsi_devfs_disk_plus = "scsi/";
2992static const char * lin_dev_scsi_disk_plus = "s";
2993static const char * lin_dev_scsi_tape1 = "ns";
2994static const char * lin_dev_scsi_tape2 = "os";
2995static const char * lin_dev_scsi_tape3 = "nos";
2996static const char * lin_dev_3ware_9000_char = "twa";
2997static const char * lin_dev_3ware_678k_char = "twe";
2998static const char * lin_dev_cciss_dir = "cciss/";
2999static const char * lin_dev_areca = "sg";
3000
3001smart_device * linux_smart_interface::autodetect_smart_device(const char * name)
3002{
3003  const char * dev_name = name; // TODO: Remove this hack
3004  int dev_prefix_len = strlen(lin_dev_prefix);
3005
3006  // if dev_name null, or string length zero
3007  int len;
3008  if (!dev_name || !(len = strlen(dev_name)))
3009    return 0;
3010
3011  // Dereference if /dev/disk/by-*/* symlink
3012  char linkbuf[100];
3013  if (   str_starts_with(dev_name, "/dev/disk/by-")
3014      && readlink(dev_name, linkbuf, sizeof(linkbuf)) > 0
3015      && str_starts_with(linkbuf, "../../")) {
3016    dev_name = linkbuf + sizeof("../../")-1;
3017  }
3018  // Remove the leading /dev/... if it's there
3019  else if (!strncmp(lin_dev_prefix, dev_name, dev_prefix_len)) {
3020    if (len <= dev_prefix_len)
3021      // if nothing else in the string, unrecognized
3022      return 0;
3023    // else advance pointer to following characters
3024    dev_name += dev_prefix_len;
3025  }
3026
3027  // form /dev/h* or h*
3028  if (!strncmp(lin_dev_ata_disk_plus, dev_name,
3029               strlen(lin_dev_ata_disk_plus)))
3030    return new linux_ata_device(this, name, "");
3031
3032  // form /dev/ide/* or ide/*
3033  if (!strncmp(lin_dev_ata_devfs_disk_plus, dev_name,
3034               strlen(lin_dev_ata_devfs_disk_plus)))
3035    return new linux_ata_device(this, name, "");
3036
3037  // form /dev/s* or s*
3038  if (!strncmp(lin_dev_scsi_disk_plus, dev_name,
3039               strlen(lin_dev_scsi_disk_plus))) {
3040
3041    // Try to detect possible USB->(S)ATA bridge
3042    unsigned short vendor_id = 0, product_id = 0, version = 0;
3043    if (get_usb_id(dev_name, vendor_id, product_id, version)) {
3044      const char * usbtype = get_usb_dev_type_by_id(vendor_id, product_id, version);
3045      if (!usbtype)
3046        return 0;
3047      // Linux USB layer does not support 16 byte SAT pass through command
3048      if (!strcmp(usbtype, "sat"))
3049        usbtype = "sat,12";
3050      // Return SAT/USB device for this type
3051      // (Note: linux_scsi_device::autodetect_open() will not be called in this case)
3052      return get_sat_device(usbtype, new linux_scsi_device(this, name, ""));
3053    }
3054
3055    // No USB bridge found, assume regular SCSI device
3056    return new linux_scsi_device(this, name, "");
3057  }
3058
3059  // form /dev/scsi/* or scsi/*
3060  if (!strncmp(lin_dev_scsi_devfs_disk_plus, dev_name,
3061               strlen(lin_dev_scsi_devfs_disk_plus)))
3062    return new linux_scsi_device(this, name, "");
3063
3064  // form /dev/ns* or ns*
3065  if (!strncmp(lin_dev_scsi_tape1, dev_name,
3066               strlen(lin_dev_scsi_tape1)))
3067    return new linux_scsi_device(this, name, "");
3068
3069  // form /dev/os* or os*
3070  if (!strncmp(lin_dev_scsi_tape2, dev_name,
3071               strlen(lin_dev_scsi_tape2)))
3072    return new linux_scsi_device(this, name, "");
3073
3074  // form /dev/nos* or nos*
3075  if (!strncmp(lin_dev_scsi_tape3, dev_name,
3076               strlen(lin_dev_scsi_tape3)))
3077    return new linux_scsi_device(this, name, "");
3078
3079  // form /dev/twa*
3080  if (!strncmp(lin_dev_3ware_9000_char, dev_name,
3081               strlen(lin_dev_3ware_9000_char)))
3082    return missing_option("-d 3ware,N");
3083
3084  // form /dev/twe*
3085  if (!strncmp(lin_dev_3ware_678k_char, dev_name,
3086               strlen(lin_dev_3ware_678k_char)))
3087    return missing_option("-d 3ware,N");
3088
3089  // form /dev/cciss*
3090  if (!strncmp(lin_dev_cciss_dir, dev_name,
3091               strlen(lin_dev_cciss_dir)))
3092    return missing_option("-d cciss,N");
3093
3094  // form /dev/sg*
3095  if ( !strncmp(lin_dev_areca, dev_name,
3096                strlen(lin_dev_areca)) )
3097    return missing_option("-d areca,N");
3098
3099  // we failed to recognize any of the forms
3100  return 0;
3101}
3102
3103smart_device * linux_smart_interface::get_custom_smart_device(const char * name, const char * type)
3104{
3105  // Marvell ?
3106  if (!strcmp(type, "marvell"))
3107    return new linux_marvell_device(this, name, type);
3108
3109  // 3Ware ?
3110  int disknum = -1, n1 = -1, n2 = -1;
3111  if (sscanf(type, "3ware,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
3112    if (n2 != (int)strlen(type)) {
3113      set_err(EINVAL, "Option -d 3ware,N requires N to be a non-negative integer");
3114      return 0;
3115    }
3116    if (!(0 <= disknum && disknum <= 127)) {
3117      set_err(EINVAL, "Option -d 3ware,N (N=%d) must have 0 <= N <= 127", disknum);
3118      return 0;
3119    }
3120
3121    if (!strncmp(name, "/dev/twa", 8))
3122      return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_9000_CHAR, disknum);
3123    else if (!strncmp(name, "/dev/twe", 8))
3124      return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_678K_CHAR, disknum);
3125    else
3126      return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_678K, disknum);
3127  }
3128
3129  // Areca?
3130  disknum = n1 = n2 = -1;
3131  if (sscanf(type, "areca,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
3132    if (n2 != (int)strlen(type)) {
3133      set_err(EINVAL, "Option -d areca,N requires N to be a non-negative integer");
3134      return 0;
3135    }
3136    if (!(1 <= disknum && disknum <= 24)) {
3137      set_err(EINVAL, "Option -d areca,N (N=%d) must have 1 <= N <= 24", disknum);
3138      return 0;
3139    }
3140    return new linux_areca_device(this, name, disknum);
3141  }
3142
3143  // Highpoint ?
3144  int controller = -1, channel = -1; disknum = 1;
3145  n1 = n2 = -1; int n3 = -1;
3146  if (sscanf(type, "hpt,%n%d/%d%n/%d%n", &n1, &controller, &channel, &n2, &disknum, &n3) >= 2 || n1 == 4) {
3147    int len = strlen(type);
3148    if (!(n2 == len || n3 == len)) {
3149      set_err(EINVAL, "Option '-d hpt,L/M/N' supports 2-3 items");
3150      return 0;
3151    }
3152    if (!(1 <= controller && controller <= 8)) {
3153      set_err(EINVAL, "Option '-d hpt,L/M/N' invalid controller id L supplied");
3154      return 0;
3155    }
3156    if (!(1 <= channel && channel <= 8)) {
3157      set_err(EINVAL, "Option '-d hpt,L/M/N' invalid channel number M supplied");
3158      return 0;
3159    }
3160    if (!(1 <= disknum && disknum <= 15)) {
3161      set_err(EINVAL, "Option '-d hpt,L/M/N' invalid pmport number N supplied");
3162      return 0;
3163    }
3164    return new linux_highpoint_device(this, name, controller, channel, disknum);
3165  }
3166
3167#ifdef HAVE_LINUX_CCISS_IOCTL_H
3168  // CCISS ?
3169  disknum = n1 = n2 = -1;
3170  if (sscanf(type, "cciss,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
3171    if (n2 != (int)strlen(type)) {
3172      set_err(EINVAL, "Option -d cciss,N requires N to be a non-negative integer");
3173      return 0;
3174    }
3175    if (!(0 <= disknum && disknum <= 15)) {
3176      set_err(EINVAL, "Option -d cciss,N (N=%d) must have 0 <= N <= 15", disknum);
3177      return 0;
3178    }
3179    return new linux_cciss_device(this, name, disknum);
3180  }
3181#endif // HAVE_LINUX_CCISS_IOCTL_H
3182
3183  // MegaRAID ?
3184  if (sscanf(type, "megaraid,%d", &disknum) == 1) {
3185    return new linux_megaraid_device(this, name, 0, disknum);
3186  }
3187  return 0;
3188}
3189
3190std::string linux_smart_interface::get_valid_custom_dev_types_str()
3191{
3192  return "marvell, areca,N, 3ware,N, hpt,L/M/N, megaraid,N"
3193#ifdef HAVE_LINUX_CCISS_IOCTL_H
3194                                              ", cciss,N"
3195#endif
3196    ;
3197}
3198
3199} // namespace
3200
3201
3202/////////////////////////////////////////////////////////////////////////////
3203/// Initialize platform interface and register with smi()
3204
3205void smart_interface::init()
3206{
3207  static os_linux::linux_smart_interface the_interface;
3208  smart_interface::set(&the_interface);
3209}
Note: See TracBrowser for help on using the browser.