4 * Home page of code is: http://smartmontools.sourceforge.net
6 * Copyright (C) 2003-11 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2003-11 Doug Gilbert <dgilbert@interlog.com>
8 * Copyright (C) 2008-12 Hank Wu <hank@areca.com.tw>
9 * Copyright (C) 2008 Oliver Bock <brevilo@users.sourceforge.net>
10 * Copyright (C) 2008-12 Christian Franke <smartmontools-support@lists.sourceforge.net>
11 * Copyright (C) 2008 Jordan Hargrave <jordan_hargrave@dell.com>
13 * Parts of this file are derived from code that was
15 * Written By: Adam Radford <linux@3ware.com>
16 * Modifications By: Joel Jacobson <linux@3ware.com>
17 * Arnaldo Carvalho de Melo <acme@conectiva.com.br>
18 * Brad Strand <linux@3ware.com>
20 * Copyright (C) 1999-2003 3ware Inc.
22 * Kernel compatablity By: Andre Hedrick <andre@suse.com>
23 * Non-Copyright (C) 2000 Andre Hedrick <andre@suse.com>
25 * Other ars of this file are derived from code that was
27 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
28 * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
30 * This program is free software; you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation; either version 2, or (at your option)
35 * You should have received a copy of the GNU General Public License
36 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
38 * This code was originally developed as a Senior Thesis by Michael Cornwell
39 * at the Concurrent Systems Laboratory (now part of the Storage Systems
40 * Research Center), Jack Baskin School of Engineering, University of
41 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
45 // This file contains the linux-specific IOCTL parts of
46 // smartmontools. It includes one interface routine for ATA devices,
47 // one for SCSI devices, and one for ATA devices behind escalade
56 #include <scsi/scsi.h>
57 #include <scsi/scsi_ioctl.h>
61 #include <sys/ioctl.h>
63 #include <sys/utsname.h>
65 #include <stddef.h> // for offsetof()
67 #include <sys/types.h>
68 #ifndef makedev // old versions of types.h do not include sysmacros.h
69 #include <sys/sysmacros.h>
72 #include <selinux/selinux.h>
83 #include "dev_interface.h"
84 #include "dev_ata_cmd_set.h"
87 #define ENOTSUP ENOSYS
90 #define ARGUSED(x) ((void)(x))
92 const char * os_linux_cpp_cvsid
= "$Id: os_linux.cpp 3558 2012-06-05 16:42:05Z chrfranke $"
96 namespace os_linux
{ // No need to publish anything, name provided for Doxygen
98 /////////////////////////////////////////////////////////////////////////////
99 /// Shared open/close routines
101 class linux_smart_device
102 : virtual public /*implements*/ smart_device
105 explicit linux_smart_device(int flags
, int retry_flags
= -1)
106 : smart_device(never_called
),
108 m_flags(flags
), m_retry_flags(retry_flags
)
111 virtual ~linux_smart_device() throw();
113 virtual bool is_open() const;
117 virtual bool close();
120 /// Return filedesc for derived classes.
125 int m_fd
; ///< filedesc, -1 if not open.
126 int m_flags
; ///< Flags for ::open()
127 int m_retry_flags
; ///< Flags to retry ::open(), -1 if no retry
131 linux_smart_device::~linux_smart_device() throw()
137 bool linux_smart_device::is_open() const
142 bool linux_smart_device::open()
144 m_fd
= ::open(get_dev_name(), m_flags
);
146 if (m_fd
< 0 && errno
== EROFS
&& m_retry_flags
!= -1)
148 m_fd
= ::open(get_dev_name(), m_retry_flags
);
151 if (errno
== EBUSY
&& (m_flags
& O_EXCL
))
153 return set_err(EBUSY
,
154 "The requested controller is used exclusively by another process!\n"
155 "(e.g. smartctl or smartd)\n"
156 "Please quit the impeding process or try again later...");
157 return set_err((errno
==ENOENT
|| errno
==ENOTDIR
) ? ENODEV
: errno
);
161 // sets FD_CLOEXEC on the opened device file descriptor. The
162 // descriptor is otherwise leaked to other applications (mail
163 // sender) which may be considered a security risk and may result
164 // in AVC messages on SELinux-enabled systems.
165 if (-1 == fcntl(m_fd
, F_SETFD
, FD_CLOEXEC
))
166 // TODO: Provide an error printing routine in class smart_interface
167 pout("fcntl(set FD_CLOEXEC) failed, errno=%d [%s]\n", errno
, strerror(errno
));
173 // equivalent to close(file descriptor)
174 bool linux_smart_device::close()
176 int fd
= m_fd
; m_fd
= -1;
178 return set_err(errno
);
182 // examples for smartctl
183 static const char smartctl_examples
[] =
184 "=================================================== SMARTCTL EXAMPLES =====\n\n"
185 " smartctl --all /dev/hda (Prints all SMART information)\n\n"
186 " smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda\n"
187 " (Enables SMART on first disk)\n\n"
188 " smartctl --test=long /dev/hda (Executes extended disk self-test)\n\n"
189 " smartctl --attributes --log=selftest --quietmode=errorsonly /dev/hda\n"
190 " (Prints Self-Test & Attribute errors)\n"
191 " smartctl --all --device=3ware,2 /dev/sda\n"
192 " smartctl --all --device=3ware,2 /dev/twe0\n"
193 " smartctl --all --device=3ware,2 /dev/twa0\n"
194 " smartctl --all --device=3ware,2 /dev/twl0\n"
195 " (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
196 " smartctl --all --device=hpt,1/1/3 /dev/sda\n"
197 " (Prints all SMART info for the SATA disk attached to the 3rd PMPort\n"
198 " of the 1st channel on the 1st HighPoint RAID controller)\n"
199 " smartctl --all --device=areca,3/1 /dev/sg2\n"
200 " (Prints all SMART info for 3rd ATA disk of the 1st enclosure\n"
201 " on Areca RAID controller)\n"
205 /////////////////////////////////////////////////////////////////////////////
206 /// Linux ATA support
208 class linux_ata_device
209 : public /*implements*/ ata_device_with_command_set
,
210 public /*extends*/ linux_smart_device
213 linux_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
216 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
219 linux_ata_device::linux_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
)
220 : smart_device(intf
, dev_name
, "ata", req_type
),
221 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
226 // This is an interface routine meant to isolate the OS dependent
227 // parts of the code, and to provide a debugging interface. Each
228 // different port and OS needs to provide it's own interface. This
230 // DETAILED DESCRIPTION OF ARGUMENTS
231 // device: is the file descriptor provided by open()
232 // command: defines the different operations.
233 // select: additional input data if needed (which log, which type of
235 // data: location to write output data, if needed (512 bytes).
236 // Note: not all commands use all arguments.
238 // -1 if the command failed
239 // 0 if the command succeeded,
240 // STATUS_CHECK routine:
241 // -1 if the command failed
242 // 0 if the command succeeded and disk SMART status is "OK"
243 // 1 if the command succeeded and disk SMART status is "FAILING"
246 #define BUFFER_LENGTH (4+512)
248 int linux_ata_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
250 unsigned char buff
[BUFFER_LENGTH
];
251 // positive: bytes to write to caller. negative: bytes to READ from
252 // caller. zero: non-data command
255 const int HDIO_DRIVE_CMD_OFFSET
= 4;
257 // See struct hd_drive_cmd_hdr in hdreg.h. Before calling ioctl()
258 // buff[0]: ATA COMMAND CODE REGISTER
259 // buff[1]: ATA SECTOR NUMBER REGISTER == LBA LOW REGISTER
260 // buff[2]: ATA FEATURES REGISTER
261 // buff[3]: ATA SECTOR COUNT REGISTER
263 // Note that on return:
264 // buff[2] contains the ATA SECTOR COUNT REGISTER
266 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
267 memset(buff
, 0, BUFFER_LENGTH
);
269 buff
[0]=ATA_SMART_CMD
;
271 case CHECK_POWER_MODE
:
272 buff
[0]=ATA_CHECK_POWER_MODE
;
276 buff
[2]=ATA_SMART_READ_VALUES
;
280 case READ_THRESHOLDS
:
281 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
286 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
294 buff
[0]=ATA_IDENTIFY_DEVICE
;
299 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
304 buff
[2]=ATA_SMART_ENABLE
;
308 buff
[2]=ATA_SMART_DISABLE
;
312 // this command only says if SMART is working. It could be
313 // replaced with STATUS_CHECK below.
314 buff
[2]=ATA_SMART_STATUS
;
317 // NOTE: According to ATAPI 4 and UP, this command is obsolete
318 // select == 241 for enable but no data transfer. Use TASK ioctl.
319 buff
[1]=ATA_SMART_AUTO_OFFLINE
;
323 // select == 248 for enable but no data transfer. Use TASK ioctl.
324 buff
[1]=ATA_SMART_AUTOSAVE
;
327 case IMMEDIATE_OFFLINE
:
328 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
332 // This command uses HDIO_DRIVE_TASK and has different syntax than
333 // the other commands.
334 buff
[1]=ATA_SMART_STATUS
;
337 pout("Unrecognized command %d in linux_ata_command_interface()\n"
338 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
343 // This command uses the HDIO_DRIVE_TASKFILE ioctl(). This is the
344 // only ioctl() that can be used to WRITE data to the disk.
345 if (command
==WRITE_LOG
) {
346 unsigned char task
[sizeof(ide_task_request_t
)+512];
347 ide_task_request_t
*reqtask
=(ide_task_request_t
*) task
;
348 task_struct_t
*taskfile
=(task_struct_t
*) reqtask
->io_ports
;
351 memset(task
, 0, sizeof(task
));
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
;
362 reqtask
->data_phase
= TASKFILE_OUT
;
363 reqtask
->req_cmd
= IDE_DRIVE_TASK_OUT
;
364 reqtask
->out_size
= 512;
365 reqtask
->in_size
= 0;
367 // copy user data into the task request structure
368 memcpy(task
+sizeof(ide_task_request_t
), data
, 512);
370 if ((retval
=ioctl(get_fd(), HDIO_DRIVE_TASKFILE
, task
))) {
372 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
378 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
380 if (command
==STATUS_CHECK
|| command
==AUTOSAVE
|| command
==AUTO_OFFLINE
){
383 // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
384 // have to read the IDE driver source code. Sigh.
385 // buff[0]: ATA COMMAND CODE REGISTER
386 // buff[1]: ATA FEATURES REGISTER
387 // buff[2]: ATA SECTOR_COUNT
388 // buff[3]: ATA SECTOR NUMBER
389 // buff[4]: ATA CYL LO REGISTER
390 // buff[5]: ATA CYL HI REGISTER
391 // buff[6]: ATA DEVICE HEAD
393 unsigned const char normal_lo
=0x4f, normal_hi
=0xc2;
394 unsigned const char failed_lo
=0xf4, failed_hi
=0x2c;
398 if ((retval
=ioctl(get_fd(), HDIO_DRIVE_TASK
, buff
))) {
399 if (retval
==-EINVAL
) {
400 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
401 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
404 syserror("Error SMART Status command failed");
408 // Cyl low and Cyl high unchanged means "Good SMART status"
409 if (buff
[4]==normal_lo
&& buff
[5]==normal_hi
)
412 // These values mean "Bad SMART status"
413 if (buff
[4]==failed_lo
&& buff
[5]==failed_hi
)
416 // We haven't gotten output that makes sense; print out some debugging info
417 syserror("Error SMART Status command failed");
418 pout("Please get assistance from " PACKAGE_HOMEPAGE
"\n");
419 pout("Register values returned from SMART Status command are:\n");
420 pout("ST =0x%02x\n",(int)buff
[0]);
421 pout("ERR=0x%02x\n",(int)buff
[1]);
422 pout("NS =0x%02x\n",(int)buff
[2]);
423 pout("SC =0x%02x\n",(int)buff
[3]);
424 pout("CL =0x%02x\n",(int)buff
[4]);
425 pout("CH =0x%02x\n",(int)buff
[5]);
426 pout("SEL=0x%02x\n",(int)buff
[6]);
431 // Note to people doing ports to other OSes -- don't worry about
432 // this block -- you can safely ignore it. I have put it here
433 // because under linux when you do IDENTIFY DEVICE to a packet
434 // device, it generates an ugly kernel syslog error message. This
435 // is harmless but frightens users. So this block detects packet
436 // devices and make IDENTIFY DEVICE fail "nicely" without a syslog
439 // If you read only the ATA specs, it appears as if a packet device
440 // *might* respond to the IDENTIFY DEVICE command. This is
441 // misleading - it's because around the time that SFF-8020 was
442 // incorporated into the ATA-3/4 standard, the ATA authors were
443 // sloppy. See SFF-8020 and you will see that ATAPI devices have
444 // *always* had IDENTIFY PACKET DEVICE as a mandatory part of their
445 // command set, and return 'Command Aborted' to IDENTIFY DEVICE.
446 if (command
==IDENTIFY
|| command
==PIDENTIFY
){
447 unsigned short deviceid
[256];
448 // check the device identity, as seen when the system was booted
449 // or the device was FIRST registered. This will not be current
450 // if the user has subsequently changed some of the parameters. If
451 // device is a packet device, swap the command interpretations.
452 if (!ioctl(get_fd(), HDIO_GET_IDENTITY
, deviceid
) && (deviceid
[0] & 0x8000))
453 buff
[0]=(command
==IDENTIFY
)?ATA_IDENTIFY_PACKET_DEVICE
:ATA_IDENTIFY_DEVICE
;
457 // We are now doing the HDIO_DRIVE_CMD type ioctl.
458 if ((ioctl(get_fd(), HDIO_DRIVE_CMD
, buff
)))
461 // CHECK POWER MODE command returns information in the Sector Count
462 // register (buff[3]). Copy to return data buffer.
463 if (command
==CHECK_POWER_MODE
)
464 buff
[HDIO_DRIVE_CMD_OFFSET
]=buff
[2];
466 // if the command returns data then copy it back
468 memcpy(data
, buff
+HDIO_DRIVE_CMD_OFFSET
, copydata
);
473 // >>>>>> Start of general SCSI specific linux code
475 /* Linux specific code.
476 * Historically smartmontools (and smartsuite before it) used the
477 * SCSI_IOCTL_SEND_COMMAND ioctl which is available to all linux device
478 * nodes that use the SCSI subsystem. A better interface has been available
479 * via the SCSI generic (sg) driver but this involves the extra step of
480 * mapping disk devices (e.g. /dev/sda) to the corresponding sg device
481 * (e.g. /dev/sg2). In the linux kernel 2.6 series most of the facilities of
482 * the sg driver have become available via the SG_IO ioctl which is available
483 * on all SCSI devices (on SCSI tape devices from lk 2.6.6).
484 * So the strategy below is to find out if the SG_IO ioctl is available and
485 * if so use it; failing that use the older SCSI_IOCTL_SEND_COMMAND ioctl.
486 * Should work in 2.0, 2.2, 2.4 and 2.6 series linux kernels. */
488 #define MAX_DXFER_LEN 1024 /* can be increased if necessary */
489 #define SEND_IOCTL_RESP_SENSE_LEN 16 /* ioctl limitation */
490 #define SG_IO_RESP_SENSE_LEN 64 /* large enough see buffer */
491 #define LSCSI_DRIVER_MASK 0xf /* mask out "suggestions" */
492 #define LSCSI_DRIVER_SENSE 0x8 /* alternate CHECK CONDITION indication */
493 #define LSCSI_DID_ERROR 0x7 /* Need to work around aacraid driver quirk */
494 #define LSCSI_DRIVER_TIMEOUT 0x6
495 #define LSCSI_DID_TIME_OUT 0x3
496 #define LSCSI_DID_BUS_BUSY 0x2
497 #define LSCSI_DID_NO_CONNECT 0x1
499 #ifndef SCSI_IOCTL_SEND_COMMAND
500 #define SCSI_IOCTL_SEND_COMMAND 1
503 #define SG_IO_PRESENT_UNKNOWN 0
504 #define SG_IO_PRESENT_YES 1
505 #define SG_IO_PRESENT_NO 2
507 static int sg_io_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
,
509 static int sisc_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
);
511 static int sg_io_state
= SG_IO_PRESENT_UNKNOWN
;
513 /* Preferred implementation for issuing SCSI commands in linux. This
514 * function uses the SG_IO ioctl. Return 0 if command issued successfully
515 * (various status values should still be checked). If the SCSI command
516 * cannot be issued then a negative errno value is returned. */
517 static int sg_io_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
,
521 ARGUSED(dev_fd
); ARGUSED(iop
); ARGUSED(report
);
524 struct sg_io_hdr io_hdr
;
528 const unsigned char * ucp
= iop
->cmnd
;
531 const int sz
= (int)sizeof(buff
);
533 np
= scsi_get_opcode_name(ucp
[0]);
534 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
535 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
536 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
538 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
539 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
541 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
542 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
543 (trunc
? " [only first 256 bytes shown]" : ""));
544 dStrHex((const char *)iop
->dxferp
,
545 (trunc
? 256 : iop
->dxfer_len
) , 1);
548 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
551 memset(&io_hdr
, 0, sizeof(struct sg_io_hdr
));
552 io_hdr
.interface_id
= 'S';
553 io_hdr
.cmd_len
= iop
->cmnd_len
;
554 io_hdr
.mx_sb_len
= iop
->max_sense_len
;
555 io_hdr
.dxfer_len
= iop
->dxfer_len
;
556 io_hdr
.dxferp
= iop
->dxferp
;
557 io_hdr
.cmdp
= iop
->cmnd
;
558 io_hdr
.sbp
= iop
->sensep
;
559 /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
560 defaults to 60 seconds. */
561 io_hdr
.timeout
= ((0 == iop
->timeout
) ? 60 : iop
->timeout
) * 1000;
562 switch (iop
->dxfer_dir
) {
564 io_hdr
.dxfer_direction
= SG_DXFER_NONE
;
566 case DXFER_FROM_DEVICE
:
567 io_hdr
.dxfer_direction
= SG_DXFER_FROM_DEV
;
569 case DXFER_TO_DEVICE
:
570 io_hdr
.dxfer_direction
= SG_DXFER_TO_DEV
;
573 pout("do_scsi_cmnd_io: bad dxfer_dir\n");
576 iop
->resp_sense_len
= 0;
577 iop
->scsi_status
= 0;
579 if (ioctl(dev_fd
, SG_IO
, &io_hdr
) < 0) {
580 if (report
&& (! unknown
))
581 pout(" SG_IO ioctl failed, errno=%d [%s]\n", errno
,
585 iop
->resid
= io_hdr
.resid
;
586 iop
->scsi_status
= io_hdr
.status
;
588 pout(" scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
589 " info=0x%x duration=%d milliseconds resid=%d\n", io_hdr
.status
,
590 io_hdr
.host_status
, io_hdr
.driver_status
, io_hdr
.info
,
591 io_hdr
.duration
, io_hdr
.resid
);
593 if (DXFER_FROM_DEVICE
== iop
->dxfer_dir
) {
596 len
= iop
->dxfer_len
- iop
->resid
;
597 trunc
= (len
> 256) ? 1 : 0;
599 pout(" Incoming data, len=%d%s:\n", len
,
600 (trunc
? " [only first 256 bytes shown]" : ""));
601 dStrHex((const char*)iop
->dxferp
, (trunc
? 256 : len
),
604 pout(" Incoming data trimmed to nothing by resid\n");
609 if (io_hdr
.info
& SG_INFO_CHECK
) { /* error or warning */
610 int masked_driver_status
= (LSCSI_DRIVER_MASK
& io_hdr
.driver_status
);
612 if (0 != io_hdr
.host_status
) {
613 if ((LSCSI_DID_NO_CONNECT
== io_hdr
.host_status
) ||
614 (LSCSI_DID_BUS_BUSY
== io_hdr
.host_status
) ||
615 (LSCSI_DID_TIME_OUT
== io_hdr
.host_status
))
618 /* Check for DID_ERROR - workaround for aacraid driver quirk */
619 if (LSCSI_DID_ERROR
!= io_hdr
.host_status
) {
620 return -EIO
; /* catch all if not DID_ERR */
623 if (0 != masked_driver_status
) {
624 if (LSCSI_DRIVER_TIMEOUT
== masked_driver_status
)
626 else if (LSCSI_DRIVER_SENSE
!= masked_driver_status
)
629 if (LSCSI_DRIVER_SENSE
== masked_driver_status
)
630 iop
->scsi_status
= SCSI_STATUS_CHECK_CONDITION
;
631 iop
->resp_sense_len
= io_hdr
.sb_len_wr
;
632 if ((SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) &&
633 iop
->sensep
&& (iop
->resp_sense_len
> 0)) {
635 pout(" >>> Sense buffer, len=%d:\n",
636 (int)iop
->resp_sense_len
);
637 dStrHex((const char *)iop
->sensep
, iop
->resp_sense_len
, 1);
641 if (SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) {
642 if ((iop
->sensep
[0] & 0x7f) > 0x71)
643 pout(" status=%x: [desc] sense_key=%x asc=%x ascq=%x\n",
644 iop
->scsi_status
, iop
->sensep
[1] & 0xf,
645 iop
->sensep
[2], iop
->sensep
[3]);
647 pout(" status=%x: sense_key=%x asc=%x ascq=%x\n",
648 iop
->scsi_status
, iop
->sensep
[2] & 0xf,
649 iop
->sensep
[12], iop
->sensep
[13]);
652 pout(" status=0x%x\n", iop
->scsi_status
);
659 struct linux_ioctl_send_command
663 UINT8 buff
[MAX_DXFER_LEN
+ 16];
666 /* The Linux SCSI_IOCTL_SEND_COMMAND ioctl is primitive and it doesn't
667 * support: CDB length (guesses it from opcode), resid and timeout.
668 * Patches in Linux 2.4.21 and 2.5.70 to extend SEND DIAGNOSTIC timeout
669 * to 2 hours in order to allow long foreground extended self tests. */
670 static int sisc_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
)
672 struct linux_ioctl_send_command wrk
;
673 int status
, buff_offset
;
676 memcpy(wrk
.buff
, iop
->cmnd
, iop
->cmnd_len
);
677 buff_offset
= iop
->cmnd_len
;
680 const unsigned char * ucp
= iop
->cmnd
;
683 const int sz
= (int)sizeof(buff
);
685 np
= scsi_get_opcode_name(ucp
[0]);
686 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
687 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
688 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
690 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
691 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
693 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
694 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
695 (trunc
? " [only first 256 bytes shown]" : ""));
696 dStrHex((const char *)iop
->dxferp
,
697 (trunc
? 256 : iop
->dxfer_len
) , 1);
700 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
703 switch (iop
->dxfer_dir
) {
708 case DXFER_FROM_DEVICE
:
710 if (iop
->dxfer_len
> MAX_DXFER_LEN
)
712 wrk
.outbufsize
= iop
->dxfer_len
;
714 case DXFER_TO_DEVICE
:
715 if (iop
->dxfer_len
> MAX_DXFER_LEN
)
717 memcpy(wrk
.buff
+ buff_offset
, iop
->dxferp
, iop
->dxfer_len
);
718 wrk
.inbufsize
= iop
->dxfer_len
;
722 pout("do_scsi_cmnd_io: bad dxfer_dir\n");
725 iop
->resp_sense_len
= 0;
726 iop
->scsi_status
= 0;
728 status
= ioctl(dev_fd
, SCSI_IOCTL_SEND_COMMAND
, &wrk
);
731 pout(" SCSI_IOCTL_SEND_COMMAND ioctl failed, errno=%d [%s]\n",
732 errno
, strerror(errno
));
738 if (DXFER_FROM_DEVICE
== iop
->dxfer_dir
) {
739 memcpy(iop
->dxferp
, wrk
.buff
, iop
->dxfer_len
);
741 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
743 pout(" Incoming data, len=%d%s:\n", (int)iop
->dxfer_len
,
744 (trunc
? " [only first 256 bytes shown]" : ""));
745 dStrHex((const char*)iop
->dxferp
,
746 (trunc
? 256 : iop
->dxfer_len
) , 1);
751 iop
->scsi_status
= status
& 0x7e; /* bits 0 and 7 used to be for vendors */
752 if (LSCSI_DRIVER_SENSE
== ((status
>> 24) & 0xf))
753 iop
->scsi_status
= SCSI_STATUS_CHECK_CONDITION
;
754 len
= (SEND_IOCTL_RESP_SENSE_LEN
< iop
->max_sense_len
) ?
755 SEND_IOCTL_RESP_SENSE_LEN
: iop
->max_sense_len
;
756 if ((SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) &&
757 iop
->sensep
&& (len
> 0)) {
758 memcpy(iop
->sensep
, wrk
.buff
, len
);
759 iop
->resp_sense_len
= len
;
761 pout(" >>> Sense buffer, len=%d:\n", (int)len
);
762 dStrHex((const char *)wrk
.buff
, len
, 1);
766 if (SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) {
767 pout(" status=%x: sense_key=%x asc=%x ascq=%x\n", status
& 0xff,
768 wrk
.buff
[2] & 0xf, wrk
.buff
[12], wrk
.buff
[13]);
771 pout(" status=0x%x\n", status
);
773 if (iop
->scsi_status
> 0)
777 pout(" ioctl status=0x%x but scsi status=0, fail with EIO\n",
779 return -EIO
; /* give up, assume no device there */
783 /* SCSI command transmission interface function, linux version.
784 * Returns 0 if SCSI command successfully launched and response
785 * received. Even when 0 is returned the caller should check
786 * scsi_cmnd_io::scsi_status for SCSI defined errors and warnings
787 * (e.g. CHECK CONDITION). If the SCSI command could not be issued
788 * (e.g. device not present or timeout) or some other problem
789 * (e.g. timeout) then returns a negative errno value */
790 static int do_normal_scsi_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
,
795 /* implementation relies on static sg_io_state variable. If not
796 * previously set tries the SG_IO ioctl. If that succeeds assume
797 * that SG_IO ioctl functional. If it fails with an errno value
798 * other than ENODEV (no device) or permission then assume
799 * SCSI_IOCTL_SEND_COMMAND is the only option. */
800 switch (sg_io_state
) {
801 case SG_IO_PRESENT_UNKNOWN
:
802 /* ignore report argument */
803 if (0 == (res
= sg_io_cmnd_io(dev_fd
, iop
, report
, 1))) {
804 sg_io_state
= SG_IO_PRESENT_YES
;
806 } else if ((-ENODEV
== res
) || (-EACCES
== res
) || (-EPERM
== res
))
807 return res
; /* wait until we see a device */
808 sg_io_state
= SG_IO_PRESENT_NO
;
809 /* drop through by design */
810 case SG_IO_PRESENT_NO
:
811 return sisc_cmnd_io(dev_fd
, iop
, report
);
812 case SG_IO_PRESENT_YES
:
813 return sg_io_cmnd_io(dev_fd
, iop
, report
, 0);
815 pout(">>>> do_scsi_cmnd_io: bad sg_io_state=%d\n", sg_io_state
);
816 sg_io_state
= SG_IO_PRESENT_UNKNOWN
;
817 return -EIO
; /* report error and reset state */
821 // >>>>>> End of general SCSI specific linux code
823 /////////////////////////////////////////////////////////////////////////////
824 /// Standard SCSI support
826 class linux_scsi_device
827 : public /*implements*/ scsi_device
,
828 public /*extends*/ linux_smart_device
831 linux_scsi_device(smart_interface
* intf
, const char * dev_name
,
832 const char * req_type
, bool scanning
= false);
834 virtual smart_device
* autodetect_open();
836 virtual bool scsi_pass_through(scsi_cmnd_io
* iop
);
839 bool m_scanning
; ///< true if created within scan_smart_devices
842 linux_scsi_device::linux_scsi_device(smart_interface
* intf
,
843 const char * dev_name
, const char * req_type
, bool scanning
/*= false*/)
844 : smart_device(intf
, dev_name
, "scsi", req_type
),
845 // If opened with O_RDWR, a SATA disk in standby mode
846 // may spin-up after device close().
847 linux_smart_device(O_RDONLY
| O_NONBLOCK
),
853 bool linux_scsi_device::scsi_pass_through(scsi_cmnd_io
* iop
)
855 int status
= do_normal_scsi_cmnd_io(get_fd(), iop
, scsi_debugmode
);
857 return set_err(-status
);
861 /////////////////////////////////////////////////////////////////////////////
862 /// LSI MegaRAID support
864 class linux_megaraid_device
865 : public /* implements */ scsi_device
,
866 public /* extends */ linux_smart_device
869 linux_megaraid_device(smart_interface
*intf
, const char *name
,
870 unsigned int bus
, unsigned int tgt
);
872 virtual ~linux_megaraid_device() throw();
874 virtual smart_device
* autodetect_open();
877 virtual bool close();
879 virtual bool scsi_pass_through(scsi_cmnd_io
*iop
);
882 unsigned int m_disknum
;
883 unsigned int m_busnum
;
887 bool (linux_megaraid_device::*pt_cmd
)(int cdblen
, void *cdb
, int dataLen
, void *data
,
888 int senseLen
, void *sense
, int report
);
889 bool megasas_cmd(int cdbLen
, void *cdb
, int dataLen
, void *data
,
890 int senseLen
, void *sense
, int report
);
891 bool megadev_cmd(int cdbLen
, void *cdb
, int dataLen
, void *data
,
892 int senseLen
, void *sense
, int report
);
895 linux_megaraid_device::linux_megaraid_device(smart_interface
*intf
,
896 const char *dev_name
, unsigned int bus
, unsigned int tgt
)
897 : smart_device(intf
, dev_name
, "megaraid", "megaraid"),
898 linux_smart_device(O_RDWR
| O_NONBLOCK
),
899 m_disknum(tgt
), m_busnum(bus
), m_hba(0),
902 set_info().info_name
= strprintf("%s [megaraid_disk_%02d]", dev_name
, m_disknum
);
905 linux_megaraid_device::~linux_megaraid_device() throw()
911 smart_device
* linux_megaraid_device::autodetect_open()
913 int report
= scsi_debugmode
;
919 // The code below is based on smartd.cpp:SCSIFilterKnown()
920 if (strcmp(get_req_type(), "megaraid"))
924 unsigned char req_buff
[64] = {0, };
926 if (scsiStdInquiry(this, req_buff
, req_len
)) {
928 set_err(EIO
, "INQUIRY failed");
932 int avail_len
= req_buff
[4] + 5;
933 int len
= (avail_len
< req_len
? avail_len
: req_len
);
938 pout("Got MegaRAID inquiry.. %s\n", req_buff
+8);
940 // Use INQUIRY to detect type
943 ata_device
* newdev
= smi()->autodetect_sat_device(this, req_buff
, len
);
945 // NOTE: 'this' is now owned by '*newdev'
947 newdev
->set_err(ENOSYS
, "SATA device detected,\n"
948 "MegaRAID SAT layer is reportedly buggy, use '-d sat+megaraid,N' to try anyhow");
953 // Nothing special found
958 bool linux_megaraid_device::open()
963 int report
= scsi_debugmode
;
965 if (!linux_smart_device::open())
969 struct sg_scsi_id sgid
;
970 if (ioctl(get_fd(), SG_GET_SCSI_ID
, &sgid
) == 0) {
971 m_hba
= sgid
.host_no
;
973 else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER
, &m_hba
) != 0) {
975 linux_smart_device::close();
976 return set_err(err
, "can't get bus number");
979 /* Perform mknod of device ioctl node */
980 fp
= fopen("/proc/devices", "r");
981 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
983 if (sscanf(line
, "%d megaraid_sas_ioctl%n", &mjr
, &n1
) == 1 && n1
== 22) {
984 n1
=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR
, makedev(mjr
, 0));
986 pout("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1
>= 0 ? 0 : errno
);
987 if (n1
>= 0 || errno
== EEXIST
)
990 else if (sscanf(line
, "%d megadev%n", &mjr
, &n1
) == 1 && n1
== 11) {
991 n1
=mknod("/dev/megadev0", S_IFCHR
, makedev(mjr
, 0));
993 pout("Creating /dev/megadev0 = %d\n", n1
>= 0 ? 0 : errno
);
994 if (n1
>= 0 || errno
== EEXIST
)
1000 /* Open Device IOCTL node */
1001 if ((m_fd
= ::open("/dev/megaraid_sas_ioctl_node", O_RDWR
)) >= 0) {
1002 pt_cmd
= &linux_megaraid_device::megasas_cmd
;
1004 else if ((m_fd
= ::open("/dev/megadev0", O_RDWR
)) >= 0) {
1005 pt_cmd
= &linux_megaraid_device::megadev_cmd
;
1009 linux_smart_device::close();
1010 return set_err(err
, "cannot open /dev/megaraid_sas_ioctl_node or /dev/megadev0");
1016 bool linux_megaraid_device::close()
1020 m_fd
= -1; m_hba
= 0; pt_cmd
= 0;
1021 return linux_smart_device::close();
1024 bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io
*iop
)
1026 int report
= scsi_debugmode
;
1030 const unsigned char * ucp
= iop
->cmnd
;
1033 const int sz
= (int)sizeof(buff
);
1035 np
= scsi_get_opcode_name(ucp
[0]);
1036 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
1037 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
1038 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
1040 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
1041 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
1043 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
1044 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
1045 (trunc
? " [only first 256 bytes shown]" : ""));
1046 dStrHex((const char *)iop
->dxferp
,
1047 (trunc
? 256 : iop
->dxfer_len
) , 1);
1050 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
1054 // Controller rejects Test Unit Ready
1055 if (iop
->cmnd
[0] == 0x00)
1058 if (iop
->cmnd
[0] == SAT_ATA_PASSTHROUGH_12
|| iop
->cmnd
[0] == SAT_ATA_PASSTHROUGH_16
) {
1059 // Controller does not return ATA output registers in SAT sense data
1060 if (iop
->cmnd
[2] & (1 << 5)) // chk_cond
1061 return set_err(ENOSYS
, "ATA return descriptor not supported by controller firmware");
1063 // SMART WRITE LOG SECTOR causing media errors
1064 if ((iop
->cmnd
[0] == SAT_ATA_PASSTHROUGH_16
&& iop
->cmnd
[14] == ATA_SMART_CMD
1065 && iop
->cmnd
[3]==0 && iop
->cmnd
[4] == ATA_SMART_WRITE_LOG_SECTOR
) ||
1066 (iop
->cmnd
[0] == SAT_ATA_PASSTHROUGH_12
&& iop
->cmnd
[9] == ATA_SMART_CMD
&&
1067 iop
->cmnd
[3] == ATA_SMART_WRITE_LOG_SECTOR
))
1068 return set_err(ENOSYS
, "SMART WRITE LOG SECTOR command is not supported by controller firmware");
1072 return (this->*pt_cmd
)(iop
->cmnd_len
, iop
->cmnd
,
1073 iop
->dxfer_len
, iop
->dxferp
,
1074 iop
->max_sense_len
, iop
->sensep
, report
);
1077 /* Issue passthrough scsi command to PERC5/6 controllers */
1078 bool linux_megaraid_device::megasas_cmd(int cdbLen
, void *cdb
,
1079 int dataLen
, void *data
,
1080 int /*senseLen*/, void * /*sense*/, int /*report*/)
1082 struct megasas_pthru_frame
*pthru
;
1083 struct megasas_iocpacket uio
;
1086 memset(&uio
, 0, sizeof(uio
));
1087 pthru
= &uio
.frame
.pthru
;
1088 pthru
->cmd
= MFI_CMD_PD_SCSI_IO
;
1089 pthru
->cmd_status
= 0xFF;
1090 pthru
->scsi_status
= 0x0;
1091 pthru
->target_id
= m_disknum
;
1093 pthru
->cdb_len
= cdbLen
;
1095 pthru
->flags
= MFI_FRAME_DIR_READ
;
1097 pthru
->sge_count
= 1;
1098 pthru
->data_xfer_len
= dataLen
;
1099 pthru
->sgl
.sge32
[0].phys_addr
= (intptr_t)data
;
1100 pthru
->sgl
.sge32
[0].length
= (uint32_t)dataLen
;
1102 memcpy(pthru
->cdb
, cdb
, cdbLen
);
1104 uio
.host_no
= m_hba
;
1107 uio
.sgl_off
= offsetof(struct megasas_pthru_frame
, sgl
);
1108 uio
.sgl
[0].iov_base
= data
;
1109 uio
.sgl
[0].iov_len
= dataLen
;
1114 rc
= ioctl(m_fd
, MEGASAS_IOC_FIRMWARE
, &uio
);
1115 if (pthru
->cmd_status
|| rc
!= 0) {
1116 if (pthru
->cmd_status
== 12) {
1117 return set_err(EIO
, "megasas_cmd: Device %d does not exist\n", m_disknum
);
1119 return set_err((errno
? errno
: EIO
), "megasas_cmd result: %d.%d = %d/%d",
1120 m_hba
, m_disknum
, errno
,
1126 /* Issue passthrough scsi commands to PERC2/3/4 controllers */
1127 bool linux_megaraid_device::megadev_cmd(int cdbLen
, void *cdb
,
1128 int dataLen
, void *data
,
1129 int /*senseLen*/, void * /*sense*/, int /*report*/)
1131 struct uioctl_t uio
;
1134 /* Don't issue to the controller */
1138 memset(&uio
, 0, sizeof(uio
));
1139 uio
.inlen
= dataLen
;
1140 uio
.outlen
= dataLen
;
1142 memset(data
, 0, dataLen
);
1143 uio
.ui
.fcs
.opcode
= 0x80; // M_RD_IOCTL_CMD
1144 uio
.ui
.fcs
.adapno
= MKADAP(m_hba
);
1146 uio
.data
.pointer
= (uint8_t *)data
;
1148 uio
.mbox
.cmd
= MEGA_MBOXCMD_PASSTHRU
;
1149 uio
.mbox
.xferaddr
= (intptr_t)&uio
.pthru
;
1152 uio
.pthru
.timeout
= 2;
1153 uio
.pthru
.channel
= 0;
1154 uio
.pthru
.target
= m_disknum
;
1155 uio
.pthru
.cdblen
= cdbLen
;
1156 uio
.pthru
.reqsenselen
= MAX_REQ_SENSE_LEN
;
1157 uio
.pthru
.dataxferaddr
= (intptr_t)data
;
1158 uio
.pthru
.dataxferlen
= dataLen
;
1159 memcpy(uio
.pthru
.cdb
, cdb
, cdbLen
);
1161 rc
=ioctl(m_fd
, MEGAIOCCMD
, &uio
);
1162 if (uio
.pthru
.scsistatus
|| rc
!= 0) {
1163 return set_err((errno
? errno
: EIO
), "megadev_cmd result: %d.%d = %d/%d",
1164 m_hba
, m_disknum
, errno
,
1165 uio
.pthru
.scsistatus
);
1170 /////////////////////////////////////////////////////////////////////////////
1171 /// CCISS RAID support
1173 #ifdef HAVE_LINUX_CCISS_IOCTL_H
1175 class linux_cciss_device
1176 : public /*implements*/ scsi_device
,
1177 public /*extends*/ linux_smart_device
1180 linux_cciss_device(smart_interface
* intf
, const char * name
, unsigned char disknum
);
1182 virtual bool scsi_pass_through(scsi_cmnd_io
* iop
);
1185 unsigned char m_disknum
; ///< Disk number.
1188 linux_cciss_device::linux_cciss_device(smart_interface
* intf
,
1189 const char * dev_name
, unsigned char disknum
)
1190 : smart_device(intf
, dev_name
, "cciss", "cciss"),
1191 linux_smart_device(O_RDWR
| O_NONBLOCK
),
1194 set_info().info_name
= strprintf("%s [cciss_disk_%02d]", dev_name
, disknum
);
1197 bool linux_cciss_device::scsi_pass_through(scsi_cmnd_io
* iop
)
1199 int status
= cciss_io_interface(get_fd(), m_disknum
, iop
, scsi_debugmode
);
1201 return set_err(-status
);
1205 #endif // HAVE_LINUX_CCISS_IOCTL_H
1207 /////////////////////////////////////////////////////////////////////////////
1208 /// AMCC/3ware RAID support
1210 class linux_escalade_device
1211 : public /*implements*/ ata_device
,
1212 public /*extends*/ linux_smart_device
1215 enum escalade_type_t
{
1217 AMCC_3WARE_678K_CHAR
,
1218 AMCC_3WARE_9000_CHAR
,
1219 AMCC_3WARE_9700_CHAR
1222 linux_escalade_device(smart_interface
* intf
, const char * dev_name
,
1223 escalade_type_t escalade_type
, int disknum
);
1225 virtual bool open();
1227 virtual bool ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
);
1230 escalade_type_t m_escalade_type
; ///< Controller type
1231 int m_disknum
; ///< Disk number.
1234 linux_escalade_device::linux_escalade_device(smart_interface
* intf
, const char * dev_name
,
1235 escalade_type_t escalade_type
, int disknum
)
1236 : smart_device(intf
, dev_name
, "3ware", "3ware"),
1237 linux_smart_device(O_RDONLY
| O_NONBLOCK
),
1238 m_escalade_type(escalade_type
), m_disknum(disknum
)
1240 set_info().info_name
= strprintf("%s [3ware_disk_%02d]", dev_name
, disknum
);
1243 /* This function will setup and fix device nodes for a 3ware controller. */
1244 #define MAJOR_STRING_LENGTH 3
1245 #define DEVICE_STRING_LENGTH 32
1246 #define NODE_STRING_LENGTH 16
1247 static int setup_3ware_nodes(const char *nodename
, const char *driver_name
)
1251 char majorstring
[MAJOR_STRING_LENGTH
+1];
1252 char device_name
[DEVICE_STRING_LENGTH
+1];
1253 char nodestring
[NODE_STRING_LENGTH
];
1254 struct stat stat_buf
;
1258 security_context_t orig_context
= NULL
;
1259 security_context_t node_context
= NULL
;
1260 int selinux_enabled
= is_selinux_enabled();
1261 int selinux_enforced
= security_getenforce();
1265 /* First try to open up /proc/devices */
1266 if (!(file
= fopen("/proc/devices", "r"))) {
1267 pout("Error opening /proc/devices to check/create 3ware device nodes\n");
1269 return 0; // don't fail here: user might not have /proc !
1272 /* Attempt to get device major number */
1273 while (EOF
!= fscanf(file
, "%3s %32s", majorstring
, device_name
)) {
1274 majorstring
[MAJOR_STRING_LENGTH
]='\0';
1275 device_name
[DEVICE_STRING_LENGTH
]='\0';
1276 if (!strncmp(device_name
, nodename
, DEVICE_STRING_LENGTH
)) {
1277 tw_major
= atoi(majorstring
);
1283 /* See if we found a major device number */
1285 pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename
, driver_name
);
1289 /* Prepare a database of contexts for files in /dev
1290 * and save the current context */
1291 if (selinux_enabled
) {
1292 if (matchpathcon_init_prefix(NULL
, "/dev") < 0)
1293 pout("Error initializing contexts database for /dev");
1294 if (getfscreatecon(&orig_context
) < 0) {
1295 pout("Error retrieving original SELinux fscreate context");
1296 if (selinux_enforced
)
1297 matchpathcon_fini();
1302 /* Now check if nodes are correct */
1303 for (index
=0; index
<16; index
++) {
1304 sprintf(nodestring
, "/dev/%s%d", nodename
, index
);
1306 /* Get context of the node and set it as the default */
1307 if (selinux_enabled
) {
1308 if (matchpathcon(nodestring
, S_IRUSR
| S_IWUSR
, &node_context
) < 0) {
1309 pout("Could not retrieve context for %s", nodestring
);
1310 if (selinux_enforced
) {
1315 if (setfscreatecon(node_context
) < 0) {
1316 pout ("Error setting default fscreate context");
1317 if (selinux_enforced
) {
1324 /* Try to stat the node */
1325 if ((stat(nodestring
, &stat_buf
))) {
1326 pout("Node %s does not exist and must be created. Check the udev rules.\n", nodestring
);
1327 /* Create a new node if it doesn't exist */
1328 if (mknod(nodestring
, S_IFCHR
|0600, makedev(tw_major
, index
))) {
1329 pout("problem creating 3ware device nodes %s", nodestring
);
1335 if (selinux_enabled
&& node_context
) {
1336 freecon(node_context
);
1337 node_context
= NULL
;
1344 /* See if nodes major and minor numbers are correct */
1345 if ((tw_major
!= (int)(major(stat_buf
.st_rdev
))) ||
1346 (index
!= (int)(minor(stat_buf
.st_rdev
))) ||
1347 (!S_ISCHR(stat_buf
.st_mode
))) {
1348 pout("Node %s has wrong major/minor number and must be created anew."
1349 " Check the udev rules.\n", nodestring
);
1350 /* Delete the old node */
1351 if (unlink(nodestring
)) {
1352 pout("problem unlinking stale 3ware device node %s", nodestring
);
1358 /* Make a new node */
1359 if (mknod(nodestring
, S_IFCHR
|0600, makedev(tw_major
, index
))) {
1360 pout("problem creating 3ware device nodes %s", nodestring
);
1367 if (selinux_enabled
&& node_context
) {
1368 freecon(node_context
);
1369 node_context
= NULL
;
1375 if (selinux_enabled
) {
1376 if(setfscreatecon(orig_context
) < 0) {
1377 pout("Error re-setting original fscreate context");
1378 if (selinux_enforced
)
1382 freecon(orig_context
);
1384 freecon(node_context
);
1385 matchpathcon_fini();
1391 bool linux_escalade_device::open()
1393 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
||
1394 m_escalade_type
== AMCC_3WARE_678K_CHAR
) {
1395 // the device nodes for these controllers are dynamically assigned,
1396 // so we need to check that they exist with the correct major
1397 // numbers and if not, create them
1398 const char * node
= (m_escalade_type
== AMCC_3WARE_9700_CHAR
? "twl" :
1399 m_escalade_type
== AMCC_3WARE_9000_CHAR
? "twa" :
1401 const char * driver
= (m_escalade_type
== AMCC_3WARE_9700_CHAR
? "3w-sas" :
1402 m_escalade_type
== AMCC_3WARE_9000_CHAR
? "3w-9xxx" :
1404 if (setup_3ware_nodes(node
, driver
))
1405 return set_err((errno
? errno
: ENXIO
), "setup_3ware_nodes(\"%s\", \"%s\") failed", node
, driver
);
1407 // Continue with default open
1408 return linux_smart_device::open();
1411 // TODO: Function no longer useful
1412 //void printwarning(smart_command_set command);
1415 // This is an interface routine meant to isolate the OS dependent
1416 // parts of the code, and to provide a debugging interface. Each
1417 // different port and OS needs to provide it's own interface. This
1418 // is the linux interface to the 3ware 3w-xxxx driver. It allows ATA
1419 // commands to be passed through the SCSI driver.
1420 // DETAILED DESCRIPTION OF ARGUMENTS
1421 // fd: is the file descriptor provided by open()
1422 // disknum is the disk number (0 to 15) in the RAID array
1423 // escalade_type indicates the type of controller type, and if scsi or char interface is used
1424 // command: defines the different operations.
1425 // select: additional input data if needed (which log, which type of
1427 // data: location to write output data, if needed (512 bytes).
1428 // Note: not all commands use all arguments.
1430 // -1 if the command failed
1431 // 0 if the command succeeded,
1432 // STATUS_CHECK routine:
1433 // -1 if the command failed
1434 // 0 if the command succeeded and disk SMART status is "OK"
1435 // 1 if the command succeeded and disk SMART status is "FAILING"
1438 /* 512 is the max payload size: increase if needed */
1439 #define BUFFER_LEN_678K ( sizeof(TW_Ioctl) ) // 1044 unpacked, 1041 packed
1440 #define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1 ) // 1539 unpacked, 1536 packed
1441 #define BUFFER_LEN_9000 ( sizeof(TW_Ioctl_Buf_Apache)+512-1 ) // 2051 unpacked, 2048 packed
1442 #define TW_IOCTL_BUFFER_SIZE ( MAX(MAX(BUFFER_LEN_678K, BUFFER_LEN_9000), BUFFER_LEN_678K_CHAR) )
1444 bool linux_escalade_device::ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
)
1446 if (!ata_cmd_is_ok(in
,
1447 true, // data_out_support
1448 false, // TODO: multi_sector_support
1449 true) // ata_48bit_support
1453 // Used by both the SCSI and char interfaces
1454 TW_Passthru
*passthru
=NULL
;
1455 char ioctl_buffer
[TW_IOCTL_BUFFER_SIZE
];
1457 // only used for SCSI device interface
1458 TW_Ioctl
*tw_ioctl
=NULL
;
1459 TW_Output
*tw_output
=NULL
;
1461 // only used for 6000/7000/8000 char device interface
1462 TW_New_Ioctl
*tw_ioctl_char
=NULL
;
1464 // only used for 9000 character device interface
1465 TW_Ioctl_Buf_Apache
*tw_ioctl_apache
=NULL
;
1467 memset(ioctl_buffer
, 0, TW_IOCTL_BUFFER_SIZE
);
1469 // TODO: Handle controller differences by different classes
1470 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
) {
1471 tw_ioctl_apache
= (TW_Ioctl_Buf_Apache
*)ioctl_buffer
;
1472 tw_ioctl_apache
->driver_command
.control_code
= TW_IOCTL_FIRMWARE_PASS_THROUGH
;
1473 tw_ioctl_apache
->driver_command
.buffer_length
= 512; /* payload size */
1474 passthru
= (TW_Passthru
*)&(tw_ioctl_apache
->firmware_command
.command
.oldcommand
);
1476 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
) {
1477 tw_ioctl_char
= (TW_New_Ioctl
*)ioctl_buffer
;
1478 tw_ioctl_char
->data_buffer_length
= 512;
1479 passthru
= (TW_Passthru
*)&(tw_ioctl_char
->firmware_command
);
1481 else if (m_escalade_type
==AMCC_3WARE_678K
) {
1482 tw_ioctl
= (TW_Ioctl
*)ioctl_buffer
;
1483 tw_ioctl
->cdb
[0] = TW_IOCTL
;
1484 tw_ioctl
->opcode
= TW_ATA_PASSTHRU
;
1485 tw_ioctl
->input_length
= 512; // correct even for non-data commands
1486 tw_ioctl
->output_length
= 512; // correct even for non-data commands
1487 tw_output
= (TW_Output
*)tw_ioctl
;
1488 passthru
= (TW_Passthru
*)&(tw_ioctl
->input_data
);
1491 return set_err(ENOSYS
,
1492 "Unrecognized escalade_type %d in linux_3ware_command_interface(disk %d)\n"
1493 "Please contact " PACKAGE_BUGREPORT
"\n", (int)m_escalade_type
, m_disknum
);
1496 // Same for (almost) all commands - but some reset below
1497 passthru
->byte0
.opcode
= TW_OP_ATA_PASSTHRU
;
1498 passthru
->request_id
= 0xFF;
1499 passthru
->unit
= m_disknum
;
1500 passthru
->status
= 0;
1501 passthru
->flags
= 0x1;
1505 const ata_in_regs_48bit
& r
= in
.in_regs
;
1506 passthru
->features
= r
.features_16
;
1507 passthru
->sector_count
= r
.sector_count_16
;
1508 passthru
->sector_num
= r
.lba_low_16
;
1509 passthru
->cylinder_lo
= r
.lba_mid_16
;
1510 passthru
->cylinder_hi
= r
.lba_high_16
;
1511 passthru
->drive_head
= r
.device
;
1512 passthru
->command
= r
.command
;
1515 // Is this a command that reads or returns 512 bytes?
1516 // passthru->param values are:
1517 // 0x0 - non data command without TFR write check,
1518 // 0x8 - non data command with TFR write check,
1519 // 0xD - data command that returns data to host from device
1520 // 0xF - data command that writes data from host to device
1521 // passthru->size values are 0x5 for non-data and 0x07 for data
1522 bool readdata
= false;
1523 if (in
.direction
== ata_cmd_in::data_in
) {
1525 passthru
->byte0
.sgloff
= 0x5;
1526 passthru
->size
= 0x7; // TODO: Other value for multi-sector ?
1527 passthru
->param
= 0xD;
1528 // For 64-bit to work correctly, up the size of the command packet
1529 // in dwords by 1 to account for the 64-bit single sgl 'address'
1530 // field. Note that this doesn't agree with the typedefs but it's
1531 // right (agree with kernel driver behavior/typedefs).
1532 if ((m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1533 && sizeof(long) == 8)
1536 else if (in
.direction
== ata_cmd_in::no_data
) {
1537 // Non data command -- but doesn't use large sector
1538 // count register values.
1539 passthru
->byte0
.sgloff
= 0x0;
1540 passthru
->size
= 0x5;
1541 passthru
->param
= 0x8;
1542 passthru
->sector_count
= 0x0;
1544 else if (in
.direction
== ata_cmd_in::data_out
) {
1545 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1546 memcpy(tw_ioctl_apache
->data_buffer
, in
.buffer
, in
.size
);
1547 else if (m_escalade_type
== AMCC_3WARE_678K_CHAR
)
1548 memcpy(tw_ioctl_char
->data_buffer
, in
.buffer
, in
.size
);
1550 // COMMAND NOT SUPPORTED VIA SCSI IOCTL INTERFACE
1551 // memcpy(tw_output->output_data, data, 512);
1552 // printwarning(command); // TODO: Parameter no longer valid
1553 return set_err(ENOTSUP
, "DATA OUT not supported for this 3ware controller type");
1555 passthru
->byte0
.sgloff
= 0x5;
1556 passthru
->size
= 0x7; // TODO: Other value for multi-sector ?
1557 passthru
->param
= 0xF; // PIO data write
1558 if ((m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1559 && sizeof(long) == 8)
1563 return set_err(EINVAL
);
1565 // Now send the command down through an ioctl()
1567 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1568 ioctlreturn
=ioctl(get_fd(), TW_IOCTL_FIRMWARE_PASS_THROUGH
, tw_ioctl_apache
);
1569 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
)
1570 ioctlreturn
=ioctl(get_fd(), TW_CMD_PACKET_WITH_DATA
, tw_ioctl_char
);
1572 ioctlreturn
=ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND
, tw_ioctl
);
1574 // Deal with the different error cases
1576 if (AMCC_3WARE_678K
==m_escalade_type
1577 && in
.in_regs
.command
==ATA_SMART_CMD
1578 && ( in
.in_regs
.features
== ATA_SMART_AUTO_OFFLINE
1579 || in
.in_regs
.features
== ATA_SMART_AUTOSAVE
)
1580 && in
.in_regs
.lba_low
) {
1581 // error here is probably a kernel driver whose version is too old
1582 // printwarning(command); // TODO: Parameter no longer valid
1583 return set_err(ENOTSUP
, "Probably kernel driver too old");
1585 return set_err(EIO
);
1588 // The passthru structure is valid after return from an ioctl if:
1589 // - we are using the character interface OR
1590 // - we are using the SCSI interface and this is a NON-READ-DATA command
1591 // For SCSI interface, note that we set passthru to a different
1592 // value after ioctl().
1593 if (AMCC_3WARE_678K
==m_escalade_type
) {
1597 passthru
=(TW_Passthru
*)&(tw_output
->output_data
);
1600 // See if the ATA command failed. Now that we have returned from
1601 // the ioctl() call, if passthru is valid, then:
1602 // - passthru->status contains the 3ware controller STATUS
1603 // - passthru->command contains the ATA STATUS register
1604 // - passthru->features contains the ATA ERROR register
1606 // Check bits 0 (error bit) and 5 (device fault) of the ATA STATUS
1607 // If bit 0 (error bit) is set, then ATA ERROR register is valid.
1608 // While we *might* decode the ATA ERROR register, at the moment it
1609 // doesn't make much sense: we don't care in detail why the error
1612 if (passthru
&& (passthru
->status
|| (passthru
->command
& 0x21))) {
1613 return set_err(EIO
);
1616 // If this is a read data command, copy data to output buffer
1618 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1619 memcpy(in
.buffer
, tw_ioctl_apache
->data_buffer
, in
.size
);
1620 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
)
1621 memcpy(in
.buffer
, tw_ioctl_char
->data_buffer
, in
.size
);
1623 memcpy(in
.buffer
, tw_output
->output_data
, in
.size
);
1626 // Return register values
1628 ata_out_regs_48bit
& r
= out
.out_regs
;
1629 r
.error
= passthru
->features
;
1630 r
.sector_count_16
= passthru
->sector_count
;
1631 r
.lba_low_16
= passthru
->sector_num
;
1632 r
.lba_mid_16
= passthru
->cylinder_lo
;
1633 r
.lba_high_16
= passthru
->cylinder_hi
;
1634 r
.device
= passthru
->drive_head
;
1635 r
.status
= passthru
->command
;
1638 // look for nonexistent devices/ports
1639 if ( in
.in_regs
.command
== ATA_IDENTIFY_DEVICE
1640 && !nonempty(in
.buffer
, in
.size
)) {
1641 return set_err(ENODEV
, "No drive on port %d", m_disknum
);
1648 /////////////////////////////////////////////////////////////////////////////
1649 /// Areca RAID support
1651 class linux_areca_device
1652 : public /*implements*/ ata_device
,
1653 public /*extends*/ linux_smart_device
1656 linux_areca_device(smart_interface
* intf
, const char * dev_name
, int disknum
, int encnum
= 1);
1659 virtual bool ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
);
1662 int m_disknum
; ///< Disk number.
1663 int m_encnum
; ///< Enclosure number.
1668 // This is an interface routine meant to isolate the OS dependent
1669 // parts of the code, and to provide a debugging interface. Each
1670 // different port and OS needs to provide it's own interface. This
1671 // is the linux interface to the Areca "arcmsr" driver. It allows ATA
1672 // commands to be passed through the SCSI driver.
1673 // DETAILED DESCRIPTION OF ARGUMENTS
1674 // fd: is the file descriptor provided by open()
1675 // disknum is the disk number (0 to 15) in the RAID array
1676 // command: defines the different operations.
1677 // select: additional input data if needed (which log, which type of
1679 // data: location to write output data, if needed (512 bytes).
1680 // Note: not all commands use all arguments.
1682 // -1 if the command failed
1683 // 0 if the command succeeded,
1684 // STATUS_CHECK routine:
1685 // -1 if the command failed
1686 // 0 if the command succeeded and disk SMART status is "OK"
1687 // 1 if the command succeeded and disk SMART status is "FAILING"
1691 #define ARECA_SATA_RAID 0x90000000
1693 #define FUNCTION_READ_RQBUFFER 0x0801
1694 #define FUNCTION_WRITE_WQBUFFER 0x0802
1695 #define FUNCTION_CLEAR_RQBUFFER 0x0803
1696 #define FUNCTION_CLEAR_WQBUFFER 0x0804
1698 /* ARECA IO CONTROL CODE*/
1699 #define ARCMSR_IOCTL_READ_RQBUFFER (ARECA_SATA_RAID | FUNCTION_READ_RQBUFFER)
1700 #define ARCMSR_IOCTL_WRITE_WQBUFFER (ARECA_SATA_RAID | FUNCTION_WRITE_WQBUFFER)
1701 #define ARCMSR_IOCTL_CLEAR_RQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_RQBUFFER)
1702 #define ARCMSR_IOCTL_CLEAR_WQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_WQBUFFER)
1703 #define ARECA_SIG_STR "ARCMSR"
1705 // The SRB_IO_CONTROL & SRB_BUFFER structures are used to communicate(to/from) to areca driver
1706 typedef struct _SRB_IO_CONTROL
1708 unsigned int HeaderLength
;
1709 unsigned char Signature
[8];
1710 unsigned int Timeout
;
1711 unsigned int ControlCode
;
1712 unsigned int ReturnCode
;
1713 unsigned int Length
;
1716 typedef struct _SRB_BUFFER
1718 sSRB_IO_CONTROL srbioctl
;
1719 unsigned char ioctldatabuffer
[1032]; // the buffer to put the command data to/from firmware
1722 // Looks in /proc/scsi to suggest correct areca devices
1723 // If hint not NULL, return device path guess
1724 static int find_areca_in_proc(char *hint
)
1726 const char* proc_format_string
="host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n";
1728 // check data formwat
1729 FILE *fp
=fopen("/proc/scsi/sg/device_hdr", "r");
1731 pout("Unable to open /proc/scsi/sg/device_hdr for reading\n");
1735 // get line, compare to format
1738 char *out
= fgets(linebuf
, 256, fp
);
1741 pout("Unable to read contents of /proc/scsi/sg/device_hdr\n");
1745 if (strcmp(linebuf
, proc_format_string
)) {
1747 // Fix this by comparing only tokens not white space!!
1748 pout("Unexpected format %s in /proc/scsi/sg/device_hdr\n", proc_format_string
);
1752 // Format is understood, now search for correct device
1753 fp
=fopen("/proc/scsi/sg/devices", "r");
1755 int host
, chan
, id
, lun
, type
, opens
, qdepth
, busy
, online
;
1758 // search all lines of /proc/scsi/sg/devices
1759 while (9 == fscanf(fp
, "%d %d %d %d %d %d %d %d %d", &host
, &chan
, &id
, &lun
, &type
, &opens
, &qdepth
, &busy
, &online
)) {
1761 if (id
== 16 && type
== 3) {
1762 // devices with id=16 and type=3 might be Areca controllers
1763 if (!found
&& hint
) {
1764 sprintf(hint
, "/dev/sg%d", dev
);
1766 pout("Device /dev/sg%d appears to be an Areca controller.\n", dev
);
1775 #if 0 // For debugging areca code
1777 static void dumpdata(unsigned char *block
, int len
)
1779 int ln
= (len
/ 16) + 1; // total line#
1783 printf(" Address = %p, Length = (0x%x)%d\n", block
, len
, len
);
1784 printf(" 0 1 2 3 4 5 6 7 8 9 A B C D E F ASCII \n");
1785 printf("=====================================================================\n");
1787 for ( int l
= 0; l
< ln
&& len
; l
++ )
1789 // printf the line# and the HEX data
1790 // if a line data length < 16 then append the space to the tail of line to reach 16 chars
1791 printf("%02X | ", l
);
1792 for ( pos
= 0; pos
< 16 && len
; pos
++, len
-- )
1794 c
= block
[l
*16+pos
];
1800 for ( int loop
= pos
; loop
< 16; loop
++ )
1807 for ( int loop
= 0; loop
< pos
; loop
++ )
1809 c
= block
[l
*16+loop
];
1810 if ( c
>= 0x20 && c
<= 0x7F )
1821 printf("=====================================================================\n");
1826 static int arcmsr_command_handler(int fd
, unsigned long arcmsr_cmd
, unsigned char *data
, int data_len
, void *ext_data
/* reserved for further use */)
1830 int ioctlreturn
= 0;
1832 struct scsi_cmnd_io io_hdr
;
1833 int dir
= DXFER_TO_DEVICE
;
1838 unsigned char *areca_return_packet
;
1841 unsigned char return_buff
[2048];
1842 unsigned char *ptr
= &return_buff
[0];
1843 memset(return_buff
, 0, sizeof(return_buff
));
1845 memset((unsigned char *)&sBuf
, 0, sizeof(sBuf
));
1846 memset(&io_hdr
, 0, sizeof(io_hdr
));
1847 memset(cdb
, 0, sizeof(cdb
));
1848 memset(sense
, 0, sizeof(sense
));
1851 sBuf
.srbioctl
.HeaderLength
= sizeof(sSRB_IO_CONTROL
);
1852 memcpy(sBuf
.srbioctl
.Signature
, ARECA_SIG_STR
, strlen(ARECA_SIG_STR
));
1853 sBuf
.srbioctl
.Timeout
= 10000;
1854 sBuf
.srbioctl
.ControlCode
= ARCMSR_IOCTL_READ_RQBUFFER
;
1856 switch ( arcmsr_cmd
)
1858 // command for writing data to driver
1859 case ARCMSR_IOCTL_WRITE_WQBUFFER
:
1860 if ( data
&& data_len
)
1862 sBuf
.srbioctl
.Length
= data_len
;
1863 memcpy((unsigned char *)sBuf
.ioctldatabuffer
, (unsigned char *)data
, data_len
);
1865 // commands for clearing related buffer of driver
1866 case ARCMSR_IOCTL_CLEAR_RQBUFFER
:
1867 case ARCMSR_IOCTL_CLEAR_WQBUFFER
:
1868 cdb
[0] = 0x3B; //SCSI_WRITE_BUF command;
1870 // command for reading data from driver
1871 case ARCMSR_IOCTL_READ_RQBUFFER
:
1872 cdb
[0] = 0x3C; //SCSI_READ_BUF command;
1873 dir
= DXFER_FROM_DEVICE
;
1876 // unknown arcmsr commands
1883 // cdb[5][6][7][8] areca defined command code( to/from driver )
1885 cdb
[5] = (char)( arcmsr_cmd
>> 24);
1886 cdb
[6] = (char)( arcmsr_cmd
>> 16);
1887 cdb
[7] = (char)( arcmsr_cmd
>> 8);
1888 cdb
[8] = (char)( arcmsr_cmd
& 0x0F );
1890 io_hdr
.dxfer_dir
= dir
;
1891 io_hdr
.dxfer_len
= sizeof(sBuf
);
1892 io_hdr
.dxferp
= (unsigned char *)&sBuf
;
1894 io_hdr
.cmnd_len
= sizeof(cdb
);
1895 io_hdr
.sensep
= sense
;
1896 io_hdr
.max_sense_len
= sizeof(sense
);
1897 io_hdr
.timeout
= SCSI_TIMEOUT_DEFAULT
;
1901 ioctlreturn
= do_normal_scsi_cmnd_io(fd
, &io_hdr
, 0);
1902 if ( ioctlreturn
|| io_hdr
.scsi_status
)
1908 if ( arcmsr_cmd
!= ARCMSR_IOCTL_READ_RQBUFFER
)
1910 // if succeeded, just returns the length of outgoing data
1914 if ( sBuf
.srbioctl
.Length
)
1916 //dumpdata(&sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
1917 memcpy(ptr
, &sBuf
.ioctldatabuffer
[0], sBuf
.srbioctl
.Length
);
1918 ptr
+= sBuf
.srbioctl
.Length
;
1919 total
+= sBuf
.srbioctl
.Length
;
1920 // the returned bytes enough to compute payload length ?
1921 if ( expected
< 0 && total
>= 5 )
1923 areca_return_packet
= (unsigned char *)&return_buff
[0];
1924 if ( areca_return_packet
[0] == 0x5E &&
1925 areca_return_packet
[1] == 0x01 &&
1926 areca_return_packet
[2] == 0x61 )
1928 // valid header, let's compute the returned payload length,
1929 // we expected the total length is
1930 // payload + 3 bytes header + 2 bytes length + 1 byte checksum
1931 expected
= areca_return_packet
[4] * 256 + areca_return_packet
[3] + 6;
1935 if ( total
>= 7 && total
>= expected
)
1937 //printf("total bytes received = %d, expected length = %d\n", total, expected);
1939 // ------ Okay! we received enough --------
1945 // Deal with the different error cases
1948 pout("do_scsi_cmnd_io with write buffer failed code = %x\n", ioctlreturn
);
1953 if ( io_hdr
.scsi_status
)
1955 pout("io_hdr.scsi_status with write buffer failed code = %x\n", io_hdr
.scsi_status
);
1962 memcpy(data
, return_buff
, total
);
1969 linux_areca_device::linux_areca_device(smart_interface
* intf
, const char * dev_name
, int disknum
, int encnum
)
1970 : smart_device(intf
, dev_name
, "areca", "areca"),
1971 linux_smart_device(O_RDWR
| O_EXCL
| O_NONBLOCK
),
1975 set_info().info_name
= strprintf("%s [areca_disk#%02d_enc#%02d]", dev_name
, disknum
, encnum
);
1978 // Areca RAID Controller
1979 // int linux_areca_device::ata_command_interface(smart_command_set command, int select, char * data)
1980 bool linux_areca_device::ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
)
1982 if (!ata_cmd_is_ok(in
,
1983 true, // data_out_support
1984 false, // TODO: multi_sector_support
1985 true) // ata_48bit_support
1989 // ATA input registers
1990 typedef struct _ATA_INPUT_REGISTERS
1992 unsigned char features
;
1993 unsigned char sector_count
;
1994 unsigned char sector_number
;
1995 unsigned char cylinder_low
;
1996 unsigned char cylinder_high
;
1997 unsigned char device_head
;
1998 unsigned char command
;
1999 unsigned char reserved
[8];
2000 unsigned char data
[512]; // [in/out] buffer for outgoing/incoming data
2001 } sATA_INPUT_REGISTERS
;
2003 // ATA output registers
2004 // Note: The output registers is re-sorted for areca internal use only
2005 typedef struct _ATA_OUTPUT_REGISTERS
2007 unsigned char error
;
2008 unsigned char status
;
2009 unsigned char sector_count
;
2010 unsigned char sector_number
;
2011 unsigned char cylinder_low
;
2012 unsigned char cylinder_high
;
2013 }sATA_OUTPUT_REGISTERS
;
2015 // Areca packet format for outgoing:
2016 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
2017 // B[3~4] : 2 bytes command length + variant data length, little endian
2018 // B[5] : 1 bytes areca defined command code, ATA passthrough command code is 0x1c
2019 // B[6~last-1] : variant bytes payload data
2020 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
2023 // header 3 bytes length 2 bytes cmd 1 byte payload data x bytes cs 1 byte
2024 // +--------------------------------------------------------------------------------+
2025 // + 0x5E 0x01 0x61 | 0x00 0x00 | 0x1c | .................... | 0x00 |
2026 // +--------------------------------------------------------------------------------+
2029 //Areca packet format for incoming:
2030 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
2031 // B[3~4] : 2 bytes payload length, little endian
2032 // B[5~last-1] : variant bytes returned payload data
2033 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
2036 // header 3 bytes length 2 bytes payload data x bytes cs 1 byte
2037 // +-------------------------------------------------------------------+
2038 // + 0x5E 0x01 0x61 | 0x00 0x00 | .................... | 0x00 |
2039 // +-------------------------------------------------------------------+
2040 unsigned char areca_packet
[640];
2041 int areca_packet_len
= sizeof(areca_packet
);
2042 unsigned char cs
= 0;
2044 sATA_INPUT_REGISTERS
*ata_cmd
;
2048 memset(sInq
, 0, sizeof(sInq
));
2049 scsiStdInquiry(fd
, (unsigned char *)sInq
, (int)sizeof(sInq
));
2050 dumpdata((unsigned char *)sInq
, sizeof(sInq
));
2052 memset(areca_packet
, 0, areca_packet_len
);
2054 // ----- BEGIN TO SETUP HEADERS -------
2055 areca_packet
[0] = 0x5E;
2056 areca_packet
[1] = 0x01;
2057 areca_packet
[2] = 0x61;
2058 areca_packet
[3] = (unsigned char)((areca_packet_len
- 6) & 0xff);
2059 areca_packet
[4] = (unsigned char)(((areca_packet_len
- 6) >> 8) & 0xff);
2060 areca_packet
[5] = 0x1c; // areca defined code for ATA passthrough command
2062 // ----- BEGIN TO SETUP PAYLOAD DATA -----
2063 memcpy(&areca_packet
[7], "SmrT", 4); // areca defined password
2064 ata_cmd
= (sATA_INPUT_REGISTERS
*)&areca_packet
[12];
2068 const ata_in_regs_48bit
& r
= in
.in_regs
;
2069 ata_cmd
->features
= r
.features_16
;
2070 ata_cmd
->sector_count
= r
.sector_count_16
;
2071 ata_cmd
->sector_number
= r
.lba_low_16
;
2072 ata_cmd
->cylinder_low
= r
.lba_mid_16
;
2073 ata_cmd
->cylinder_high
= r
.lba_high_16
;
2074 ata_cmd
->device_head
= r
.device
;
2075 ata_cmd
->command
= r
.command
;
2077 bool readdata
= false;
2078 if (in
.direction
== ata_cmd_in::data_in
) {
2080 // the command will read data
2081 areca_packet
[6] = 0x13;
2083 else if ( in
.direction
== ata_cmd_in::no_data
)
2085 // the commands will return no data
2086 areca_packet
[6] = 0x15;
2088 else if (in
.direction
== ata_cmd_in::data_out
)
2090 // the commands will write data
2091 memcpy(ata_cmd
->data
, in
.buffer
, in
.size
);
2092 areca_packet
[6] = 0x14;
2095 // COMMAND NOT SUPPORTED VIA ARECA IOCTL INTERFACE
2096 return set_err(ENOTSUP
, "DATA OUT not supported for this Areca controller type");
2099 areca_packet
[11] = m_disknum
- 1; // disk#
2100 areca_packet
[19] = m_encnum
- 1; // enc#
2102 // ----- BEGIN TO SETUP CHECKSUM -----
2103 for ( int loop
= 3; loop
< areca_packet_len
- 1; loop
++ )
2105 cs
+= areca_packet
[loop
];
2107 areca_packet
[areca_packet_len
-1] = cs
;
2109 // ----- BEGIN TO SEND TO ARECA DRIVER ------
2111 unsigned char return_buff
[2048];
2112 memset(return_buff
, 0, sizeof(return_buff
));
2114 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_RQBUFFER
, NULL
, 0, NULL
);
2116 find_areca_in_proc(NULL
);
2117 return set_err(EIO
);
2120 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_WQBUFFER
, NULL
, 0, NULL
);
2121 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_WRITE_WQBUFFER
, areca_packet
, areca_packet_len
, NULL
);
2124 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_READ_RQBUFFER
, return_buff
, sizeof(return_buff
), NULL
);
2131 // ----- VERIFY THE CHECKSUM -----
2133 for ( int loop
= 3; loop
< expected
- 1; loop
++ )
2135 cs
+= return_buff
[loop
];
2138 if ( return_buff
[expected
- 1] != cs
)
2140 return set_err(EIO
);
2143 sATA_OUTPUT_REGISTERS
*ata_out
= (sATA_OUTPUT_REGISTERS
*)&return_buff
[5] ;
2144 if ( ata_out
->status
)
2146 if ( in
.in_regs
.command
== ATA_IDENTIFY_DEVICE
2147 && !nonempty((unsigned char *)in
.buffer
, in
.size
))
2149 return set_err(ENODEV
, "No drive on port %d", m_disknum
);
2153 // returns with data
2156 memcpy(in
.buffer
, &return_buff
[7], in
.size
);
2159 // Return register values
2161 ata_out_regs_48bit
& r
= out
.out_regs
;
2162 r
.error
= ata_out
->error
;
2163 r
.sector_count_16
= ata_out
->sector_count
;
2164 r
.lba_low_16
= ata_out
->sector_number
;
2165 r
.lba_mid_16
= ata_out
->cylinder_low
;
2166 r
.lba_high_16
= ata_out
->cylinder_high
;
2167 r
.status
= ata_out
->status
;
2173 /////////////////////////////////////////////////////////////////////////////
2176 class linux_marvell_device
2177 : public /*implements*/ ata_device_with_command_set
,
2178 public /*extends*/ linux_smart_device
2181 linux_marvell_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
2184 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2187 linux_marvell_device::linux_marvell_device(smart_interface
* intf
,
2188 const char * dev_name
, const char * req_type
)
2189 : smart_device(intf
, dev_name
, "marvell", req_type
),
2190 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
2194 int linux_marvell_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2203 mvsata_scsi_cmd smart_command
;
2204 unsigned char *buff
= (unsigned char *)&smart_command
.cmd
[6];
2205 // See struct hd_drive_cmd_hdr in hdreg.h
2206 // buff[0]: ATA COMMAND CODE REGISTER
2207 // buff[1]: ATA SECTOR NUMBER REGISTER
2208 // buff[2]: ATA FEATURES REGISTER
2209 // buff[3]: ATA SECTOR COUNT REGISTER
2211 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
2212 memset(&smart_command
, 0, sizeof(smart_command
));
2213 smart_command
.inlen
= 540;
2214 smart_command
.outlen
= 540;
2215 smart_command
.cmd
[0] = 0xC; //Vendor-specific code
2216 smart_command
.cmd
[4] = 6; //command length
2218 buff
[0] = ATA_SMART_CMD
;
2220 case CHECK_POWER_MODE
:
2221 buff
[0]=ATA_CHECK_POWER_MODE
;
2224 buff
[2]=ATA_SMART_READ_VALUES
;
2227 case READ_THRESHOLDS
:
2228 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
2229 copydata
=buff
[1]=buff
[3]=1;
2232 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
2237 buff
[0]=ATA_IDENTIFY_DEVICE
;
2241 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
2245 buff
[2]=ATA_SMART_ENABLE
;
2249 buff
[2]=ATA_SMART_DISABLE
;
2254 // this command only says if SMART is working. It could be
2255 // replaced with STATUS_CHECK below.
2256 buff
[2] = ATA_SMART_STATUS
;
2259 buff
[2]=ATA_SMART_AUTO_OFFLINE
;
2260 buff
[3]=select
; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2263 buff
[2]=ATA_SMART_AUTOSAVE
;
2264 buff
[3]=select
; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2266 case IMMEDIATE_OFFLINE
:
2267 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
2271 pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command
);
2275 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
2277 // We are now doing the HDIO_DRIVE_CMD type ioctl.
2278 if (ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND
, (void *)&smart_command
))
2281 if (command
==CHECK_POWER_MODE
) {
2282 // LEON -- CHECK THIS PLEASE. THIS SHOULD BE THE SECTOR COUNT
2283 // REGISTER, AND IT MIGHT BE buff[2] NOT buff[3]. Bruce
2288 // Always succeed on a SMART status, as a disk that failed returned
2289 // buff[4]=0xF4, buff[5]=0x2C, i.e. "Bad SMART status" (see below).
2290 if (command
== STATUS
)
2292 //Data returned is starting from 0 offset
2293 if (command
== STATUS_CHECK
)
2295 // Cyl low and Cyl high unchanged means "Good SMART status"
2296 if (buff
[4] == 0x4F && buff
[5] == 0xC2)
2298 // These values mean "Bad SMART status"
2299 if (buff
[4] == 0xF4 && buff
[5] == 0x2C)
2301 // We haven't gotten output that makes sense; print out some debugging info
2302 syserror("Error SMART Status command failed");
2303 pout("Please get assistance from %s\n",PACKAGE_BUGREPORT
);
2304 pout("Register values returned from SMART Status command are:\n");
2305 pout("CMD =0x%02x\n",(int)buff
[0]);
2306 pout("FR =0x%02x\n",(int)buff
[1]);
2307 pout("NS =0x%02x\n",(int)buff
[2]);
2308 pout("SC =0x%02x\n",(int)buff
[3]);
2309 pout("CL =0x%02x\n",(int)buff
[4]);
2310 pout("CH =0x%02x\n",(int)buff
[5]);
2311 pout("SEL=0x%02x\n",(int)buff
[6]);
2316 memcpy(data
, buff
, 512);
2321 /////////////////////////////////////////////////////////////////////////////
2322 /// Highpoint RAID support
2324 class linux_highpoint_device
2325 : public /*implements*/ ata_device_with_command_set
,
2326 public /*extends*/ linux_smart_device
2329 linux_highpoint_device(smart_interface
* intf
, const char * dev_name
,
2330 unsigned char controller
, unsigned char channel
, unsigned char port
);
2333 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2336 unsigned char m_hpt_data
[3]; ///< controller/channel/port
2339 linux_highpoint_device::linux_highpoint_device(smart_interface
* intf
, const char * dev_name
,
2340 unsigned char controller
, unsigned char channel
, unsigned char port
)
2341 : smart_device(intf
, dev_name
, "hpt", "hpt"),
2342 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
2344 m_hpt_data
[0] = controller
; m_hpt_data
[1] = channel
; m_hpt_data
[2] = port
;
2345 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]);
2348 // this implementation is derived from ata_command_interface with a header
2349 // packing for highpoint linux driver ioctl interface
2351 // ioctl(fd,HPTIO_CTL,buff)
2354 // structure of hpt_buff
2355 // +----+----+----+----+--------------------.....---------------------+
2356 // | 1 | 2 | 3 | 4 | 5 |
2357 // +----+----+----+----+--------------------.....---------------------+
2359 // 1: The target controller [ int ( 4 Bytes ) ]
2360 // 2: The channel of the target controllee [ int ( 4 Bytes ) ]
2361 // 3: HDIO_ ioctl call [ int ( 4 Bytes ) ]
2362 // available from ${LINUX_KERNEL_SOURCE}/Documentation/ioctl/hdio
2363 // 4: the pmport that disk attached, [ int ( 4 Bytes ) ]
2364 // if no pmport device, set to 1 or leave blank
2365 // 5: data [ void * ( var leangth ) ]
2367 #define STRANGE_BUFFER_LENGTH (4+512*0xf8)
2369 int linux_highpoint_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2371 unsigned char hpt_buff
[4*sizeof(int) + STRANGE_BUFFER_LENGTH
];
2372 unsigned int *hpt
= (unsigned int *)hpt_buff
;
2373 unsigned char *buff
= &hpt_buff
[4*sizeof(int)];
2375 const int HDIO_DRIVE_CMD_OFFSET
= 4;
2377 memset(hpt_buff
, 0, 4*sizeof(int) + STRANGE_BUFFER_LENGTH
);
2378 hpt
[0] = m_hpt_data
[0]; // controller id
2379 hpt
[1] = m_hpt_data
[1]; // channel number
2380 hpt
[3] = m_hpt_data
[2]; // pmport number
2382 buff
[0]=ATA_SMART_CMD
;
2384 case CHECK_POWER_MODE
:
2385 buff
[0]=ATA_CHECK_POWER_MODE
;
2389 buff
[2]=ATA_SMART_READ_VALUES
;
2393 case READ_THRESHOLDS
:
2394 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
2399 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
2407 buff
[0]=ATA_IDENTIFY_DEVICE
;
2412 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
2417 buff
[2]=ATA_SMART_ENABLE
;
2421 buff
[2]=ATA_SMART_DISABLE
;
2425 buff
[2]=ATA_SMART_STATUS
;
2428 buff
[2]=ATA_SMART_AUTO_OFFLINE
;
2432 buff
[2]=ATA_SMART_AUTOSAVE
;
2435 case IMMEDIATE_OFFLINE
:
2436 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
2440 buff
[1]=ATA_SMART_STATUS
;
2443 pout("Unrecognized command %d in linux_highpoint_command_interface()\n"
2444 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
2449 if (command
==WRITE_LOG
) {
2450 unsigned char task
[4*sizeof(int)+sizeof(ide_task_request_t
)+512];
2451 unsigned int *hpt_tf
= (unsigned int *)task
;
2452 ide_task_request_t
*reqtask
= (ide_task_request_t
*)(&task
[4*sizeof(int)]);
2453 task_struct_t
*taskfile
= (task_struct_t
*)reqtask
->io_ports
;
2456 memset(task
, 0, sizeof(task
));
2458 hpt_tf
[0] = m_hpt_data
[0]; // controller id
2459 hpt_tf
[1] = m_hpt_data
[1]; // channel number
2460 hpt_tf
[3] = m_hpt_data
[2]; // pmport number
2461 hpt_tf
[2] = HDIO_DRIVE_TASKFILE
; // real hd ioctl
2464 taskfile
->feature
= ATA_SMART_WRITE_LOG_SECTOR
;
2465 taskfile
->sector_count
= 1;
2466 taskfile
->sector_number
= select
;
2467 taskfile
->low_cylinder
= 0x4f;
2468 taskfile
->high_cylinder
= 0xc2;
2469 taskfile
->device_head
= 0;
2470 taskfile
->command
= ATA_SMART_CMD
;
2472 reqtask
->data_phase
= TASKFILE_OUT
;
2473 reqtask
->req_cmd
= IDE_DRIVE_TASK_OUT
;
2474 reqtask
->out_size
= 512;
2475 reqtask
->in_size
= 0;
2477 memcpy(task
+sizeof(ide_task_request_t
)+4*sizeof(int), data
, 512);
2479 if ((retval
=ioctl(get_fd(), HPTIO_CTL
, task
))) {
2480 if (retval
==-EINVAL
)
2481 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
2487 if (command
==STATUS_CHECK
){
2489 unsigned const char normal_lo
=0x4f, normal_hi
=0xc2;
2490 unsigned const char failed_lo
=0xf4, failed_hi
=0x2c;
2494 hpt
[2] = HDIO_DRIVE_TASK
;
2496 if ((retval
=ioctl(get_fd(), HPTIO_CTL
, hpt_buff
))) {
2497 if (retval
==-EINVAL
) {
2498 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
2499 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
2502 syserror("Error SMART Status command failed");
2506 if (buff
[4]==normal_lo
&& buff
[5]==normal_hi
)
2509 if (buff
[4]==failed_lo
&& buff
[5]==failed_hi
)
2512 syserror("Error SMART Status command failed");
2513 pout("Please get assistance from " PACKAGE_HOMEPAGE
"\n");
2514 pout("Register values returned from SMART Status command are:\n");
2515 pout("CMD=0x%02x\n",(int)buff
[0]);
2516 pout("FR =0x%02x\n",(int)buff
[1]);
2517 pout("NS =0x%02x\n",(int)buff
[2]);
2518 pout("SC =0x%02x\n",(int)buff
[3]);
2519 pout("CL =0x%02x\n",(int)buff
[4]);
2520 pout("CH =0x%02x\n",(int)buff
[5]);
2521 pout("SEL=0x%02x\n",(int)buff
[6]);
2526 if (command
==IDENTIFY
|| command
==PIDENTIFY
) {
2527 unsigned char deviceid
[4*sizeof(int)+512*sizeof(char)];
2528 unsigned int *hpt_id
= (unsigned int *)deviceid
;
2530 hpt_id
[0] = m_hpt_data
[0]; // controller id
2531 hpt_id
[1] = m_hpt_data
[1]; // channel number
2532 hpt_id
[3] = m_hpt_data
[2]; // pmport number
2534 hpt_id
[2] = HDIO_GET_IDENTITY
;
2535 if (!ioctl(get_fd(), HPTIO_CTL
, deviceid
) && (deviceid
[4*sizeof(int)] & 0x8000))
2536 buff
[0]=(command
==IDENTIFY
)?ATA_IDENTIFY_PACKET_DEVICE
:ATA_IDENTIFY_DEVICE
;
2540 hpt
[2] = HDIO_DRIVE_CMD
;
2541 if ((ioctl(get_fd(), HPTIO_CTL
, hpt_buff
)))
2544 if (command
==CHECK_POWER_MODE
)
2545 buff
[HDIO_DRIVE_CMD_OFFSET
]=buff
[2];
2548 memcpy(data
, buff
+HDIO_DRIVE_CMD_OFFSET
, copydata
);
2554 #if 0 // TODO: Migrate from 'smart_command_set' to 'ata_in_regs' OR remove the function
2555 // Utility function for printing warnings
2556 void printwarning(smart_command_set command
){
2557 static int printed
[4]={0,0,0,0};
2558 const char* message
=
2559 "can not be passed through the 3ware 3w-xxxx driver. This can be fixed by\n"
2560 "applying a simple 3w-xxxx driver patch that can be found here:\n"
2561 PACKAGE_HOMEPAGE
"\n"
2562 "Alternatively, upgrade your 3w-xxxx driver to version 1.02.00.037 or greater.\n\n";
2564 if (command
==AUTO_OFFLINE
&& !printed
[0]) {
2566 pout("The SMART AUTO-OFFLINE ENABLE command (smartmontools -o on option/Directive)\n%s", message
);
2568 else if (command
==AUTOSAVE
&& !printed
[1]) {
2570 pout("The SMART AUTOSAVE ENABLE command (smartmontools -S on option/Directive)\n%s", message
);
2572 else if (command
==STATUS_CHECK
&& !printed
[2]) {
2574 pout("The SMART RETURN STATUS return value (smartmontools -H option/Directive)\n%s", message
);
2576 else if (command
==WRITE_LOG
&& !printed
[3]) {
2578 pout("The SMART WRITE LOG command (smartmontools -t selective) only supported via char /dev/tw[ae] interface\n");
2586 /////////////////////////////////////////////////////////////////////////////
2587 /// SCSI open with autodetection support
2589 smart_device
* linux_scsi_device::autodetect_open()
2595 // No Autodetection if device type was specified by user
2596 bool sat_only
= false;
2597 if (*get_req_type()) {
2598 // Detect SAT if device object was created by scan_smart_devices().
2599 if (!(m_scanning
&& !strcmp(get_req_type(), "sat")))
2604 // The code below is based on smartd.cpp:SCSIFilterKnown()
2607 unsigned char req_buff
[64] = {0, };
2609 if (scsiStdInquiry(this, req_buff
, req_len
)) {
2610 // Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices
2611 // watch this spot ... other devices could lock up here
2613 if (scsiStdInquiry(this, req_buff
, req_len
)) {
2614 // device doesn't like INQUIRY commands
2616 set_err(EIO
, "INQUIRY failed");
2621 int avail_len
= req_buff
[4] + 5;
2622 int len
= (avail_len
< req_len
? avail_len
: req_len
);
2626 set_err(EIO
, "INQUIRY too short for SAT");
2631 // Use INQUIRY to detect type
2635 if (!memcmp(req_buff
+ 8, "3ware", 5) || !memcmp(req_buff
+ 8, "AMCC", 4)) {
2637 set_err(EINVAL
, "AMCC/3ware controller, please try adding '-d 3ware,N',\n"
2638 "you may need to replace %s with /dev/twlN, /dev/twaN or /dev/tweN", get_dev_name());
2643 if (!memcmp(req_buff
+ 8, "DELL PERC", 12) || !memcmp(req_buff
+ 8, "MegaRAID", 8)) {
2645 set_err(EINVAL
, "DELL or MegaRaid controller, please try adding '-d megaraid,N'");
2650 if (len
>= 42 && !memcmp(req_buff
+ 36, "MVSATA", 6)) {
2651 //pout("Device %s: using '-d marvell' for ATA disk with Marvell driver\n", get_dev_name());
2653 smart_device_auto_ptr
newdev(
2654 new linux_marvell_device(smi(), get_dev_name(), get_req_type())
2656 newdev
->open(); // TODO: Can possibly pass open fd
2658 return newdev
.release();
2664 smart_device
* newdev
= smi()->autodetect_sat_device(this, req_buff
, len
);
2666 // NOTE: 'this' is now owned by '*newdev'
2670 // Nothing special found
2674 set_err(EIO
, "Not a SAT device");
2680 //////////////////////////////////////////////////////////////////////
2681 // USB bridge ID detection
2683 // Read USB ID from /sys file
2684 static bool read_id(const std::string
& path
, unsigned short & id
)
2686 FILE * f
= fopen(path
.c_str(), "r");
2690 bool ok
= (fscanf(f
, "%hx%n", &id
, &n
) == 1 && n
== 4);
2695 // Get USB bridge ID for "sdX"
2696 static bool get_usb_id(const char * name
, unsigned short & vendor_id
,
2697 unsigned short & product_id
, unsigned short & version
)
2699 // Only "sdX" supported
2700 if (!(!strncmp(name
, "sd", 2) && !strchr(name
, '/')))
2703 // Start search at dir referenced by symlink "/sys/block/sdX/device"
2704 // -> "/sys/devices/.../usb*/.../host*/target*/..."
2705 std::string dir
= strprintf("/sys/block/%s/device", name
);
2707 // Stop search at "/sys/devices"
2709 if (stat("/sys/devices", &st
))
2711 ino_t stop_ino
= st
.st_ino
;
2713 // Search in parent directories until "idVendor" is found,
2714 // fail if "/sys/devices" reached or too many iterations
2718 if (!(++cnt
< 10 && !stat(dir
.c_str(), &st
) && st
.st_ino
!= stop_ino
))
2720 } while (access((dir
+ "/idVendor").c_str(), 0));
2723 if (!( read_id(dir
+ "/idVendor", vendor_id
)
2724 && read_id(dir
+ "/idProduct", product_id
)
2725 && read_id(dir
+ "/bcdDevice", version
) ))
2728 if (scsi_debugmode
> 1)
2729 pout("USB ID = 0x%04x:0x%04x (0x%03x)\n", vendor_id
, product_id
, version
);
2734 //////////////////////////////////////////////////////////////////////
2737 class linux_smart_interface
2738 : public /*implements*/ smart_interface
2741 virtual std::string
get_os_version_str();
2743 virtual std::string
get_app_examples(const char * appname
);
2745 virtual bool scan_smart_devices(smart_device_list
& devlist
, const char * type
,
2746 const char * pattern
= 0);
2749 virtual ata_device
* get_ata_device(const char * name
, const char * type
);
2751 virtual scsi_device
* get_scsi_device(const char * name
, const char * type
);
2753 virtual smart_device
* autodetect_smart_device(const char * name
);
2755 virtual smart_device
* get_custom_smart_device(const char * name
, const char * type
);
2757 virtual std::string
get_valid_custom_dev_types_str();
2760 bool get_dev_list(smart_device_list
& devlist
, const char * pattern
,
2761 bool scan_ata
, bool scan_scsi
, const char * req_type
, bool autodetect
);
2763 smart_device
* missing_option(const char * opt
);
2766 std::string
linux_smart_interface::get_os_version_str()
2770 return strprintf("%s-linux-%s", u
.machine
, u
.release
);
2772 return SMARTMONTOOLS_BUILD_HOST
;
2775 std::string
linux_smart_interface::get_app_examples(const char * appname
)
2777 if (!strcmp(appname
, "smartctl"))
2778 return smartctl_examples
;
2783 // we are going to take advantage of the fact that Linux's devfs will only
2784 // have device entries for devices that exist. So if we get the equivalent of
2785 // ls /dev/hd[a-t], we have all the ATA devices on the system
2786 bool linux_smart_interface::get_dev_list(smart_device_list
& devlist
,
2787 const char * pattern
, bool scan_ata
, bool scan_scsi
,
2788 const char * req_type
, bool autodetect
)
2790 // Use glob to look for any directory entries matching the pattern
2792 memset(&globbuf
, 0, sizeof(globbuf
));
2793 int retglob
= glob(pattern
, GLOB_ERR
, NULL
, &globbuf
);
2795 // glob failed: free memory and return
2798 if (retglob
==GLOB_NOMATCH
){
2799 pout("glob(3) found no matches for pattern %s\n", pattern
);
2803 if (retglob
==GLOB_NOSPACE
)
2804 set_err(ENOMEM
, "glob(3) ran out of memory matching pattern %s", pattern
);
2805 #ifdef GLOB_ABORTED // missing in old versions of glob.h
2806 else if (retglob
==GLOB_ABORTED
)
2807 set_err(EINVAL
, "glob(3) aborted matching pattern %s", pattern
);
2810 set_err(EINVAL
, "Unexplained error in glob(3) of pattern %s", pattern
);
2815 // did we find too many paths?
2816 const int max_pathc
= 32;
2817 int n
= (int)globbuf
.gl_pathc
;
2818 if (n
> max_pathc
) {
2819 pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n",
2820 n
, max_pathc
, pattern
, n
- max_pathc
);
2824 // now step through the list returned by glob. If not a link, copy
2825 // to list. If it is a link, evaluate it and see if the path ends
2827 for (int i
= 0; i
< n
; i
++){
2828 // see if path is a link
2830 int retlink
= readlink(globbuf
.gl_pathv
[i
], linkbuf
, sizeof(linkbuf
)-1);
2832 char tmpname
[1024]={0};
2833 const char * name
= 0;
2834 bool is_scsi
= scan_scsi
;
2835 // if not a link (or a strange link), keep it
2836 if (retlink
<=0 || retlink
>1023)
2837 name
= globbuf
.gl_pathv
[i
];
2839 // or if it's a link that points to a disc, follow it
2840 linkbuf
[retlink
] = 0;
2842 if ((p
=strrchr(linkbuf
, '/')) && !strcmp(p
+1, "disc"))
2843 // This is the branch of the code that gets followed if we are
2844 // using devfs WITH traditional compatibility links. In this
2845 // case, we add the traditional device name to the list that
2847 name
= globbuf
.gl_pathv
[i
];
2849 // This is the branch of the code that gets followed if we are
2850 // using devfs WITHOUT traditional compatibility links. In
2851 // this case, we check that the link to the directory is of
2852 // the correct type, and then append "disc" to it.
2853 bool match_ata
= strstr(linkbuf
, "ide");
2854 bool match_scsi
= strstr(linkbuf
, "scsi");
2855 if (((match_ata
&& scan_ata
) || (match_scsi
&& scan_scsi
)) && !(match_ata
&& match_scsi
)) {
2856 is_scsi
= match_scsi
;
2857 snprintf(tmpname
, sizeof(tmpname
), "%s/disc", globbuf
.gl_pathv
[i
]);
2864 // Found a name, add device to list.
2867 dev
= autodetect_smart_device(name
);
2869 dev
= new linux_scsi_device(this, name
, req_type
, true /*scanning*/);
2871 dev
= new linux_ata_device(this, name
, req_type
);
2872 if (dev
) // autodetect_smart_device() may return nullptr.
2873 devlist
.push_back(dev
);
2883 bool linux_smart_interface::scan_smart_devices(smart_device_list
& devlist
,
2884 const char * type
, const char * pattern
/*= 0*/)
2887 set_err(EINVAL
, "DEVICESCAN with pattern not implemented yet");
2894 bool scan_ata
= (!*type
|| !strcmp(type
, "ata" ));
2895 // "sat" detection will be later handled in linux_scsi_device::autodetect_open()
2896 bool scan_scsi
= (!*type
|| !strcmp(type
, "scsi") || !strcmp(type
, "sat"));
2897 if (!(scan_ata
|| scan_scsi
))
2901 get_dev_list(devlist
, "/dev/hd[a-t]", true, false, type
, false);
2903 bool autodetect
= !*type
; // Try USB autodetection if no type specifed
2904 get_dev_list(devlist
, "/dev/sd[a-z]", false, true, type
, autodetect
);
2905 // Support up to 104 devices
2906 get_dev_list(devlist
, "/dev/sd[a-c][a-z]", false, true, type
, autodetect
);
2909 // if we found traditional links, we are done
2910 if (devlist
.size() > 0)
2913 // else look for devfs entries without traditional links
2914 // TODO: Add udev support
2915 return get_dev_list(devlist
, "/dev/discs/disc*", scan_ata
, scan_scsi
, type
, false);
2918 ata_device
* linux_smart_interface::get_ata_device(const char * name
, const char * type
)
2920 return new linux_ata_device(this, name
, type
);
2923 scsi_device
* linux_smart_interface::get_scsi_device(const char * name
, const char * type
)
2925 return new linux_scsi_device(this, name
, type
);
2928 smart_device
* linux_smart_interface::missing_option(const char * opt
)
2930 set_err(EINVAL
, "requires option '%s'", opt
);
2934 // Return kernel release as integer ("2.6.31" -> 206031)
2935 static unsigned get_kernel_release()
2940 unsigned x
= 0, y
= 0, z
= 0;
2941 if (!(sscanf(u
.release
, "%u.%u.%u", &x
, &y
, &z
) == 3
2942 && x
< 100 && y
< 100 && z
< 1000 ))
2944 return x
* 100000 + y
* 1000 + z
;
2947 // Guess device type (ata or scsi) based on device name (Linux
2948 // specific) SCSI device name in linux can be sd, sr, scd, st, nst,
2949 // osst, nosst and sg.
2950 smart_device
* linux_smart_interface::autodetect_smart_device(const char * name
)
2952 const char * test_name
= name
;
2954 // Dereference symlinks
2956 std::string pathbuf
;
2957 if (!lstat(name
, &st
) && S_ISLNK(st
.st_mode
)) {
2958 char * p
= realpath(name
, (char *)0);
2962 test_name
= pathbuf
.c_str();
2966 // Remove the leading /dev/... if it's there
2967 static const char dev_prefix
[] = "/dev/";
2968 if (str_starts_with(test_name
, dev_prefix
))
2969 test_name
+= strlen(dev_prefix
);
2971 // form /dev/h* or h*
2972 if (str_starts_with(test_name
, "h"))
2973 return new linux_ata_device(this, name
, "");
2975 // form /dev/ide/* or ide/*
2976 if (str_starts_with(test_name
, "ide/"))
2977 return new linux_ata_device(this, name
, "");
2979 // form /dev/s* or s*
2980 if (str_starts_with(test_name
, "s")) {
2982 // Try to detect possible USB->(S)ATA bridge
2983 unsigned short vendor_id
= 0, product_id
= 0, version
= 0;
2984 if (get_usb_id(test_name
, vendor_id
, product_id
, version
)) {
2985 const char * usbtype
= get_usb_dev_type_by_id(vendor_id
, product_id
, version
);
2989 // Kernels before 2.6.29 do not support the sense data length
2990 // required for SAT ATA PASS-THROUGH(16)
2991 if (!strcmp(usbtype
, "sat") && get_kernel_release() < 206029)
2994 // Return SAT/USB device for this type
2995 // (Note: linux_scsi_device::autodetect_open() will not be called in this case)
2996 return get_sat_device(usbtype
, new linux_scsi_device(this, name
, ""));
2999 // No USB bridge found, assume regular SCSI device
3000 return new linux_scsi_device(this, name
, "");
3003 // form /dev/scsi/* or scsi/*
3004 if (str_starts_with(test_name
, "scsi/"))
3005 return new linux_scsi_device(this, name
, "");
3007 // form /dev/ns* or ns*
3008 if (str_starts_with(test_name
, "ns"))
3009 return new linux_scsi_device(this, name
, "");
3011 // form /dev/os* or os*
3012 if (str_starts_with(test_name
, "os"))
3013 return new linux_scsi_device(this, name
, "");
3015 // form /dev/nos* or nos*
3016 if (str_starts_with(test_name
, "nos"))
3017 return new linux_scsi_device(this, name
, "");
3019 // form /dev/tw[ael]* or tw[ael]*
3020 if (str_starts_with(test_name
, "tw") && strchr("ael", test_name
[2]))
3021 return missing_option("-d 3ware,N");
3023 // form /dev/cciss/* or cciss/*
3024 if (str_starts_with(test_name
, "cciss/"))
3025 return missing_option("-d cciss,N");
3027 // we failed to recognize any of the forms
3031 smart_device
* linux_smart_interface::get_custom_smart_device(const char * name
, const char * type
)
3034 if (!strcmp(type
, "marvell"))
3035 return new linux_marvell_device(this, name
, type
);
3038 int disknum
= -1, n1
= -1, n2
= -1;
3039 if (sscanf(type
, "3ware,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3040 if (n2
!= (int)strlen(type
)) {
3041 set_err(EINVAL
, "Option -d 3ware,N requires N to be a non-negative integer");
3044 if (!(0 <= disknum
&& disknum
<= 127)) {
3045 set_err(EINVAL
, "Option -d 3ware,N (N=%d) must have 0 <= N <= 127", disknum
);
3049 if (!strncmp(name
, "/dev/twl", 8))
3050 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_9700_CHAR
, disknum
);
3051 else if (!strncmp(name
, "/dev/twa", 8))
3052 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_9000_CHAR
, disknum
);
3053 else if (!strncmp(name
, "/dev/twe", 8))
3054 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_678K_CHAR
, disknum
);
3056 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_678K
, disknum
);
3060 disknum
= n1
= n2
= -1;
3062 if (sscanf(type
, "areca,%n%d/%d%n", &n1
, &disknum
, &encnum
, &n2
) >= 1 || n1
== 6) {
3063 if (!(1 <= disknum
&& disknum
<= 128)) {
3064 set_err(EINVAL
, "Option -d areca,N/E (N=%d) must have 1 <= N <= 128", disknum
);
3067 if (!(1 <= encnum
&& encnum
<= 8)) {
3068 set_err(EINVAL
, "Option -d areca,N/E (E=%d) must have 1 <= E <= 8", encnum
);
3071 return new linux_areca_device(this, name
, disknum
, encnum
);
3075 int controller
= -1, channel
= -1; disknum
= 1;
3076 n1
= n2
= -1; int n3
= -1;
3077 if (sscanf(type
, "hpt,%n%d/%d%n/%d%n", &n1
, &controller
, &channel
, &n2
, &disknum
, &n3
) >= 2 || n1
== 4) {
3078 int len
= strlen(type
);
3079 if (!(n2
== len
|| n3
== len
)) {
3080 set_err(EINVAL
, "Option '-d hpt,L/M/N' supports 2-3 items");
3083 if (!(1 <= controller
&& controller
<= 8)) {
3084 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid controller id L supplied");
3087 if (!(1 <= channel
&& channel
<= 16)) {
3088 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid channel number M supplied");
3091 if (!(1 <= disknum
&& disknum
<= 15)) {
3092 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid pmport number N supplied");
3095 return new linux_highpoint_device(this, name
, controller
, channel
, disknum
);
3098 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3100 disknum
= n1
= n2
= -1;
3101 if (sscanf(type
, "cciss,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3102 if (n2
!= (int)strlen(type
)) {
3103 set_err(EINVAL
, "Option -d cciss,N requires N to be a non-negative integer");
3106 if (!(0 <= disknum
&& disknum
<= 127)) {
3107 set_err(EINVAL
, "Option -d cciss,N (N=%d) must have 0 <= N <= 127", disknum
);
3110 return new linux_cciss_device(this, name
, disknum
);
3112 #endif // HAVE_LINUX_CCISS_IOCTL_H
3115 if (sscanf(type
, "megaraid,%d", &disknum
) == 1) {
3116 return new linux_megaraid_device(this, name
, 0, disknum
);
3121 std::string
linux_smart_interface::get_valid_custom_dev_types_str()
3123 return "marvell, areca,N/E, 3ware,N, hpt,L/M/N, megaraid,N"
3124 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3133 /////////////////////////////////////////////////////////////////////////////
3134 /// Initialize platform interface and register with smi()
3136 void smart_interface::init()
3138 static os_linux::linux_smart_interface the_interface
;
3139 smart_interface::set(&the_interface
);