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