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