Ticket #1653: os_linux.cpp

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