4 * Home page of code is: http://smartmontools.sourceforge.net
6 * Copyright (C) 2003-8 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2003-8 Doug Gilbert <dougg@torque.net>
8 * Copyright (C) 2008 Hank Wu <hank@areca.com.tw>
9 * Copyright (C) 2008 Oliver Bock <brevilo@users.sourceforge.net>
10 * Copyright (C) 2008-9 Christian Franke <smartmontools-support@lists.sourceforge.net>
11 * Copyright (C) 2008 Jordan Hargrave <jordan_hargrave@dell.com>
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>
66 #include <sys/types.h>
67 #ifndef makedev // old versions of types.h do not include sysmacros.h
68 #include <sys/sysmacros.h>
71 #include <selinux/selinux.h>
84 #include "dev_interface.h"
85 #include "dev_ata_cmd_set.h"
88 #define ENOTSUP ENOSYS
91 #define ARGUSED(x) ((void)(x))
93 const char *os_XXXX_c_cvsid
="$Id: os_linux.cpp 2879 2009-08-29 17:19:00Z chrfranke $" \
94 ATACMDS_H_CVSID CONFIG_H_CVSID INT64_H_CVSID OS_LINUX_H_CVSID SCSICMDS_H_CVSID UTILITY_H_CVSID
;
96 /* for passing global control variables */
97 // (con->reportscsiioctl only)
98 extern smartmonctrl
*con
;
101 namespace os_linux
{ // No need to publish anything, name provided for Doxygen
103 /////////////////////////////////////////////////////////////////////////////
104 /// Shared open/close routines
106 class linux_smart_device
107 : virtual public /*implements*/ smart_device
110 explicit linux_smart_device(int flags
, int retry_flags
= -1)
111 : smart_device(never_called
),
113 m_flags(flags
), m_retry_flags(retry_flags
)
116 virtual ~linux_smart_device() throw();
118 virtual bool is_open() const;
122 virtual bool close();
125 /// Return filedesc for derived classes.
130 int m_fd
; ///< filedesc, -1 if not open.
131 int m_flags
; ///< Flags for ::open()
132 int m_retry_flags
; ///< Flags to retry ::open(), -1 if no retry
136 linux_smart_device::~linux_smart_device() throw()
142 bool linux_smart_device::is_open() const
147 bool linux_smart_device::open()
149 m_fd
= ::open(get_dev_name(), m_flags
);
151 if (m_fd
< 0 && errno
== EROFS
&& m_retry_flags
!= -1)
153 m_fd
= ::open(get_dev_name(), m_retry_flags
);
156 if (errno
== EBUSY
&& (m_flags
& O_EXCL
))
158 return set_err(EBUSY
,
159 "The requested controller is used exclusively by another process!\n"
160 "(e.g. smartctl or smartd)\n"
161 "Please quit the impeding process or try again later...");
162 return set_err((errno
==ENOENT
|| errno
==ENOTDIR
) ? ENODEV
: errno
);
166 // sets FD_CLOEXEC on the opened device file descriptor. The
167 // descriptor is otherwise leaked to other applications (mail
168 // sender) which may be considered a security risk and may result
169 // in AVC messages on SELinux-enabled systems.
170 if (-1 == fcntl(m_fd
, F_SETFD
, FD_CLOEXEC
))
171 // TODO: Provide an error printing routine in class smart_interface
172 pout("fcntl(set FD_CLOEXEC) failed, errno=%d [%s]\n", errno
, strerror(errno
));
178 // equivalent to close(file descriptor)
179 bool linux_smart_device::close()
181 int fd
= m_fd
; m_fd
= -1;
183 return set_err(errno
);
187 // examples for smartctl
188 static const char smartctl_examples
[] =
189 "=================================================== SMARTCTL EXAMPLES =====\n\n"
190 " smartctl --all /dev/hda (Prints all SMART information)\n\n"
191 " smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda\n"
192 " (Enables SMART on first disk)\n\n"
193 " smartctl --test=long /dev/hda (Executes extended disk self-test)\n\n"
194 " smartctl --attributes --log=selftest --quietmode=errorsonly /dev/hda\n"
195 " (Prints Self-Test & Attribute errors)\n"
196 " smartctl --all --device=3ware,2 /dev/sda\n"
197 " smartctl --all --device=3ware,2 /dev/twe0\n"
198 " smartctl --all --device=3ware,2 /dev/twa0\n"
199 " (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
200 " smartctl --all --device=hpt,1/1/3 /dev/sda\n"
201 " (Prints all SMART info for the SATA disk attached to the 3rd PMPort\n"
202 " of the 1st channel on the 1st HighPoint RAID controller)\n"
203 " smartctl --all --device=areca,3 /dev/sg2\n"
204 " (Prints all SMART info for 3rd ATA disk on Areca RAID controller)\n"
208 /////////////////////////////////////////////////////////////////////////////
209 /// Linux ATA support
211 class linux_ata_device
212 : public /*implements*/ ata_device_with_command_set
,
213 public /*extends*/ linux_smart_device
216 linux_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
219 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
222 linux_ata_device::linux_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
)
223 : smart_device(intf
, dev_name
, "ata", req_type
),
224 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
229 // This is an interface routine meant to isolate the OS dependent
230 // parts of the code, and to provide a debugging interface. Each
231 // different port and OS needs to provide it's own interface. This
233 // DETAILED DESCRIPTION OF ARGUMENTS
234 // device: is the file descriptor provided by open()
235 // command: defines the different operations.
236 // select: additional input data if needed (which log, which type of
238 // data: location to write output data, if needed (512 bytes).
239 // Note: not all commands use all arguments.
241 // -1 if the command failed
242 // 0 if the command succeeded,
243 // STATUS_CHECK routine:
244 // -1 if the command failed
245 // 0 if the command succeeded and disk SMART status is "OK"
246 // 1 if the command succeeded and disk SMART status is "FAILING"
249 #define BUFFER_LENGTH (4+512)
251 int linux_ata_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
253 unsigned char buff
[BUFFER_LENGTH
];
254 // positive: bytes to write to caller. negative: bytes to READ from
255 // caller. zero: non-data command
258 const int HDIO_DRIVE_CMD_OFFSET
= 4;
260 // See struct hd_drive_cmd_hdr in hdreg.h. Before calling ioctl()
261 // buff[0]: ATA COMMAND CODE REGISTER
262 // buff[1]: ATA SECTOR NUMBER REGISTER == LBA LOW REGISTER
263 // buff[2]: ATA FEATURES REGISTER
264 // buff[3]: ATA SECTOR COUNT REGISTER
266 // Note that on return:
267 // buff[2] contains the ATA SECTOR COUNT REGISTER
269 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
270 memset(buff
, 0, BUFFER_LENGTH
);
272 buff
[0]=ATA_SMART_CMD
;
274 case CHECK_POWER_MODE
:
275 buff
[0]=ATA_CHECK_POWER_MODE
;
279 buff
[2]=ATA_SMART_READ_VALUES
;
283 case READ_THRESHOLDS
:
284 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
289 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
297 buff
[0]=ATA_IDENTIFY_DEVICE
;
302 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
307 buff
[2]=ATA_SMART_ENABLE
;
311 buff
[2]=ATA_SMART_DISABLE
;
315 // this command only says if SMART is working. It could be
316 // replaced with STATUS_CHECK below.
317 buff
[2]=ATA_SMART_STATUS
;
320 // NOTE: According to ATAPI 4 and UP, this command is obsolete
321 // select == 241 for enable but no data transfer. Use TASK ioctl.
322 buff
[1]=ATA_SMART_AUTO_OFFLINE
;
326 // select == 248 for enable but no data transfer. Use TASK ioctl.
327 buff
[1]=ATA_SMART_AUTOSAVE
;
330 case IMMEDIATE_OFFLINE
:
331 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
335 // This command uses HDIO_DRIVE_TASK and has different syntax than
336 // the other commands.
337 buff
[1]=ATA_SMART_STATUS
;
340 pout("Unrecognized command %d in linux_ata_command_interface()\n"
341 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
346 // This command uses the HDIO_DRIVE_TASKFILE ioctl(). This is the
347 // only ioctl() that can be used to WRITE data to the disk.
348 if (command
==WRITE_LOG
) {
349 unsigned char task
[sizeof(ide_task_request_t
)+512];
350 ide_task_request_t
*reqtask
=(ide_task_request_t
*) task
;
351 task_struct_t
*taskfile
=(task_struct_t
*) reqtask
->io_ports
;
354 memset(task
, 0, sizeof(task
));
357 taskfile
->feature
= ATA_SMART_WRITE_LOG_SECTOR
;
358 taskfile
->sector_count
= 1;
359 taskfile
->sector_number
= select
;
360 taskfile
->low_cylinder
= 0x4f;
361 taskfile
->high_cylinder
= 0xc2;
362 taskfile
->device_head
= 0;
363 taskfile
->command
= ATA_SMART_CMD
;
365 reqtask
->data_phase
= TASKFILE_OUT
;
366 reqtask
->req_cmd
= IDE_DRIVE_TASK_OUT
;
367 reqtask
->out_size
= 512;
368 reqtask
->in_size
= 0;
370 // copy user data into the task request structure
371 memcpy(task
+sizeof(ide_task_request_t
), data
, 512);
373 if ((retval
=ioctl(get_fd(), HDIO_DRIVE_TASKFILE
, task
))) {
375 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
381 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
383 if (command
==STATUS_CHECK
|| command
==AUTOSAVE
|| command
==AUTO_OFFLINE
){
386 // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
387 // have to read the IDE driver source code. Sigh.
388 // buff[0]: ATA COMMAND CODE REGISTER
389 // buff[1]: ATA FEATURES REGISTER
390 // buff[2]: ATA SECTOR_COUNT
391 // buff[3]: ATA SECTOR NUMBER
392 // buff[4]: ATA CYL LO REGISTER
393 // buff[5]: ATA CYL HI REGISTER
394 // buff[6]: ATA DEVICE HEAD
396 unsigned const char normal_lo
=0x4f, normal_hi
=0xc2;
397 unsigned const char failed_lo
=0xf4, failed_hi
=0x2c;
401 if ((retval
=ioctl(get_fd(), HDIO_DRIVE_TASK
, buff
))) {
402 if (retval
==-EINVAL
) {
403 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
404 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
407 syserror("Error SMART Status command failed");
411 // Cyl low and Cyl high unchanged means "Good SMART status"
412 if (buff
[4]==normal_lo
&& buff
[5]==normal_hi
)
415 // These values mean "Bad SMART status"
416 if (buff
[4]==failed_lo
&& buff
[5]==failed_hi
)
419 // We haven't gotten output that makes sense; print out some debugging info
420 syserror("Error SMART Status command failed");
421 pout("Please get assistance from " PACKAGE_HOMEPAGE
"\n");
422 pout("Register values returned from SMART Status command are:\n");
423 pout("ST =0x%02x\n",(int)buff
[0]);
424 pout("ERR=0x%02x\n",(int)buff
[1]);
425 pout("NS =0x%02x\n",(int)buff
[2]);
426 pout("SC =0x%02x\n",(int)buff
[3]);
427 pout("CL =0x%02x\n",(int)buff
[4]);
428 pout("CH =0x%02x\n",(int)buff
[5]);
429 pout("SEL=0x%02x\n",(int)buff
[6]);
434 // Note to people doing ports to other OSes -- don't worry about
435 // this block -- you can safely ignore it. I have put it here
436 // because under linux when you do IDENTIFY DEVICE to a packet
437 // device, it generates an ugly kernel syslog error message. This
438 // is harmless but frightens users. So this block detects packet
439 // devices and make IDENTIFY DEVICE fail "nicely" without a syslog
442 // If you read only the ATA specs, it appears as if a packet device
443 // *might* respond to the IDENTIFY DEVICE command. This is
444 // misleading - it's because around the time that SFF-8020 was
445 // incorporated into the ATA-3/4 standard, the ATA authors were
446 // sloppy. See SFF-8020 and you will see that ATAPI devices have
447 // *always* had IDENTIFY PACKET DEVICE as a mandatory part of their
448 // command set, and return 'Command Aborted' to IDENTIFY DEVICE.
449 if (command
==IDENTIFY
|| command
==PIDENTIFY
){
450 unsigned short deviceid
[256];
451 // check the device identity, as seen when the system was booted
452 // or the device was FIRST registered. This will not be current
453 // if the user has subsequently changed some of the parameters. If
454 // device is a packet device, swap the command interpretations.
455 if (!ioctl(get_fd(), HDIO_GET_IDENTITY
, deviceid
) && (deviceid
[0] & 0x8000))
456 buff
[0]=(command
==IDENTIFY
)?ATA_IDENTIFY_PACKET_DEVICE
:ATA_IDENTIFY_DEVICE
;
460 // We are now doing the HDIO_DRIVE_CMD type ioctl.
461 if ((ioctl(get_fd(), HDIO_DRIVE_CMD
, buff
)))
464 // CHECK POWER MODE command returns information in the Sector Count
465 // register (buff[3]). Copy to return data buffer.
466 if (command
==CHECK_POWER_MODE
)
467 buff
[HDIO_DRIVE_CMD_OFFSET
]=buff
[2];
469 // if the command returns data then copy it back
471 memcpy(data
, buff
+HDIO_DRIVE_CMD_OFFSET
, copydata
);
476 // >>>>>> Start of general SCSI specific linux code
478 /* Linux specific code.
479 * Historically smartmontools (and smartsuite before it) used the
480 * SCSI_IOCTL_SEND_COMMAND ioctl which is available to all linux device
481 * nodes that use the SCSI subsystem. A better interface has been available
482 * via the SCSI generic (sg) driver but this involves the extra step of
483 * mapping disk devices (e.g. /dev/sda) to the corresponding sg device
484 * (e.g. /dev/sg2). In the linux kernel 2.6 series most of the facilities of
485 * the sg driver have become available via the SG_IO ioctl which is available
486 * on all SCSI devices (on SCSI tape devices from lk 2.6.6).
487 * So the strategy below is to find out if the SG_IO ioctl is available and
488 * if so use it; failing that use the older SCSI_IOCTL_SEND_COMMAND ioctl.
489 * Should work in 2.0, 2.2, 2.4 and 2.6 series linux kernels. */
491 #define MAX_DXFER_LEN 1024 /* can be increased if necessary */
492 #define SEND_IOCTL_RESP_SENSE_LEN 16 /* ioctl limitation */
493 #define SG_IO_RESP_SENSE_LEN 64 /* large enough see buffer */
494 #define LSCSI_DRIVER_MASK 0xf /* mask out "suggestions" */
495 #define LSCSI_DRIVER_SENSE 0x8 /* alternate CHECK CONDITION indication */
496 #define LSCSI_DRIVER_TIMEOUT 0x6
497 #define LSCSI_DID_TIME_OUT 0x3
498 #define LSCSI_DID_BUS_BUSY 0x2
499 #define LSCSI_DID_NO_CONNECT 0x1
501 #ifndef SCSI_IOCTL_SEND_COMMAND
502 #define SCSI_IOCTL_SEND_COMMAND 1
505 #define SG_IO_PRESENT_UNKNOWN 0
506 #define SG_IO_PRESENT_YES 1
507 #define SG_IO_PRESENT_NO 2
509 static int sg_io_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
,
511 static int sisc_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
);
513 static int sg_io_state
= SG_IO_PRESENT_UNKNOWN
;
515 /* Preferred implementation for issuing SCSI commands in linux. This
516 * function uses the SG_IO ioctl. Return 0 if command issued successfully
517 * (various status values should still be checked). If the SCSI command
518 * cannot be issued then a negative errno value is returned. */
519 static int sg_io_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
,
523 ARGUSED(dev_fd
); ARGUSED(iop
); ARGUSED(report
);
526 struct sg_io_hdr io_hdr
;
530 const unsigned char * ucp
= iop
->cmnd
;
533 const int sz
= (int)sizeof(buff
);
535 np
= scsi_get_opcode_name(ucp
[0]);
536 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
537 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
538 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
540 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
541 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
543 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
544 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
545 (trunc
? " [only first 256 bytes shown]" : ""));
546 dStrHex((const char *)iop
->dxferp
,
547 (trunc
? 256 : iop
->dxfer_len
) , 1);
550 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
553 memset(&io_hdr
, 0, sizeof(struct sg_io_hdr
));
554 io_hdr
.interface_id
= 'S';
555 io_hdr
.cmd_len
= iop
->cmnd_len
;
556 io_hdr
.mx_sb_len
= iop
->max_sense_len
;
557 io_hdr
.dxfer_len
= iop
->dxfer_len
;
558 io_hdr
.dxferp
= iop
->dxferp
;
559 io_hdr
.cmdp
= iop
->cmnd
;
560 io_hdr
.sbp
= iop
->sensep
;
561 /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
562 defaults to 60 seconds. */
563 io_hdr
.timeout
= ((0 == iop
->timeout
) ? 60 : iop
->timeout
) * 1000;
564 switch (iop
->dxfer_dir
) {
566 io_hdr
.dxfer_direction
= SG_DXFER_NONE
;
568 case DXFER_FROM_DEVICE
:
569 io_hdr
.dxfer_direction
= SG_DXFER_FROM_DEV
;
571 case DXFER_TO_DEVICE
:
572 io_hdr
.dxfer_direction
= SG_DXFER_TO_DEV
;
575 pout("do_scsi_cmnd_io: bad dxfer_dir\n");
578 iop
->resp_sense_len
= 0;
579 iop
->scsi_status
= 0;
581 if (ioctl(dev_fd
, SG_IO
, &io_hdr
) < 0) {
582 if (report
&& (! unknown
))
583 pout(" SG_IO ioctl failed, errno=%d [%s]\n", errno
,
587 iop
->resid
= io_hdr
.resid
;
588 iop
->scsi_status
= io_hdr
.status
;
590 pout(" scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
591 " info=0x%x duration=%d milliseconds resid=%d\n", io_hdr
.status
,
592 io_hdr
.host_status
, io_hdr
.driver_status
, io_hdr
.info
,
593 io_hdr
.duration
, io_hdr
.resid
);
595 if (DXFER_FROM_DEVICE
== iop
->dxfer_dir
) {
598 len
= iop
->dxfer_len
- iop
->resid
;
599 trunc
= (len
> 256) ? 1 : 0;
601 pout(" Incoming data, len=%d%s:\n", len
,
602 (trunc
? " [only first 256 bytes shown]" : ""));
603 dStrHex((const char*)iop
->dxferp
, (trunc
? 256 : len
),
606 pout(" Incoming data trimmed to nothing by resid\n");
611 if (io_hdr
.info
| SG_INFO_CHECK
) { /* error or warning */
612 int masked_driver_status
= (LSCSI_DRIVER_MASK
& io_hdr
.driver_status
);
614 if (0 != io_hdr
.host_status
) {
615 if ((LSCSI_DID_NO_CONNECT
== io_hdr
.host_status
) ||
616 (LSCSI_DID_BUS_BUSY
== io_hdr
.host_status
) ||
617 (LSCSI_DID_TIME_OUT
== io_hdr
.host_status
))
620 return -EIO
; /* catch all */
622 if (0 != masked_driver_status
) {
623 if (LSCSI_DRIVER_TIMEOUT
== masked_driver_status
)
625 else if (LSCSI_DRIVER_SENSE
!= masked_driver_status
)
628 if (LSCSI_DRIVER_SENSE
== masked_driver_status
)
629 iop
->scsi_status
= SCSI_STATUS_CHECK_CONDITION
;
630 iop
->resp_sense_len
= io_hdr
.sb_len_wr
;
631 if ((SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) &&
632 iop
->sensep
&& (iop
->resp_sense_len
> 0)) {
634 pout(" >>> Sense buffer, len=%d:\n",
635 (int)iop
->resp_sense_len
);
636 dStrHex((const char *)iop
->sensep
, iop
->resp_sense_len
, 1);
640 if (SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) {
641 if ((iop
->sensep
[0] & 0x7f) > 0x71)
642 pout(" status=%x: [desc] sense_key=%x asc=%x ascq=%x\n",
643 iop
->scsi_status
, iop
->sensep
[1] & 0xf,
644 iop
->sensep
[2], iop
->sensep
[3]);
646 pout(" status=%x: sense_key=%x asc=%x ascq=%x\n",
647 iop
->scsi_status
, iop
->sensep
[2] & 0xf,
648 iop
->sensep
[12], iop
->sensep
[13]);
651 pout(" status=0x%x\n", iop
->scsi_status
);
658 struct linux_ioctl_send_command
662 UINT8 buff
[MAX_DXFER_LEN
+ 16];
665 /* The Linux SCSI_IOCTL_SEND_COMMAND ioctl is primitive and it doesn't
666 * support: CDB length (guesses it from opcode), resid and timeout.
667 * Patches in Linux 2.4.21 and 2.5.70 to extend SEND DIAGNOSTIC timeout
668 * to 2 hours in order to allow long foreground extended self tests. */
669 static int sisc_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
)
671 struct linux_ioctl_send_command wrk
;
672 int status
, buff_offset
;
675 memcpy(wrk
.buff
, iop
->cmnd
, iop
->cmnd_len
);
676 buff_offset
= iop
->cmnd_len
;
679 const unsigned char * ucp
= iop
->cmnd
;
682 const int sz
= (int)sizeof(buff
);
684 np
= scsi_get_opcode_name(ucp
[0]);
685 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
686 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
687 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
689 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
690 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
692 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
693 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
694 (trunc
? " [only first 256 bytes shown]" : ""));
695 dStrHex((const char *)iop
->dxferp
,
696 (trunc
? 256 : iop
->dxfer_len
) , 1);
699 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
702 switch (iop
->dxfer_dir
) {
707 case DXFER_FROM_DEVICE
:
709 if (iop
->dxfer_len
> MAX_DXFER_LEN
)
711 wrk
.outbufsize
= iop
->dxfer_len
;
713 case DXFER_TO_DEVICE
:
714 if (iop
->dxfer_len
> MAX_DXFER_LEN
)
716 memcpy(wrk
.buff
+ buff_offset
, iop
->dxferp
, iop
->dxfer_len
);
717 wrk
.inbufsize
= iop
->dxfer_len
;
721 pout("do_scsi_cmnd_io: bad dxfer_dir\n");
724 iop
->resp_sense_len
= 0;
725 iop
->scsi_status
= 0;
727 status
= ioctl(dev_fd
, SCSI_IOCTL_SEND_COMMAND
, &wrk
);
730 pout(" SCSI_IOCTL_SEND_COMMAND ioctl failed, errno=%d [%s]\n",
731 errno
, strerror(errno
));
737 if (DXFER_FROM_DEVICE
== iop
->dxfer_dir
) {
738 memcpy(iop
->dxferp
, wrk
.buff
, iop
->dxfer_len
);
740 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
742 pout(" Incoming data, len=%d%s:\n", (int)iop
->dxfer_len
,
743 (trunc
? " [only first 256 bytes shown]" : ""));
744 dStrHex((const char*)iop
->dxferp
,
745 (trunc
? 256 : iop
->dxfer_len
) , 1);
750 iop
->scsi_status
= status
& 0x7e; /* bits 0 and 7 used to be for vendors */
751 if (LSCSI_DRIVER_SENSE
== ((status
>> 24) & 0xf))
752 iop
->scsi_status
= SCSI_STATUS_CHECK_CONDITION
;
753 len
= (SEND_IOCTL_RESP_SENSE_LEN
< iop
->max_sense_len
) ?
754 SEND_IOCTL_RESP_SENSE_LEN
: iop
->max_sense_len
;
755 if ((SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) &&
756 iop
->sensep
&& (len
> 0)) {
757 memcpy(iop
->sensep
, wrk
.buff
, len
);
758 iop
->resp_sense_len
= len
;
760 pout(" >>> Sense buffer, len=%d:\n", (int)len
);
761 dStrHex((const char *)wrk
.buff
, len
, 1);
765 if (SCSI_STATUS_CHECK_CONDITION
== iop
->scsi_status
) {
766 pout(" status=%x: sense_key=%x asc=%x ascq=%x\n", status
& 0xff,
767 wrk
.buff
[2] & 0xf, wrk
.buff
[12], wrk
.buff
[13]);
770 pout(" status=0x%x\n", status
);
772 if (iop
->scsi_status
> 0)
776 pout(" ioctl status=0x%x but scsi status=0, fail with EIO\n",
778 return -EIO
; /* give up, assume no device there */
782 /* SCSI command transmission interface function, linux version.
783 * Returns 0 if SCSI command successfully launched and response
784 * received. Even when 0 is returned the caller should check
785 * scsi_cmnd_io::scsi_status for SCSI defined errors and warnings
786 * (e.g. CHECK CONDITION). If the SCSI command could not be issued
787 * (e.g. device not present or timeout) or some other problem
788 * (e.g. timeout) then returns a negative errno value */
789 static int do_normal_scsi_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
,
794 /* implementation relies on static sg_io_state variable. If not
795 * previously set tries the SG_IO ioctl. If that succeeds assume
796 * that SG_IO ioctl functional. If it fails with an errno value
797 * other than ENODEV (no device) or permission then assume
798 * SCSI_IOCTL_SEND_COMMAND is the only option. */
799 switch (sg_io_state
) {
800 case SG_IO_PRESENT_UNKNOWN
:
801 /* ignore report argument */
802 if (0 == (res
= sg_io_cmnd_io(dev_fd
, iop
, report
, 1))) {
803 sg_io_state
= SG_IO_PRESENT_YES
;
805 } else if ((-ENODEV
== res
) || (-EACCES
== res
) || (-EPERM
== res
))
806 return res
; /* wait until we see a device */
807 sg_io_state
= SG_IO_PRESENT_NO
;
808 /* drop through by design */
809 case SG_IO_PRESENT_NO
:
810 return sisc_cmnd_io(dev_fd
, iop
, report
);
811 case SG_IO_PRESENT_YES
:
812 return sg_io_cmnd_io(dev_fd
, iop
, report
, 0);
814 pout(">>>> do_scsi_cmnd_io: bad sg_io_state=%d\n", sg_io_state
);
815 sg_io_state
= SG_IO_PRESENT_UNKNOWN
;
816 return -EIO
; /* report error and reset state */
820 // >>>>>> End of general SCSI specific linux code
822 /////////////////////////////////////////////////////////////////////////////
823 /// Standard SCSI support
825 class linux_scsi_device
826 : public /*implements*/ scsi_device
,
827 public /*extends*/ linux_smart_device
830 linux_scsi_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
832 virtual smart_device
* autodetect_open();
834 virtual bool scsi_pass_through(scsi_cmnd_io
* iop
);
837 linux_scsi_device::linux_scsi_device(smart_interface
* intf
,
838 const char * dev_name
, const char * req_type
)
839 : smart_device(intf
, dev_name
, "scsi", req_type
),
840 linux_smart_device(O_RDWR
| O_NONBLOCK
, O_RDONLY
| O_NONBLOCK
)
845 bool linux_scsi_device::scsi_pass_through(scsi_cmnd_io
* iop
)
847 int status
= do_normal_scsi_cmnd_io(get_fd(), iop
, con
->reportscsiioctl
);
849 return set_err(-status
);
853 /////////////////////////////////////////////////////////////////////////////
854 /// LSI MegaRAID support
856 class linux_megaraid_device
857 : public /* implements */ scsi_device
,
858 public /* extends */ linux_smart_device
861 linux_megaraid_device(smart_interface
*intf
, const char *name
,
862 unsigned int bus
, unsigned int tgt
);
864 virtual ~linux_megaraid_device() throw();
866 virtual smart_device
* autodetect_open();
869 virtual bool close();
871 virtual bool scsi_pass_through(scsi_cmnd_io
*iop
);
874 unsigned int m_disknum
;
875 unsigned int m_busnum
;
879 bool (linux_megaraid_device::*pt_cmd
)(int cdblen
, void *cdb
, int dataLen
, void *data
,
880 int senseLen
, void *sense
, int report
);
881 bool megasas_cmd(int cdbLen
, void *cdb
, int dataLen
, void *data
,
882 int senseLen
, void *sense
, int report
);
883 bool megadev_cmd(int cdbLen
, void *cdb
, int dataLen
, void *data
,
884 int senseLen
, void *sense
, int report
);
887 linux_megaraid_device::linux_megaraid_device(smart_interface
*intf
,
888 const char *dev_name
, unsigned int bus
, unsigned int tgt
)
889 : smart_device(intf
, dev_name
, "megaraid", "megaraid"),
890 linux_smart_device(O_RDWR
| O_NONBLOCK
),
891 m_disknum(tgt
), m_busnum(bus
), m_hba(0),
894 set_info().info_name
= strprintf("%s [megaraid_disk_%02d]", dev_name
, m_disknum
);
897 linux_megaraid_device::~linux_megaraid_device() throw()
903 smart_device
* linux_megaraid_device::autodetect_open()
909 // The code below is based on smartd.cpp:SCSIFilterKnown()
910 if (strcmp(get_req_type(), "megaraid"))
914 unsigned char req_buff
[64] = {0, };
916 if (scsiStdInquiry(this, req_buff
, req_len
)) {
918 set_err(EIO
, "INQUIRY failed");
922 int avail_len
= req_buff
[4] + 5;
923 int len
= (avail_len
< req_len
? avail_len
: req_len
);
927 printf("Got MegaRAID inquiry.. %s\n", req_buff
+8);
929 // Use INQUIRY to detect type
930 smart_device
* newdev
= 0;
933 newdev
= smi()->autodetect_sat_device(this, req_buff
, len
);
935 // NOTE: 'this' is now owned by '*newdev'
939 // Cleanup if exception occurs after newdev was allocated
944 // Nothing special found
949 bool linux_megaraid_device::open()
955 if (!linux_smart_device::open())
959 struct sg_scsi_id sgid
;
960 if (ioctl(get_fd(), SG_GET_SCSI_ID
, &sgid
) == 0) {
961 m_hba
= sgid
.host_no
;
963 else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER
, &m_hba
) != 0) {
965 linux_smart_device::close();
966 return set_err(err
, "can't get hba");
969 /* Perform mknod of device ioctl node */
970 fp
= fopen("/proc/devices", "r");
971 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
973 if (sscanf(line
, "%d megaraid_sas_ioctl%n", &mjr
, &n1
) == 1 && n1
== 22) {
974 n1
=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR
, makedev(mjr
, 0));
975 printf("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1
>= 0 ? 0 : errno
);
976 if (n1
>= 0 || errno
== EEXIST
)
979 else if (sscanf(line
, "%d megadev%n", &mjr
, &n1
) == 1 && n1
== 11) {
980 n1
=mknod("/dev/megadev0", S_IFCHR
, makedev(mjr
, 0));
981 printf("Creating /dev/megadev0 = %d\n", n1
>= 0 ? 0 : errno
);
982 if (n1
>= 0 || errno
== EEXIST
)
988 /* Open Device IOCTL node */
989 if ((m_fd
= ::open("/dev/megaraid_sas_ioctl_node", O_RDWR
)) >= 0) {
990 pt_cmd
= &linux_megaraid_device::megasas_cmd
;
992 else if ((m_fd
= ::open("/dev/megadev0", O_RDWR
)) >= 0) {
993 pt_cmd
= &linux_megaraid_device::megadev_cmd
;
997 linux_smart_device::close();
998 return set_err(err
, "cannot open /dev/megaraid_sas_ioctl_node or /dev/megadev0");
1004 bool linux_megaraid_device::close()
1008 m_fd
= -1; m_hba
= 0; pt_cmd
= 0;
1009 return linux_smart_device::close();
1012 bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io
*iop
)
1014 int report
= con
->reportscsiioctl
;
1018 const unsigned char * ucp
= iop
->cmnd
;
1021 const int sz
= (int)sizeof(buff
);
1023 np
= scsi_get_opcode_name(ucp
[0]);
1024 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
1025 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
1026 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
1028 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
1029 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
1031 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
1032 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
1033 (trunc
? " [only first 256 bytes shown]" : ""));
1034 dStrHex((const char *)iop
->dxferp
,
1035 (trunc
? 256 : iop
->dxfer_len
) , 1);
1038 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
1042 /* Controller rejects Enable SMART and Test Unit Ready */
1043 if (iop
->cmnd
[0] == 0x00)
1045 if (iop
->cmnd
[0] == 0x85 && iop
->cmnd
[1] == 0x06) {
1046 pout("Rejecting SMART/ATA command to controller\n");
1052 return (this->*pt_cmd
)(iop
->cmnd_len
, iop
->cmnd
,
1053 iop
->dxfer_len
, iop
->dxferp
,
1054 iop
->max_sense_len
, iop
->sensep
, report
);
1057 /* Issue passthrough scsi command to PERC5/6 controllers */
1058 bool linux_megaraid_device::megasas_cmd(int cdbLen
, void *cdb
,
1059 int dataLen
, void *data
,
1060 int /*senseLen*/, void * /*sense*/, int /*report*/)
1062 struct megasas_pthru_frame
*pthru
;
1063 struct megasas_iocpacket uio
;
1066 memset(&uio
, 0, sizeof(uio
));
1067 pthru
= (struct megasas_pthru_frame
*)uio
.frame
.raw
;
1068 pthru
->cmd
= MFI_CMD_PD_SCSI_IO
;
1069 pthru
->cmd_status
= 0xFF;
1070 pthru
->scsi_status
= 0x0;
1071 pthru
->target_id
= m_disknum
;
1073 pthru
->cdb_len
= cdbLen
;
1075 pthru
->flags
= MFI_FRAME_DIR_READ
;
1076 pthru
->sge_count
= 1;
1077 pthru
->data_xfer_len
= dataLen
;
1078 pthru
->sgl
.sge32
[0].phys_addr
= (intptr_t)data
;
1079 pthru
->sgl
.sge32
[0].length
= (uint32_t)dataLen
;
1080 memcpy(pthru
->cdb
, cdb
, cdbLen
);
1082 uio
.host_no
= m_hba
;
1084 uio
.sgl_off
= offsetof(struct megasas_pthru_frame
, sgl
);
1085 uio
.sgl
[0].iov_base
= data
;
1086 uio
.sgl
[0].iov_len
= dataLen
;
1090 rc
= ioctl(m_fd
, MEGASAS_IOC_FIRMWARE
, &uio
);
1091 if (pthru
->cmd_status
|| rc
!= 0) {
1092 if (pthru
->cmd_status
== 12) {
1093 return set_err(EIO
, "megasas_cmd: Device %d does not exist\n", m_disknum
);
1095 return set_err((errno
? errno
: EIO
), "megasas_cmd result: %d.%d = %d/%d",
1096 m_hba
, m_disknum
, errno
,
1102 /* Issue passthrough scsi commands to PERC2/3/4 controllers */
1103 bool linux_megaraid_device::megadev_cmd(int cdbLen
, void *cdb
,
1104 int dataLen
, void *data
,
1105 int senseLen
, void *sense
, int /*report*/)
1107 struct uioctl_t uio
;
1113 /* Don't issue to the controller */
1117 memset(&uio
, 0, sizeof(uio
));
1118 uio
.inlen
= dataLen
;
1119 uio
.outlen
= dataLen
;
1121 memset(data
, 0, dataLen
);
1122 uio
.ui
.fcs
.opcode
= 0x80; // M_RD_IOCTL_CMD
1123 uio
.ui
.fcs
.adapno
= MKADAP(m_hba
);
1125 uio
.data
.pointer
= (uint8_t *)data
;
1127 uio
.mbox
.cmd
= MEGA_MBOXCMD_PASSTHRU
;
1128 uio
.mbox
.xferaddr
= (intptr_t)&uio
.pthru
;
1131 uio
.pthru
.timeout
= 2;
1132 uio
.pthru
.channel
= 0;
1133 uio
.pthru
.target
= m_disknum
;
1134 uio
.pthru
.cdblen
= cdbLen
;
1135 uio
.pthru
.reqsenselen
= MAX_REQ_SENSE_LEN
;
1136 uio
.pthru
.dataxferaddr
= (intptr_t)data
;
1137 uio
.pthru
.dataxferlen
= dataLen
;
1138 memcpy(uio
.pthru
.cdb
, cdb
, cdbLen
);
1140 rc
=ioctl(m_fd
, MEGAIOCCMD
, &uio
);
1141 if (uio
.pthru
.scsistatus
|| rc
!= 0) {
1142 return set_err((errno
? errno
: EIO
), "megadev_cmd result: %d.%d = %d/%d",
1143 m_hba
, m_disknum
, errno
,
1144 uio
.pthru
.scsistatus
);
1149 /////////////////////////////////////////////////////////////////////////////
1150 /// CCISS RAID support
1152 #ifdef HAVE_LINUX_CCISS_IOCTL_H
1154 class linux_cciss_device
1155 : public /*implements*/ scsi_device
,
1156 public /*extends*/ linux_smart_device
1159 linux_cciss_device(smart_interface
* intf
, const char * name
, unsigned char disknum
);
1161 virtual bool scsi_pass_through(scsi_cmnd_io
* iop
);
1164 unsigned char m_disknum
; ///< Disk number.
1167 linux_cciss_device::linux_cciss_device(smart_interface
* intf
,
1168 const char * dev_name
, unsigned char disknum
)
1169 : smart_device(intf
, dev_name
, "cciss", "cciss"),
1170 linux_smart_device(O_RDWR
| O_NONBLOCK
),
1173 set_info().info_name
= strprintf("%s [cciss_disk_%02d]", dev_name
, disknum
);
1176 bool linux_cciss_device::scsi_pass_through(scsi_cmnd_io
* iop
)
1178 int status
= cciss_io_interface(get_fd(), m_disknum
, iop
, con
->reportscsiioctl
);
1180 return set_err(-status
);
1184 #endif // HAVE_LINUX_CCISS_IOCTL_H
1186 /////////////////////////////////////////////////////////////////////////////
1187 /// AMCC/3ware RAID support
1189 class linux_escalade_device
1190 : public /*implements*/ ata_device
,
1191 public /*extends*/ linux_smart_device
1194 enum escalade_type_t
{
1196 AMCC_3WARE_678K_CHAR
,
1197 AMCC_3WARE_9000_CHAR
1200 linux_escalade_device(smart_interface
* intf
, const char * dev_name
,
1201 escalade_type_t escalade_type
, int disknum
);
1203 virtual bool open();
1205 virtual bool ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
);
1208 escalade_type_t m_escalade_type
; ///< Controller type
1209 int m_disknum
; ///< Disk number.
1212 linux_escalade_device::linux_escalade_device(smart_interface
* intf
, const char * dev_name
,
1213 escalade_type_t escalade_type
, int disknum
)
1214 : smart_device(intf
, dev_name
, "3ware", "3ware"),
1215 linux_smart_device(O_RDONLY
| O_NONBLOCK
),
1216 m_escalade_type(escalade_type
), m_disknum(disknum
)
1218 set_info().info_name
= strprintf("%s [3ware_disk_%02d]", dev_name
, disknum
);
1221 /* This function will setup and fix device nodes for a 3ware controller. */
1222 #define MAJOR_STRING_LENGTH 3
1223 #define DEVICE_STRING_LENGTH 32
1224 #define NODE_STRING_LENGTH 16
1225 int setup_3ware_nodes(const char *nodename
, const char *driver_name
) {
1228 char majorstring
[MAJOR_STRING_LENGTH
+1];
1229 char device_name
[DEVICE_STRING_LENGTH
+1];
1230 char nodestring
[NODE_STRING_LENGTH
];
1231 struct stat stat_buf
;
1235 security_context_t orig_context
= NULL
;
1236 security_context_t node_context
= NULL
;
1237 int selinux_enabled
= is_selinux_enabled();
1238 int selinux_enforced
= security_getenforce();
1242 /* First try to open up /proc/devices */
1243 if (!(file
= fopen("/proc/devices", "r"))) {
1244 pout("Error opening /proc/devices to check/create 3ware device nodes\n");
1246 return 0; // don't fail here: user might not have /proc !
1249 /* Attempt to get device major number */
1250 while (EOF
!= fscanf(file
, "%3s %32s", majorstring
, device_name
)) {
1251 majorstring
[MAJOR_STRING_LENGTH
]='\0';
1252 device_name
[DEVICE_STRING_LENGTH
]='\0';
1253 if (!strncmp(device_name
, nodename
, DEVICE_STRING_LENGTH
)) {
1254 tw_major
= atoi(majorstring
);
1260 /* See if we found a major device number */
1262 pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename
, driver_name
);
1266 /* Prepare a database of contexts for files in /dev
1267 * and save the current context */
1268 if (selinux_enabled
) {
1269 if (matchpathcon_init_prefix(NULL
, "/dev") < 0)
1270 pout("Error initializing contexts database for /dev");
1271 if (getfscreatecon(&orig_context
) < 0) {
1272 pout("Error retrieving original SELinux fscreate context");
1273 if (selinux_enforced
)
1274 matchpathcon_fini();
1279 /* Now check if nodes are correct */
1280 for (index
=0; index
<16; index
++) {
1281 sprintf(nodestring
, "/dev/%s%d", nodename
, index
);
1283 /* Get context of the node and set it as the default */
1284 if (selinux_enabled
) {
1285 if (matchpathcon(nodestring
, S_IRUSR
| S_IWUSR
, &node_context
) < 0) {
1286 pout("Could not retrieve context for %s", nodestring
);
1287 if (selinux_enforced
) {
1292 if (setfscreatecon(node_context
) < 0) {
1293 pout ("Error setting default fscreate context");
1294 if (selinux_enforced
) {
1301 /* Try to stat the node */
1302 if ((stat(nodestring
, &stat_buf
))) {
1303 pout("Node %s does not exist and must be created. Check the udev rules.\n", nodestring
);
1304 /* Create a new node if it doesn't exist */
1305 if (mknod(nodestring
, S_IFCHR
|0600, makedev(tw_major
, index
))) {
1306 pout("problem creating 3ware device nodes %s", nodestring
);
1312 if (selinux_enabled
&& node_context
) {
1313 freecon(node_context
);
1314 node_context
= NULL
;
1321 /* See if nodes major and minor numbers are correct */
1322 if ((tw_major
!= (int)(major(stat_buf
.st_rdev
))) ||
1323 (index
!= (int)(minor(stat_buf
.st_rdev
))) ||
1324 (!S_ISCHR(stat_buf
.st_mode
))) {
1325 pout("Node %s has wrong major/minor number and must be created anew."
1326 " Check the udev rules.\n", nodestring
);
1327 /* Delete the old node */
1328 if (unlink(nodestring
)) {
1329 pout("problem unlinking stale 3ware device node %s", nodestring
);
1335 /* Make a new node */
1336 if (mknod(nodestring
, S_IFCHR
|0600, makedev(tw_major
, index
))) {
1337 pout("problem creating 3ware device nodes %s", nodestring
);
1344 if (selinux_enabled
&& node_context
) {
1345 freecon(node_context
);
1346 node_context
= NULL
;
1352 if (selinux_enabled
) {
1353 if(setfscreatecon(orig_context
) < 0) {
1354 pout("Error re-setting original fscreate context");
1355 if (selinux_enforced
)
1359 freecon(orig_context
);
1361 freecon(node_context
);
1362 matchpathcon_fini();
1368 bool linux_escalade_device::open()
1370 if (m_escalade_type
== AMCC_3WARE_9000_CHAR
|| m_escalade_type
== AMCC_3WARE_678K_CHAR
) {
1371 // the device nodes for these controllers are dynamically assigned,
1372 // so we need to check that they exist with the correct major
1373 // numbers and if not, create them
1374 const char * node
= (m_escalade_type
== AMCC_3WARE_9000_CHAR
? "twa" : "twe" );
1375 const char * driver
= (m_escalade_type
== AMCC_3WARE_9000_CHAR
? "3w-9xxx": "3w-xxxx");
1376 if (setup_3ware_nodes(node
, driver
))
1377 return set_err((errno
? errno
: ENXIO
), "setup_3ware_nodes(\"%s\", \"%s\") failed", node
, driver
);
1379 // Continue with default open
1380 return linux_smart_device::open();
1383 // TODO: Function no longer useful
1384 //void printwarning(smart_command_set command);
1387 // This is an interface routine meant to isolate the OS dependent
1388 // parts of the code, and to provide a debugging interface. Each
1389 // different port and OS needs to provide it's own interface. This
1390 // is the linux interface to the 3ware 3w-xxxx driver. It allows ATA
1391 // commands to be passed through the SCSI driver.
1392 // DETAILED DESCRIPTION OF ARGUMENTS
1393 // fd: is the file descriptor provided by open()
1394 // disknum is the disk number (0 to 15) in the RAID array
1395 // escalade_type indicates the type of controller type, and if scsi or char interface is used
1396 // command: defines the different operations.
1397 // select: additional input data if needed (which log, which type of
1399 // data: location to write output data, if needed (512 bytes).
1400 // Note: not all commands use all arguments.
1402 // -1 if the command failed
1403 // 0 if the command succeeded,
1404 // STATUS_CHECK routine:
1405 // -1 if the command failed
1406 // 0 if the command succeeded and disk SMART status is "OK"
1407 // 1 if the command succeeded and disk SMART status is "FAILING"
1410 /* 512 is the max payload size: increase if needed */
1411 #define BUFFER_LEN_678K ( sizeof(TW_Ioctl) ) // 1044 unpacked, 1041 packed
1412 #define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1 ) // 1539 unpacked, 1536 packed
1413 #define BUFFER_LEN_9000 ( sizeof(TW_Ioctl_Buf_Apache)+512-1 ) // 2051 unpacked, 2048 packed
1414 #define TW_IOCTL_BUFFER_SIZE ( MAX(MAX(BUFFER_LEN_678K, BUFFER_LEN_9000), BUFFER_LEN_678K_CHAR) )
1416 bool linux_escalade_device::ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
)
1418 if (!ata_cmd_is_ok(in
,
1419 true, // data_out_support
1420 false, // TODO: multi_sector_support
1421 true) // ata_48bit_support
1425 // Used by both the SCSI and char interfaces
1426 TW_Passthru
*passthru
=NULL
;
1427 char ioctl_buffer
[TW_IOCTL_BUFFER_SIZE
];
1429 // only used for SCSI device interface
1430 TW_Ioctl
*tw_ioctl
=NULL
;
1431 TW_Output
*tw_output
=NULL
;
1433 // only used for 6000/7000/8000 char device interface
1434 TW_New_Ioctl
*tw_ioctl_char
=NULL
;
1436 // only used for 9000 character device interface
1437 TW_Ioctl_Buf_Apache
*tw_ioctl_apache
=NULL
;
1439 memset(ioctl_buffer
, 0, TW_IOCTL_BUFFER_SIZE
);
1441 // TODO: Handle controller differences by different classes
1442 if (m_escalade_type
==AMCC_3WARE_9000_CHAR
) {
1443 tw_ioctl_apache
= (TW_Ioctl_Buf_Apache
*)ioctl_buffer
;
1444 tw_ioctl_apache
->driver_command
.control_code
= TW_IOCTL_FIRMWARE_PASS_THROUGH
;
1445 tw_ioctl_apache
->driver_command
.buffer_length
= 512; /* payload size */
1446 passthru
= (TW_Passthru
*)&(tw_ioctl_apache
->firmware_command
.command
.oldcommand
);
1448 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
) {
1449 tw_ioctl_char
= (TW_New_Ioctl
*)ioctl_buffer
;
1450 tw_ioctl_char
->data_buffer_length
= 512;
1451 passthru
= (TW_Passthru
*)&(tw_ioctl_char
->firmware_command
);
1453 else if (m_escalade_type
==AMCC_3WARE_678K
) {
1454 tw_ioctl
= (TW_Ioctl
*)ioctl_buffer
;
1455 tw_ioctl
->cdb
[0] = TW_IOCTL
;
1456 tw_ioctl
->opcode
= TW_ATA_PASSTHRU
;
1457 tw_ioctl
->input_length
= 512; // correct even for non-data commands
1458 tw_ioctl
->output_length
= 512; // correct even for non-data commands
1459 tw_output
= (TW_Output
*)tw_ioctl
;
1460 passthru
= (TW_Passthru
*)&(tw_ioctl
->input_data
);
1463 return set_err(ENOSYS
,
1464 "Unrecognized escalade_type %d in linux_3ware_command_interface(disk %d)\n"
1465 "Please contact " PACKAGE_BUGREPORT
"\n", (int)m_escalade_type
, m_disknum
);
1468 // Same for (almost) all commands - but some reset below
1469 passthru
->byte0
.opcode
= TW_OP_ATA_PASSTHRU
;
1470 passthru
->request_id
= 0xFF;
1471 passthru
->unit
= m_disknum
;
1472 passthru
->status
= 0;
1473 passthru
->flags
= 0x1;
1477 const ata_in_regs_48bit
& r
= in
.in_regs
;
1478 passthru
->features
= r
.features_16
;
1479 passthru
->sector_count
= r
.sector_count_16
;
1480 passthru
->sector_num
= r
.lba_low_16
;
1481 passthru
->cylinder_lo
= r
.lba_mid_16
;
1482 passthru
->cylinder_hi
= r
.lba_high_16
;
1483 passthru
->drive_head
= r
.device
;
1484 passthru
->command
= r
.command
;
1487 // Is this a command that reads or returns 512 bytes?
1488 // passthru->param values are:
1489 // 0x0 - non data command without TFR write check,
1490 // 0x8 - non data command with TFR write check,
1491 // 0xD - data command that returns data to host from device
1492 // 0xF - data command that writes data from host to device
1493 // passthru->size values are 0x5 for non-data and 0x07 for data
1494 bool readdata
= false;
1495 if (in
.direction
== ata_cmd_in::data_in
) {
1497 passthru
->byte0
.sgloff
= 0x5;
1498 passthru
->size
= 0x7; // TODO: Other value for multi-sector ?
1499 passthru
->param
= 0xD;
1500 // For 64-bit to work correctly, up the size of the command packet
1501 // in dwords by 1 to account for the 64-bit single sgl 'address'
1502 // field. Note that this doesn't agree with the typedefs but it's
1503 // right (agree with kernel driver behavior/typedefs).
1504 if (m_escalade_type
==AMCC_3WARE_9000_CHAR
&& sizeof(long)==8)
1507 else if (in
.direction
== ata_cmd_in::no_data
) {
1508 // Non data command -- but doesn't use large sector
1509 // count register values.
1510 passthru
->byte0
.sgloff
= 0x0;
1511 passthru
->size
= 0x5;
1512 passthru
->param
= 0x8;
1513 passthru
->sector_count
= 0x0;
1515 else if (in
.direction
== ata_cmd_in::data_out
) {
1516 if (m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1517 memcpy(tw_ioctl_apache
->data_buffer
, in
.buffer
, in
.size
);
1518 else if (m_escalade_type
== AMCC_3WARE_678K_CHAR
)
1519 memcpy(tw_ioctl_char
->data_buffer
, in
.buffer
, in
.size
);
1521 // COMMAND NOT SUPPORTED VIA SCSI IOCTL INTERFACE
1522 // memcpy(tw_output->output_data, data, 512);
1523 // printwarning(command); // TODO: Parameter no longer valid
1524 return set_err(ENOTSUP
, "DATA OUT not supported for this 3ware controller type");
1526 passthru
->byte0
.sgloff
= 0x5;
1527 passthru
->size
= 0x7; // TODO: Other value for multi-sector ?
1528 passthru
->param
= 0xF; // PIO data write
1529 if (m_escalade_type
==AMCC_3WARE_9000_CHAR
&& sizeof(long)==8)
1535 // Now send the command down through an ioctl()
1537 if (m_escalade_type
==AMCC_3WARE_9000_CHAR
)
1538 ioctlreturn
=ioctl(get_fd(), TW_IOCTL_FIRMWARE_PASS_THROUGH
, tw_ioctl_apache
);
1539 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
)
1540 ioctlreturn
=ioctl(get_fd(), TW_CMD_PACKET_WITH_DATA
, tw_ioctl_char
);
1542 ioctlreturn
=ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND
, tw_ioctl
);
1544 // Deal with the different error cases
1546 if (AMCC_3WARE_678K
==m_escalade_type
1547 && in
.in_regs
.command
==ATA_SMART_CMD
1548 && ( in
.in_regs
.features
== ATA_SMART_AUTO_OFFLINE
1549 || in
.in_regs
.features
== ATA_SMART_AUTOSAVE
)
1550 && in
.in_regs
.lba_low
) {
1551 // error here is probably a kernel driver whose version is too old
1552 // printwarning(command); // TODO: Parameter no longer valid
1553 return set_err(ENOTSUP
, "Probably kernel driver too old");
1555 return set_err(EIO
);
1558 // The passthru structure is valid after return from an ioctl if:
1559 // - we are using the character interface OR
1560 // - we are using the SCSI interface and this is a NON-READ-DATA command
1561 // For SCSI interface, note that we set passthru to a different
1562 // value after ioctl().
1563 if (AMCC_3WARE_678K
==m_escalade_type
) {
1567 passthru
=(TW_Passthru
*)&(tw_output
->output_data
);
1570 // See if the ATA command failed. Now that we have returned from
1571 // the ioctl() call, if passthru is valid, then:
1572 // - passthru->status contains the 3ware controller STATUS
1573 // - passthru->command contains the ATA STATUS register
1574 // - passthru->features contains the ATA ERROR register
1576 // Check bits 0 (error bit) and 5 (device fault) of the ATA STATUS
1577 // If bit 0 (error bit) is set, then ATA ERROR register is valid.
1578 // While we *might* decode the ATA ERROR register, at the moment it
1579 // doesn't make much sense: we don't care in detail why the error
1582 if (passthru
&& (passthru
->status
|| (passthru
->command
& 0x21))) {
1583 return set_err(EIO
);
1586 // If this is a read data command, copy data to output buffer
1588 if (m_escalade_type
==AMCC_3WARE_9000_CHAR
)
1589 memcpy(in
.buffer
, tw_ioctl_apache
->data_buffer
, in
.size
);
1590 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
)
1591 memcpy(in
.buffer
, tw_ioctl_char
->data_buffer
, in
.size
);
1593 memcpy(in
.buffer
, tw_output
->output_data
, in
.size
);
1596 // Return register values
1598 ata_out_regs_48bit
& r
= out
.out_regs
;
1599 r
.error
= passthru
->features
;
1600 r
.sector_count_16
= passthru
->sector_count
;
1601 r
.lba_low_16
= passthru
->sector_num
;
1602 r
.lba_mid_16
= passthru
->cylinder_lo
;
1603 r
.lba_high_16
= passthru
->cylinder_hi
;
1604 r
.device
= passthru
->drive_head
;
1605 r
.status
= passthru
->command
;
1608 // look for nonexistent devices/ports
1609 if ( in
.in_regs
.command
== ATA_IDENTIFY_DEVICE
1610 && !nonempty((unsigned char *)in
.buffer
, in
.size
)) {
1611 return set_err(ENODEV
, "No drive on port %d", m_disknum
);
1618 /////////////////////////////////////////////////////////////////////////////
1619 /// Areca RAID support
1621 class linux_areca_device
1622 : public /*implements*/ ata_device_with_command_set
,
1623 public /*extends*/ linux_smart_device
1626 linux_areca_device(smart_interface
* intf
, const char * dev_name
, int disknum
);
1629 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
1632 int m_disknum
; ///< Disk number.
1637 // This is an interface routine meant to isolate the OS dependent
1638 // parts of the code, and to provide a debugging interface. Each
1639 // different port and OS needs to provide it's own interface. This
1640 // is the linux interface to the Areca "arcmsr" driver. It allows ATA
1641 // commands to be passed through the SCSI driver.
1642 // DETAILED DESCRIPTION OF ARGUMENTS
1643 // fd: is the file descriptor provided by open()
1644 // disknum is the disk number (0 to 15) in the RAID array
1645 // command: defines the different operations.
1646 // select: additional input data if needed (which log, which type of
1648 // data: location to write output data, if needed (512 bytes).
1649 // Note: not all commands use all arguments.
1651 // -1 if the command failed
1652 // 0 if the command succeeded,
1653 // STATUS_CHECK routine:
1654 // -1 if the command failed
1655 // 0 if the command succeeded and disk SMART status is "OK"
1656 // 1 if the command succeeded and disk SMART status is "FAILING"
1660 #define ARECA_SATA_RAID 0x90000000
1662 #define FUNCTION_READ_RQBUFFER 0x0801
1663 #define FUNCTION_WRITE_WQBUFFER 0x0802
1664 #define FUNCTION_CLEAR_RQBUFFER 0x0803
1665 #define FUNCTION_CLEAR_WQBUFFER 0x0804
1667 /* ARECA IO CONTROL CODE*/
1668 #define ARCMSR_IOCTL_READ_RQBUFFER (ARECA_SATA_RAID | FUNCTION_READ_RQBUFFER)
1669 #define ARCMSR_IOCTL_WRITE_WQBUFFER (ARECA_SATA_RAID | FUNCTION_WRITE_WQBUFFER)
1670 #define ARCMSR_IOCTL_CLEAR_RQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_RQBUFFER)
1671 #define ARCMSR_IOCTL_CLEAR_WQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_WQBUFFER)
1672 #define ARECA_SIG_STR "ARCMSR"
1674 // The SRB_IO_CONTROL & SRB_BUFFER structures are used to communicate(to/from) to areca driver
1675 typedef struct _SRB_IO_CONTROL
1677 unsigned int HeaderLength
;
1678 unsigned char Signature
[8];
1679 unsigned int Timeout
;
1680 unsigned int ControlCode
;
1681 unsigned int ReturnCode
;
1682 unsigned int Length
;
1685 typedef struct _SRB_BUFFER
1687 sSRB_IO_CONTROL srbioctl
;
1688 unsigned char ioctldatabuffer
[1032]; // the buffer to put the command data to/from firmware
1691 // Looks in /proc/scsi to suggest correct areca devices
1692 // If hint not NULL, return device path guess
1693 int find_areca_in_proc(char *hint
) {
1695 const char* proc_format_string
="host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n";
1697 // check data formwat
1698 FILE *fp
=fopen("/proc/scsi/sg/device_hdr", "r");
1700 pout("Unable to open /proc/scsi/sg/device_hdr for reading\n");
1704 // get line, compare to format
1707 char *out
= fgets(linebuf
, 256, fp
);
1710 pout("Unable to read contents of /proc/scsi/sg/device_hdr\n");
1714 if (strcmp(linebuf
, proc_format_string
)) {
1716 // Fix this by comparing only tokens not white space!!
1717 pout("Unexpected format %s in /proc/scsi/sg/device_hdr\n", proc_format_string
);
1721 // Format is understood, now search for correct device
1722 fp
=fopen("/proc/scsi/sg/devices", "r");
1724 int host
, chan
, id
, lun
, type
, opens
, qdepth
, busy
, online
;
1727 // search all lines of /proc/scsi/sg/devices
1728 while (9 == fscanf(fp
, "%d %d %d %d %d %d %d %d %d", &host
, &chan
, &id
, &lun
, &type
, &opens
, &qdepth
, &busy
, &online
)) {
1730 if (id
== 16 && type
== 3) {
1731 // devices with id=16 and type=3 might be Areca controllers
1732 if (!found
&& hint
) {
1733 sprintf(hint
, "/dev/sg%d", dev
);
1735 pout("Device /dev/sg%d appears to be an Areca controller.\n", dev
);
1745 void dumpdata( unsigned char *block
, int len
)
1747 int ln
= (len
/ 16) + 1; // total line#
1751 printf(" Address = %p, Length = (0x%x)%d\n", block
, len
, len
);
1752 printf(" 0 1 2 3 4 5 6 7 8 9 A B C D E F ASCII \n");
1753 printf("=====================================================================\n");
1755 for ( int l
= 0; l
< ln
&& len
; l
++ )
1757 // printf the line# and the HEX data
1758 // if a line data length < 16 then append the space to the tail of line to reach 16 chars
1759 printf("%02X | ", l
);
1760 for ( pos
= 0; pos
< 16 && len
; pos
++, len
-- )
1762 c
= block
[l
*16+pos
];
1768 for ( int loop
= pos
; loop
< 16; loop
++ )
1775 for ( int loop
= 0; loop
< pos
; loop
++ )
1777 c
= block
[l
*16+loop
];
1778 if ( c
>= 0x20 && c
<= 0x7F )
1789 printf("=====================================================================\n");
1794 int arcmsr_command_handler(int fd
, unsigned long arcmsr_cmd
, unsigned char *data
, int data_len
, void *ext_data
/* reserved for further use */)
1798 int ioctlreturn
= 0;
1800 struct scsi_cmnd_io io_hdr
;
1801 int dir
= DXFER_TO_DEVICE
;
1806 unsigned char *areca_return_packet
;
1809 unsigned char return_buff
[2048];
1810 unsigned char *ptr
= &return_buff
[0];
1811 memset(return_buff
, 0, sizeof(return_buff
));
1813 memset((unsigned char *)&sBuf
, 0, sizeof(sBuf
));
1814 memset(&io_hdr
, 0, sizeof(io_hdr
));
1815 memset(cdb
, 0, sizeof(cdb
));
1816 memset(sense
, 0, sizeof(sense
));
1819 sBuf
.srbioctl
.HeaderLength
= sizeof(sSRB_IO_CONTROL
);
1820 memcpy(sBuf
.srbioctl
.Signature
, ARECA_SIG_STR
, strlen(ARECA_SIG_STR
));
1821 sBuf
.srbioctl
.Timeout
= 10000;
1822 sBuf
.srbioctl
.ControlCode
= ARCMSR_IOCTL_READ_RQBUFFER
;
1824 switch ( arcmsr_cmd
)
1826 // command for writing data to driver
1827 case ARCMSR_IOCTL_WRITE_WQBUFFER
:
1828 if ( data
&& data_len
)
1830 sBuf
.srbioctl
.Length
= data_len
;
1831 memcpy((unsigned char *)sBuf
.ioctldatabuffer
, (unsigned char *)data
, data_len
);
1833 // commands for clearing related buffer of driver
1834 case ARCMSR_IOCTL_CLEAR_RQBUFFER
:
1835 case ARCMSR_IOCTL_CLEAR_WQBUFFER
:
1836 cdb
[0] = 0x3B; //SCSI_WRITE_BUF command;
1838 // command for reading data from driver
1839 case ARCMSR_IOCTL_READ_RQBUFFER
:
1840 cdb
[0] = 0x3C; //SCSI_READ_BUF command;
1841 dir
= DXFER_FROM_DEVICE
;
1844 // unknown arcmsr commands
1851 // cdb[5][6][7][8] areca defined command code( to/from driver )
1853 cdb
[5] = (char)( arcmsr_cmd
>> 24);
1854 cdb
[6] = (char)( arcmsr_cmd
>> 16);
1855 cdb
[7] = (char)( arcmsr_cmd
>> 8);
1856 cdb
[8] = (char)( arcmsr_cmd
& 0x0F );
1858 io_hdr
.dxfer_dir
= dir
;
1859 io_hdr
.dxfer_len
= sizeof(sBuf
);
1860 io_hdr
.dxferp
= (unsigned char *)&sBuf
;
1862 io_hdr
.cmnd_len
= sizeof(cdb
);
1863 io_hdr
.sensep
= sense
;
1864 io_hdr
.max_sense_len
= sizeof(sense
);
1865 io_hdr
.timeout
= SCSI_TIMEOUT_DEFAULT
;
1869 ioctlreturn
= do_normal_scsi_cmnd_io(fd
, &io_hdr
, 0);
1870 if ( ioctlreturn
|| io_hdr
.scsi_status
)
1876 if ( arcmsr_cmd
!= ARCMSR_IOCTL_READ_RQBUFFER
)
1878 // if succeeded, just returns the length of outgoing data
1882 if ( sBuf
.srbioctl
.Length
)
1884 //dumpdata(&sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
1885 memcpy(ptr
, &sBuf
.ioctldatabuffer
[0], sBuf
.srbioctl
.Length
);
1886 ptr
+= sBuf
.srbioctl
.Length
;
1887 total
+= sBuf
.srbioctl
.Length
;
1888 // the returned bytes enough to compute payload length ?
1889 if ( expected
< 0 && total
>= 5 )
1891 areca_return_packet
= (unsigned char *)&return_buff
[0];
1892 if ( areca_return_packet
[0] == 0x5E &&
1893 areca_return_packet
[1] == 0x01 &&
1894 areca_return_packet
[2] == 0x61 )
1896 // valid header, let's compute the returned payload length,
1897 // we expected the total length is
1898 // payload + 3 bytes header + 2 bytes length + 1 byte checksum
1899 expected
= areca_return_packet
[4] * 256 + areca_return_packet
[3] + 6;
1903 if ( total
>= 7 && total
>= expected
)
1905 //printf("total bytes received = %d, expected length = %d\n", total, expected);
1907 // ------ Okay! we received enough --------
1913 // Deal with the different error cases
1916 printf("do_scsi_cmnd_io with write buffer failed code = %x\n", ioctlreturn
);
1921 if ( io_hdr
.scsi_status
)
1923 printf("io_hdr.scsi_status with write buffer failed code = %x\n", io_hdr
.scsi_status
);
1930 memcpy(data
, return_buff
, total
);
1937 linux_areca_device::linux_areca_device(smart_interface
* intf
, const char * dev_name
, int disknum
)
1938 : smart_device(intf
, dev_name
, "areca", "areca"),
1939 linux_smart_device(O_RDWR
| O_EXCL
| O_NONBLOCK
),
1942 set_info().info_name
= strprintf("%s [areca_%02d]", dev_name
, disknum
);
1945 // Areca RAID Controller
1946 int linux_areca_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
1948 // ATA input registers
1949 typedef struct _ATA_INPUT_REGISTERS
1951 unsigned char features
;
1952 unsigned char sector_count
;
1953 unsigned char sector_number
;
1954 unsigned char cylinder_low
;
1955 unsigned char cylinder_high
;
1956 unsigned char device_head
;
1957 unsigned char command
;
1958 unsigned char reserved
[8];
1959 unsigned char data
[512]; // [in/out] buffer for outgoing/incoming data
1960 } sATA_INPUT_REGISTERS
;
1962 // ATA output registers
1963 // Note: The output registers is re-sorted for areca internal use only
1964 typedef struct _ATA_OUTPUT_REGISTERS
1966 unsigned char error
;
1967 unsigned char status
;
1968 unsigned char sector_count
;
1969 unsigned char sector_number
;
1970 unsigned char cylinder_low
;
1971 unsigned char cylinder_high
;
1972 }sATA_OUTPUT_REGISTERS
;
1974 // Areca packet format for outgoing:
1975 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
1976 // B[3~4] : 2 bytes command length + variant data length, little endian
1977 // B[5] : 1 bytes areca defined command code, ATA passthrough command code is 0x1c
1978 // B[6~last-1] : variant bytes payload data
1979 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
1982 // header 3 bytes length 2 bytes cmd 1 byte payload data x bytes cs 1 byte
1983 // +--------------------------------------------------------------------------------+
1984 // + 0x5E 0x01 0x61 | 0x00 0x00 | 0x1c | .................... | 0x00 |
1985 // +--------------------------------------------------------------------------------+
1988 //Areca packet format for incoming:
1989 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
1990 // B[3~4] : 2 bytes payload length, little endian
1991 // B[5~last-1] : variant bytes returned payload data
1992 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
1995 // header 3 bytes length 2 bytes payload data x bytes cs 1 byte
1996 // +-------------------------------------------------------------------+
1997 // + 0x5E 0x01 0x61 | 0x00 0x00 | .................... | 0x00 |
1998 // +-------------------------------------------------------------------+
1999 unsigned char areca_packet
[640];
2000 int areca_packet_len
= sizeof(areca_packet
);
2001 unsigned char cs
= 0;
2003 sATA_INPUT_REGISTERS
*ata_cmd
;
2007 memset(sInq
, 0, sizeof(sInq
));
2008 scsiStdInquiry(fd
, (unsigned char *)sInq
, (int)sizeof(sInq
));
2009 dumpdata((unsigned char *)sInq
, sizeof(sInq
));
2011 memset(areca_packet
, 0, areca_packet_len
);
2013 // ----- BEGIN TO SETUP HEADERS -------
2014 areca_packet
[0] = 0x5E;
2015 areca_packet
[1] = 0x01;
2016 areca_packet
[2] = 0x61;
2017 areca_packet
[3] = (unsigned char)((areca_packet_len
- 6) & 0xff);
2018 areca_packet
[4] = (unsigned char)(((areca_packet_len
- 6) >> 8) & 0xff);
2019 areca_packet
[5] = 0x1c; // areca defined code for ATA passthrough command
2022 // ----- BEGIN TO SETUP PAYLOAD DATA -----
2024 memcpy(&areca_packet
[7], "SmrT", 4); // areca defined password
2026 ata_cmd
= (sATA_INPUT_REGISTERS
*)&areca_packet
[12];
2027 ata_cmd
->cylinder_low
= 0x4F;
2028 ata_cmd
->cylinder_high
= 0xC2;
2031 if ( command
== READ_VALUES
||
2032 command
== READ_THRESHOLDS
||
2033 command
== READ_LOG
||
2034 command
== IDENTIFY
||
2035 command
== PIDENTIFY
)
2037 // the commands will return data
2038 areca_packet
[6] = 0x13;
2039 ata_cmd
->sector_count
= 0x1;
2041 else if ( command
== WRITE_LOG
)
2043 // the commands will write data
2044 areca_packet
[6] = 0x14;
2048 // the commands will return no data
2049 areca_packet
[6] = 0x15;
2053 ata_cmd
->command
= ATA_SMART_CMD
;
2054 // Now set ATA registers depending upon command
2057 case CHECK_POWER_MODE
:
2058 //printf("command = CHECK_POWER_MODE\n");
2059 ata_cmd
->command
= ATA_CHECK_POWER_MODE
;
2062 //printf("command = READ_VALUES\n");
2063 ata_cmd
->features
= ATA_SMART_READ_VALUES
;
2065 case READ_THRESHOLDS
:
2066 //printf("command = READ_THRESHOLDS\n");
2067 ata_cmd
->features
= ATA_SMART_READ_THRESHOLDS
;
2070 //printf("command = READ_LOG\n");
2071 ata_cmd
->features
= ATA_SMART_READ_LOG_SECTOR
;
2072 ata_cmd
->sector_number
= select
;
2075 //printf("command = WRITE_LOG\n");
2076 ata_cmd
->features
= ATA_SMART_WRITE_LOG_SECTOR
;
2077 memcpy(ata_cmd
->data
, data
, 512);
2078 ata_cmd
->sector_count
= 1;
2079 ata_cmd
->sector_number
= select
;
2082 //printf("command = IDENTIFY\n");
2083 ata_cmd
->command
= ATA_IDENTIFY_DEVICE
;
2086 //printf("command = PIDENTIFY\n");
2090 //printf("command = ENABLE\n");
2091 ata_cmd
->features
= ATA_SMART_ENABLE
;
2094 //printf("command = DISABLE\n");
2095 ata_cmd
->features
= ATA_SMART_DISABLE
;
2098 //printf("command = AUTO_OFFLINE\n");
2099 ata_cmd
->features
= ATA_SMART_AUTO_OFFLINE
;
2100 // Enable or disable?
2101 ata_cmd
->sector_count
= select
;
2104 //printf("command = AUTOSAVE\n");
2105 ata_cmd
->features
= ATA_SMART_AUTOSAVE
;
2106 // Enable or disable?
2107 ata_cmd
->sector_count
= select
;
2109 case IMMEDIATE_OFFLINE
:
2110 //printf("command = IMMEDIATE_OFFLINE\n");
2111 ata_cmd
->features
= ATA_SMART_IMMEDIATE_OFFLINE
;
2112 // What test type to run?
2113 ata_cmd
->sector_number
= select
;
2116 //printf("command = STATUS_CHECK\n");
2117 ata_cmd
->features
= ATA_SMART_STATUS
;
2120 //printf("command = STATUS\n");
2121 ata_cmd
->features
= ATA_SMART_STATUS
;
2124 //printf("command = UNKNOWN\n");
2129 areca_packet
[11] = m_disknum
- 1; // drive number
2131 // ----- BEGIN TO SETUP CHECKSUM -----
2132 for ( int loop
= 3; loop
< areca_packet_len
- 1; loop
++ )
2134 cs
+= areca_packet
[loop
];
2136 areca_packet
[areca_packet_len
-1] = cs
;
2138 // ----- BEGIN TO SEND TO ARECA DRIVER ------
2140 unsigned char return_buff
[2048];
2141 memset(return_buff
, 0, sizeof(return_buff
));
2143 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_RQBUFFER
, NULL
, 0, NULL
);
2145 find_areca_in_proc(NULL
);
2149 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_WQBUFFER
, NULL
, 0, NULL
);
2150 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_WRITE_WQBUFFER
, areca_packet
, areca_packet_len
, NULL
);
2153 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_READ_RQBUFFER
, return_buff
, sizeof(return_buff
), NULL
);
2160 // ----- VERIFY THE CHECKSUM -----
2162 for ( int loop
= 3; loop
< expected
- 1; loop
++ )
2164 cs
+= return_buff
[loop
];
2167 if ( return_buff
[expected
- 1] != cs
)
2173 sATA_OUTPUT_REGISTERS
*ata_out
= (sATA_OUTPUT_REGISTERS
*)&return_buff
[5] ;
2174 if ( ata_out
->status
)
2176 if ( command
== IDENTIFY
)
2178 pout("The firmware of your Areca RAID controller appears to be outdated!\n" \
2179 "Please update your controller to firmware version 1.46 or later.\n" \
2180 "You may download it here: ftp://ftp.areca.com.tw/RaidCards/BIOS_Firmware\n\n");
2186 // returns with data
2187 if ( command
== READ_VALUES
||
2188 command
== READ_THRESHOLDS
||
2189 command
== READ_LOG
||
2190 command
== IDENTIFY
||
2191 command
== PIDENTIFY
)
2193 memcpy(data
, &return_buff
[7], 512);
2196 if ( command
== CHECK_POWER_MODE
)
2198 data
[0] = ata_out
->sector_count
;
2201 if ( command
== STATUS_CHECK
&&
2202 ( ata_out
->cylinder_low
== 0xF4 && ata_out
->cylinder_high
== 0x2C ) )
2211 /////////////////////////////////////////////////////////////////////////////
2214 class linux_marvell_device
2215 : public /*implements*/ ata_device_with_command_set
,
2216 public /*extends*/ linux_smart_device
2219 linux_marvell_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
2222 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2225 linux_marvell_device::linux_marvell_device(smart_interface
* intf
,
2226 const char * dev_name
, const char * req_type
)
2227 : smart_device(intf
, dev_name
, "marvell", req_type
),
2228 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
2232 int linux_marvell_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2241 mvsata_scsi_cmd smart_command
;
2242 unsigned char *buff
= (unsigned char *)&smart_command
.cmd
[6];
2243 // See struct hd_drive_cmd_hdr in hdreg.h
2244 // buff[0]: ATA COMMAND CODE REGISTER
2245 // buff[1]: ATA SECTOR NUMBER REGISTER
2246 // buff[2]: ATA FEATURES REGISTER
2247 // buff[3]: ATA SECTOR COUNT REGISTER
2249 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
2250 memset(&smart_command
, 0, sizeof(smart_command
));
2251 smart_command
.inlen
= 540;
2252 smart_command
.outlen
= 540;
2253 smart_command
.cmd
[0] = 0xC; //Vendor-specific code
2254 smart_command
.cmd
[4] = 6; //command length
2256 buff
[0] = ATA_SMART_CMD
;
2258 case CHECK_POWER_MODE
:
2259 buff
[0]=ATA_CHECK_POWER_MODE
;
2262 buff
[2]=ATA_SMART_READ_VALUES
;
2265 case READ_THRESHOLDS
:
2266 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
2267 copydata
=buff
[1]=buff
[3]=1;
2270 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
2275 buff
[0]=ATA_IDENTIFY_DEVICE
;
2279 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
2283 buff
[2]=ATA_SMART_ENABLE
;
2287 buff
[2]=ATA_SMART_DISABLE
;
2292 // this command only says if SMART is working. It could be
2293 // replaced with STATUS_CHECK below.
2294 buff
[2] = ATA_SMART_STATUS
;
2297 buff
[2]=ATA_SMART_AUTO_OFFLINE
;
2298 buff
[3]=select
; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2301 buff
[2]=ATA_SMART_AUTOSAVE
;
2302 buff
[3]=select
; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2304 case IMMEDIATE_OFFLINE
:
2305 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
2309 pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command
);
2313 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
2315 // We are now doing the HDIO_DRIVE_CMD type ioctl.
2316 if (ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND
, (void *)&smart_command
))
2319 if (command
==CHECK_POWER_MODE
) {
2320 // LEON -- CHECK THIS PLEASE. THIS SHOULD BE THE SECTOR COUNT
2321 // REGISTER, AND IT MIGHT BE buff[2] NOT buff[3]. Bruce
2326 // Always succeed on a SMART status, as a disk that failed returned
2327 // buff[4]=0xF4, buff[5]=0x2C, i.e. "Bad SMART status" (see below).
2328 if (command
== STATUS
)
2330 //Data returned is starting from 0 offset
2331 if (command
== STATUS_CHECK
)
2333 // Cyl low and Cyl high unchanged means "Good SMART status"
2334 if (buff
[4] == 0x4F && buff
[5] == 0xC2)
2336 // These values mean "Bad SMART status"
2337 if (buff
[4] == 0xF4 && buff
[5] == 0x2C)
2339 // We haven't gotten output that makes sense; print out some debugging info
2340 syserror("Error SMART Status command failed");
2341 pout("Please get assistance from %s\n",PACKAGE_BUGREPORT
);
2342 pout("Register values returned from SMART Status command are:\n");
2343 pout("CMD =0x%02x\n",(int)buff
[0]);
2344 pout("FR =0x%02x\n",(int)buff
[1]);
2345 pout("NS =0x%02x\n",(int)buff
[2]);
2346 pout("SC =0x%02x\n",(int)buff
[3]);
2347 pout("CL =0x%02x\n",(int)buff
[4]);
2348 pout("CH =0x%02x\n",(int)buff
[5]);
2349 pout("SEL=0x%02x\n",(int)buff
[6]);
2354 memcpy(data
, buff
, 512);
2359 /////////////////////////////////////////////////////////////////////////////
2360 /// Highpoint RAID support
2362 class linux_highpoint_device
2363 : public /*implements*/ ata_device_with_command_set
,
2364 public /*extends*/ linux_smart_device
2367 linux_highpoint_device(smart_interface
* intf
, const char * dev_name
,
2368 unsigned char controller
, unsigned char channel
, unsigned char port
);
2371 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2374 unsigned char m_hpt_data
[3]; ///< controller/channel/port
2377 linux_highpoint_device::linux_highpoint_device(smart_interface
* intf
, const char * dev_name
,
2378 unsigned char controller
, unsigned char channel
, unsigned char port
)
2379 : smart_device(intf
, dev_name
, "hpt", "hpt"),
2380 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
2382 m_hpt_data
[0] = controller
; m_hpt_data
[1] = channel
; m_hpt_data
[2] = port
;
2383 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]);
2386 // this implementation is derived from ata_command_interface with a header
2387 // packing for highpoint linux driver ioctl interface
2389 // ioctl(fd,HPTIO_CTL,buff)
2392 // structure of hpt_buff
2393 // +----+----+----+----+--------------------.....---------------------+
2394 // | 1 | 2 | 3 | 4 | 5 |
2395 // +----+----+----+----+--------------------.....---------------------+
2397 // 1: The target controller [ int ( 4 Bytes ) ]
2398 // 2: The channel of the target controllee [ int ( 4 Bytes ) ]
2399 // 3: HDIO_ ioctl call [ int ( 4 Bytes ) ]
2400 // available from ${LINUX_KERNEL_SOURCE}/Documentation/ioctl/hdio
2401 // 4: the pmport that disk attached, [ int ( 4 Bytes ) ]
2402 // if no pmport device, set to 1 or leave blank
2403 // 5: data [ void * ( var leangth ) ]
2405 #define STRANGE_BUFFER_LENGTH (4+512*0xf8)
2407 int linux_highpoint_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2409 unsigned char hpt_buff
[4*sizeof(int) + STRANGE_BUFFER_LENGTH
];
2410 unsigned int *hpt
= (unsigned int *)hpt_buff
;
2411 unsigned char *buff
= &hpt_buff
[4*sizeof(int)];
2413 const int HDIO_DRIVE_CMD_OFFSET
= 4;
2415 memset(hpt_buff
, 0, 4*sizeof(int) + STRANGE_BUFFER_LENGTH
);
2416 hpt
[0] = m_hpt_data
[0]; // controller id
2417 hpt
[1] = m_hpt_data
[1]; // channel number
2418 hpt
[3] = m_hpt_data
[2]; // pmport number
2420 buff
[0]=ATA_SMART_CMD
;
2422 case CHECK_POWER_MODE
:
2423 buff
[0]=ATA_CHECK_POWER_MODE
;
2427 buff
[2]=ATA_SMART_READ_VALUES
;
2431 case READ_THRESHOLDS
:
2432 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
2437 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
2445 buff
[0]=ATA_IDENTIFY_DEVICE
;
2450 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
2455 buff
[2]=ATA_SMART_ENABLE
;
2459 buff
[2]=ATA_SMART_DISABLE
;
2463 buff
[2]=ATA_SMART_STATUS
;
2466 buff
[2]=ATA_SMART_AUTO_OFFLINE
;
2470 buff
[2]=ATA_SMART_AUTOSAVE
;
2473 case IMMEDIATE_OFFLINE
:
2474 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
2478 buff
[1]=ATA_SMART_STATUS
;
2481 pout("Unrecognized command %d in linux_highpoint_command_interface()\n"
2482 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
2487 if (command
==WRITE_LOG
) {
2488 unsigned char task
[4*sizeof(int)+sizeof(ide_task_request_t
)+512];
2489 unsigned int *hpt
= (unsigned int *)task
;
2490 ide_task_request_t
*reqtask
= (ide_task_request_t
*)(&task
[4*sizeof(int)]);
2491 task_struct_t
*taskfile
= (task_struct_t
*)reqtask
->io_ports
;
2494 memset(task
, 0, sizeof(task
));
2496 hpt
[0] = m_hpt_data
[0]; // controller id
2497 hpt
[1] = m_hpt_data
[1]; // channel number
2498 hpt
[3] = m_hpt_data
[2]; // pmport number
2499 hpt
[2] = HDIO_DRIVE_TASKFILE
; // real hd ioctl
2502 taskfile
->feature
= ATA_SMART_WRITE_LOG_SECTOR
;
2503 taskfile
->sector_count
= 1;
2504 taskfile
->sector_number
= select
;
2505 taskfile
->low_cylinder
= 0x4f;
2506 taskfile
->high_cylinder
= 0xc2;
2507 taskfile
->device_head
= 0;
2508 taskfile
->command
= ATA_SMART_CMD
;
2510 reqtask
->data_phase
= TASKFILE_OUT
;
2511 reqtask
->req_cmd
= IDE_DRIVE_TASK_OUT
;
2512 reqtask
->out_size
= 512;
2513 reqtask
->in_size
= 0;
2515 memcpy(task
+sizeof(ide_task_request_t
)+4*sizeof(int), data
, 512);
2517 if ((retval
=ioctl(get_fd(), HPTIO_CTL
, task
))) {
2518 if (retval
==-EINVAL
)
2519 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
2525 if (command
==STATUS_CHECK
){
2527 unsigned const char normal_lo
=0x4f, normal_hi
=0xc2;
2528 unsigned const char failed_lo
=0xf4, failed_hi
=0x2c;
2532 hpt
[2] = HDIO_DRIVE_TASK
;
2534 if ((retval
=ioctl(get_fd(), HPTIO_CTL
, hpt_buff
))) {
2535 if (retval
==-EINVAL
) {
2536 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
2537 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
2540 syserror("Error SMART Status command failed");
2544 if (buff
[4]==normal_lo
&& buff
[5]==normal_hi
)
2547 if (buff
[4]==failed_lo
&& buff
[5]==failed_hi
)
2550 syserror("Error SMART Status command failed");
2551 pout("Please get assistance from " PACKAGE_HOMEPAGE
"\n");
2552 pout("Register values returned from SMART Status command are:\n");
2553 pout("CMD=0x%02x\n",(int)buff
[0]);
2554 pout("FR =0x%02x\n",(int)buff
[1]);
2555 pout("NS =0x%02x\n",(int)buff
[2]);
2556 pout("SC =0x%02x\n",(int)buff
[3]);
2557 pout("CL =0x%02x\n",(int)buff
[4]);
2558 pout("CH =0x%02x\n",(int)buff
[5]);
2559 pout("SEL=0x%02x\n",(int)buff
[6]);
2564 if (command
==IDENTIFY
|| command
==PIDENTIFY
) {
2565 unsigned char deviceid
[4*sizeof(int)+512*sizeof(char)];
2566 unsigned int *hpt
= (unsigned int *)deviceid
;
2568 hpt
[0] = m_hpt_data
[0]; // controller id
2569 hpt
[1] = m_hpt_data
[1]; // channel number
2570 hpt
[3] = m_hpt_data
[2]; // pmport number
2572 hpt
[2] = HDIO_GET_IDENTITY
;
2573 if (!ioctl(get_fd(), HPTIO_CTL
, deviceid
) && (deviceid
[4*sizeof(int)] & 0x8000))
2574 buff
[0]=(command
==IDENTIFY
)?ATA_IDENTIFY_PACKET_DEVICE
:ATA_IDENTIFY_DEVICE
;
2578 hpt
[2] = HDIO_DRIVE_CMD
;
2579 if ((ioctl(get_fd(), HPTIO_CTL
, hpt_buff
)))
2582 if (command
==CHECK_POWER_MODE
)
2583 buff
[HDIO_DRIVE_CMD_OFFSET
]=buff
[2];
2586 memcpy(data
, buff
+HDIO_DRIVE_CMD_OFFSET
, copydata
);
2592 #if 0 // TODO: Migrate from 'smart_command_set' to 'ata_in_regs' OR remove the function
2593 // Utility function for printing warnings
2594 void printwarning(smart_command_set command
){
2595 static int printed
[4]={0,0,0,0};
2596 const char* message
=
2597 "can not be passed through the 3ware 3w-xxxx driver. This can be fixed by\n"
2598 "applying a simple 3w-xxxx driver patch that can be found here:\n"
2599 PACKAGE_HOMEPAGE
"\n"
2600 "Alternatively, upgrade your 3w-xxxx driver to version 1.02.00.037 or greater.\n\n";
2602 if (command
==AUTO_OFFLINE
&& !printed
[0]) {
2604 pout("The SMART AUTO-OFFLINE ENABLE command (smartmontools -o on option/Directive)\n%s", message
);
2606 else if (command
==AUTOSAVE
&& !printed
[1]) {
2608 pout("The SMART AUTOSAVE ENABLE command (smartmontools -S on option/Directive)\n%s", message
);
2610 else if (command
==STATUS_CHECK
&& !printed
[2]) {
2612 pout("The SMART RETURN STATUS return value (smartmontools -H option/Directive)\n%s", message
);
2614 else if (command
==WRITE_LOG
&& !printed
[3]) {
2616 pout("The SMART WRITE LOG command (smartmontools -t selective) only supported via char /dev/tw[ae] interface\n");
2624 /////////////////////////////////////////////////////////////////////////////
2625 /// SCSI open with autodetection support
2627 smart_device
* linux_scsi_device::autodetect_open()
2633 // No Autodetection if device type was specified by user
2634 if (*get_req_type())
2637 // The code below is based on smartd.cpp:SCSIFilterKnown()
2640 unsigned char req_buff
[64] = {0, };
2642 if (scsiStdInquiry(this, req_buff
, req_len
)) {
2643 // Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices
2644 // watch this spot ... other devices could lock up here
2646 if (scsiStdInquiry(this, req_buff
, req_len
)) {
2647 // device doesn't like INQUIRY commands
2649 set_err(EIO
, "INQUIRY failed");
2654 int avail_len
= req_buff
[4] + 5;
2655 int len
= (avail_len
< req_len
? avail_len
: req_len
);
2659 // Use INQUIRY to detect type
2660 smart_device
* newdev
= 0;
2663 if (!memcmp(req_buff
+ 8, "3ware", 5) || !memcmp(req_buff
+ 8, "AMCC", 4)) {
2665 set_err(EINVAL
, "AMCC/3ware controller, please try adding '-d 3ware,N',\n"
2666 "you may need to replace %s with /dev/twaN or /dev/tweN", get_dev_name());
2671 if (len
>= 42 && !memcmp(req_buff
+ 36, "MVSATA", 6)) {
2672 //pout("Device %s: using '-d marvell' for ATA disk with Marvell driver\n", get_dev_name());
2674 newdev
= new linux_marvell_device(smi(), get_dev_name(), get_req_type());
2675 newdev
->open(); // TODO: Can possibly pass open fd
2681 newdev
= smi()->autodetect_sat_device(this, req_buff
, len
);
2683 // NOTE: 'this' is now owned by '*newdev'
2687 // Cleanup if exception occurs after newdev was allocated
2692 // Nothing special found
2697 //////////////////////////////////////////////////////////////////////
2698 // USB bridge ID detection
2700 // Read USB ID from /sys file
2701 static bool read_id(const std::string
& path
, unsigned short & id
)
2703 FILE * f
= fopen(path
.c_str(), "r");
2707 bool ok
= (fscanf(f
, "%hx%n", &id
, &n
) == 1 && n
== 4);
2712 // Get USB bridge ID for "/dev/sdX"
2713 static bool get_usb_id(const char * path
, unsigned short & vendor_id
,
2714 unsigned short & product_id
, unsigned short & version
)
2716 // Only "/dev/sdX" supported
2717 if (!(!strncmp(path
, "/dev/sd", 7) && !strchr(path
+ 7, '/')))
2720 // Start search at dir referenced by symlink "/sys/block/sdX/device"
2721 // -> "/sys/devices/.../usb*/.../host*/target*/..."
2722 std::string dir
= strprintf("/sys/block/%s/device", path
+ 5);
2724 // Stop search at "/sys/devices"
2726 if (stat("/sys/devices", &st
))
2728 ino_t stop_ino
= st
.st_ino
;
2730 // Search in parent directories until "idVendor" is found,
2731 // fail if "/sys/devices" reached or too many iterations
2735 if (!(++cnt
< 10 && !stat(dir
.c_str(), &st
) && st
.st_ino
!= stop_ino
))
2737 } while (access((dir
+ "/idVendor").c_str(), 0));
2740 if (!( read_id(dir
+ "/idVendor", vendor_id
)
2741 && read_id(dir
+ "/idProduct", product_id
)
2742 && read_id(dir
+ "/bcdDevice", version
) ))
2745 if (con
->reportscsiioctl
> 1)
2746 pout("USB ID = 0x%04x:0x%04x (0x%03x)\n", vendor_id
, product_id
, version
);
2751 //////////////////////////////////////////////////////////////////////
2754 class linux_smart_interface
2755 : public /*implements*/ smart_interface
2758 virtual const char * get_app_examples(const char * appname
);
2760 virtual bool scan_smart_devices(smart_device_list
& devlist
, const char * type
,
2761 const char * pattern
= 0);
2764 virtual ata_device
* get_ata_device(const char * name
, const char * type
);
2766 virtual scsi_device
* get_scsi_device(const char * name
, const char * type
);
2768 virtual smart_device
* autodetect_smart_device(const char * name
);
2770 virtual smart_device
* get_custom_smart_device(const char * name
, const char * type
);
2772 virtual const char * get_valid_custom_dev_types_str();
2775 bool get_dev_list(smart_device_list
& devlist
, const char * pattern
,
2776 bool scan_ata
, bool scan_scsi
, const char * req_type
);
2778 smart_device
* missing_option(const char * opt
);
2781 const char * linux_smart_interface::get_app_examples(const char * appname
)
2783 if (!strcmp(appname
, "smartctl"))
2784 return smartctl_examples
;
2789 // we are going to take advantage of the fact that Linux's devfs will only
2790 // have device entries for devices that exist. So if we get the equivalent of
2791 // ls /dev/hd[a-t], we have all the ATA devices on the system
2792 bool linux_smart_interface::get_dev_list(smart_device_list
& devlist
,
2793 const char * pattern
, bool scan_ata
, bool scan_scsi
, const char * req_type
)
2795 // Use glob to look for any directory entries matching the pattern
2797 memset(&globbuf
, 0, sizeof(globbuf
));
2798 int retglob
= glob(pattern
, GLOB_ERR
, NULL
, &globbuf
);
2800 // glob failed: free memory and return
2803 if (retglob
==GLOB_NOMATCH
){
2804 pout("glob(3) found no matches for pattern %s\n", pattern
);
2808 if (retglob
==GLOB_NOSPACE
)
2809 set_err(ENOMEM
, "glob(3) ran out of memory matching pattern %s", pattern
);
2810 #ifdef GLOB_ABORTED // missing in old versions of glob.h
2811 else if (retglob
==GLOB_ABORTED
)
2812 set_err(EINVAL
, "glob(3) aborted matching pattern %s", pattern
);
2815 set_err(EINVAL
, "Unexplained error in glob(3) of pattern %s", pattern
);
2820 // did we find too many paths?
2821 const int max_pathc
= 32;
2822 int n
= (int)globbuf
.gl_pathc
;
2823 if (n
> max_pathc
) {
2824 pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n",
2825 n
, max_pathc
, pattern
, n
- max_pathc
);
2829 // now step through the list returned by glob. If not a link, copy
2830 // to list. If it is a link, evaluate it and see if the path ends
2832 for (int i
= 0; i
< n
; i
++){
2833 // see if path is a link
2835 int retlink
= readlink(globbuf
.gl_pathv
[i
], linkbuf
, sizeof(linkbuf
)-1);
2837 char tmpname
[1024]={0};
2838 const char * name
= 0;
2839 bool is_scsi
= scan_scsi
;
2840 // if not a link (or a strange link), keep it
2841 if (retlink
<=0 || retlink
>1023)
2842 name
= globbuf
.gl_pathv
[i
];
2844 // or if it's a link that points to a disc, follow it
2845 linkbuf
[retlink
] = 0;
2847 if ((p
=strrchr(linkbuf
, '/')) && !strcmp(p
+1, "disc"))
2848 // This is the branch of the code that gets followed if we are
2849 // using devfs WITH traditional compatibility links. In this
2850 // case, we add the traditional device name to the list that
2852 name
= globbuf
.gl_pathv
[i
];
2854 // This is the branch of the code that gets followed if we are
2855 // using devfs WITHOUT traditional compatibility links. In
2856 // this case, we check that the link to the directory is of
2857 // the correct type, and then append "disc" to it.
2858 bool match_ata
= strstr(linkbuf
, "ide");
2859 bool match_scsi
= strstr(linkbuf
, "scsi");
2860 if (((match_ata
&& scan_ata
) || (match_scsi
&& scan_scsi
)) && !(match_ata
&& match_scsi
)) {
2861 is_scsi
= match_scsi
;
2862 snprintf(tmpname
, sizeof(tmpname
), "%s/disc", globbuf
.gl_pathv
[i
]);
2869 // Found a name, add device to list.
2871 devlist
.add(new linux_scsi_device(this, name
, req_type
));
2873 devlist
.add(new linux_ata_device(this, name
, req_type
));
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 bool scan_scsi
= (!*type
|| !strcmp(type
, "scsi"));
2896 if (!(scan_ata
|| scan_scsi
))
2900 get_dev_list(devlist
,"/dev/hd[a-t]", true, false, type
);
2902 get_dev_list(devlist
, "/dev/sd[a-z]", false, true, type
);
2904 // if we found traditional links, we are done
2905 if (devlist
.size() > 0)
2908 // else look for devfs entries without traditional links
2909 // TODO: Add udev support
2910 return get_dev_list(devlist
, "/dev/discs/disc*", scan_ata
, scan_scsi
, type
);
2913 ata_device
* linux_smart_interface::get_ata_device(const char * name
, const char * type
)
2915 return new linux_ata_device(this, name
, type
);
2918 scsi_device
* linux_smart_interface::get_scsi_device(const char * name
, const char * type
)
2920 return new linux_scsi_device(this, name
, type
);
2923 smart_device
* linux_smart_interface::missing_option(const char * opt
)
2925 set_err(EINVAL
, "requires option '%s'", opt
);
2929 // Guess device type (ata or scsi) based on device name (Linux
2930 // specific) SCSI device name in linux can be sd, sr, scd, st, nst,
2931 // osst, nosst and sg.
2932 static const char * lin_dev_prefix
= "/dev/";
2933 static const char * lin_dev_ata_disk_plus
= "h";
2934 static const char * lin_dev_ata_devfs_disk_plus
= "ide/";
2935 static const char * lin_dev_scsi_devfs_disk_plus
= "scsi/";
2936 static const char * lin_dev_scsi_disk_plus
= "s";
2937 static const char * lin_dev_scsi_tape1
= "ns";
2938 static const char * lin_dev_scsi_tape2
= "os";
2939 static const char * lin_dev_scsi_tape3
= "nos";
2940 static const char * lin_dev_3ware_9000_char
= "twa";
2941 static const char * lin_dev_3ware_678k_char
= "twe";
2942 static const char * lin_dev_cciss_dir
= "cciss/";
2943 static const char * lin_dev_areca
= "sg";
2945 smart_device
* linux_smart_interface::autodetect_smart_device(const char * name
)
2947 const char * dev_name
= name
; // TODO: Remove this hack
2948 int dev_prefix_len
= strlen(lin_dev_prefix
);
2950 // if dev_name null, or string length zero
2952 if (!dev_name
|| !(len
= strlen(dev_name
)))
2955 // Remove the leading /dev/... if it's there
2956 if (!strncmp(lin_dev_prefix
, dev_name
, dev_prefix_len
)) {
2957 if (len
<= dev_prefix_len
)
2958 // if nothing else in the string, unrecognized
2960 // else advance pointer to following characters
2961 dev_name
+= dev_prefix_len
;
2964 // form /dev/h* or h*
2965 if (!strncmp(lin_dev_ata_disk_plus
, dev_name
,
2966 strlen(lin_dev_ata_disk_plus
)))
2967 return new linux_ata_device(this, name
, "");
2969 // form /dev/ide/* or ide/*
2970 if (!strncmp(lin_dev_ata_devfs_disk_plus
, dev_name
,
2971 strlen(lin_dev_ata_devfs_disk_plus
)))
2972 return new linux_ata_device(this, name
, "");
2974 // form /dev/s* or s*
2975 if (!strncmp(lin_dev_scsi_disk_plus
, dev_name
,
2976 strlen(lin_dev_scsi_disk_plus
))) {
2978 // Try to detect possible USB->(S)ATA bridge
2979 unsigned short vendor_id
= 0, product_id
= 0, version
= 0;
2980 if (get_usb_id(name
, vendor_id
, product_id
, version
)) {
2981 const char * usbtype
= get_usb_dev_type_by_id(vendor_id
, product_id
, version
);
2984 // Linux USB layer does not support 16 byte SAT pass through command
2985 if (!strcmp(usbtype
, "sat"))
2987 // Return SAT/USB device for this type
2988 // (Note: linux_scsi_device::autodetect_open() will not be called in this case)
2989 return get_sat_device(usbtype
, new linux_scsi_device(this, name
, ""));
2992 // No USB bridge found, assume regular SCSI device
2993 return new linux_scsi_device(this, name
, "");
2996 // form /dev/scsi/* or scsi/*
2997 if (!strncmp(lin_dev_scsi_devfs_disk_plus
, dev_name
,
2998 strlen(lin_dev_scsi_devfs_disk_plus
)))
2999 return new linux_scsi_device(this, name
, "");
3001 // form /dev/ns* or ns*
3002 if (!strncmp(lin_dev_scsi_tape1
, dev_name
,
3003 strlen(lin_dev_scsi_tape1
)))
3004 return new linux_scsi_device(this, name
, "");
3006 // form /dev/os* or os*
3007 if (!strncmp(lin_dev_scsi_tape2
, dev_name
,
3008 strlen(lin_dev_scsi_tape2
)))
3009 return new linux_scsi_device(this, name
, "");
3011 // form /dev/nos* or nos*
3012 if (!strncmp(lin_dev_scsi_tape3
, dev_name
,
3013 strlen(lin_dev_scsi_tape3
)))
3014 return new linux_scsi_device(this, name
, "");
3017 if (!strncmp(lin_dev_3ware_9000_char
, dev_name
,
3018 strlen(lin_dev_3ware_9000_char
)))
3019 return missing_option("-d 3ware,N");
3022 if (!strncmp(lin_dev_3ware_678k_char
, dev_name
,
3023 strlen(lin_dev_3ware_678k_char
)))
3024 return missing_option("-d 3ware,N");
3027 if (!strncmp(lin_dev_cciss_dir
, dev_name
,
3028 strlen(lin_dev_cciss_dir
)))
3029 return missing_option("-d cciss,N");
3032 if ( !strncmp(lin_dev_areca
, dev_name
,
3033 strlen(lin_dev_areca
)) )
3034 return missing_option("-d areca,N");
3036 // we failed to recognize any of the forms
3040 smart_device
* linux_smart_interface::get_custom_smart_device(const char * name
, const char * type
)
3043 if (!strcmp(type
, "marvell"))
3044 return new linux_marvell_device(this, name
, type
);
3047 int disknum
= -1, n1
= -1, n2
= -1;
3048 if (sscanf(type
, "3ware,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3049 if (n2
!= (int)strlen(type
)) {
3050 set_err(EINVAL
, "Option -d 3ware,N requires N to be a non-negative integer");
3053 if (!(0 <= disknum
&& disknum
<= 127)) {
3054 set_err(EINVAL
, "Option -d 3ware,N (N=%d) must have 0 <= N <= 127", disknum
);
3058 if (!strncmp(name
, "/dev/twa", 8))
3059 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_9000_CHAR
, disknum
);
3060 else if (!strncmp(name
, "/dev/twe", 8))
3061 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_678K_CHAR
, disknum
);
3063 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_678K
, disknum
);
3067 disknum
= n1
= n2
= -1;
3068 if (sscanf(type
, "areca,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3069 if (n2
!= (int)strlen(type
)) {
3070 set_err(EINVAL
, "Option -d areca,N requires N to be a non-negative integer");
3073 if (!(1 <= disknum
&& disknum
<= 24)) {
3074 set_err(EINVAL
, "Option -d areca,N (N=%d) must have 1 <= N <= 24", disknum
);
3077 return new linux_areca_device(this, name
, disknum
);
3081 int controller
= -1, channel
= -1; disknum
= 1;
3082 n1
= n2
= -1; int n3
= -1;
3083 if (sscanf(type
, "hpt,%n%d/%d%n/%d%n", &n1
, &controller
, &channel
, &n2
, &disknum
, &n3
) >= 2 || n1
== 4) {
3084 int len
= strlen(type
);
3085 if (!(n2
== len
|| n3
== len
)) {
3086 set_err(EINVAL
, "Option '-d hpt,L/M/N' supports 2-3 items");
3089 if (!(1 <= controller
&& controller
<= 8)) {
3090 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid controller id L supplied");
3093 if (!(1 <= channel
&& channel
<= 8)) {
3094 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid channel number M supplied");
3097 if (!(1 <= disknum
&& disknum
<= 15)) {
3098 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid pmport number N supplied");
3101 return new linux_highpoint_device(this, name
, controller
, channel
, disknum
);
3104 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3106 disknum
= n1
= n2
= -1;
3107 if (sscanf(type
, "cciss,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3108 if (n2
!= (int)strlen(type
)) {
3109 set_err(EINVAL
, "Option -d cciss,N requires N to be a non-negative integer");
3112 if (!(0 <= disknum
&& disknum
<= 15)) {
3113 set_err(EINVAL
, "Option -d cciss,N (N=%d) must have 0 <= N <= 15", disknum
);
3116 return new linux_cciss_device(this, name
, disknum
);
3118 #endif // HAVE_LINUX_CCISS_IOCTL_H
3121 if (sscanf(type
, "megaraid,%d", &disknum
) == 1) {
3122 return new linux_megaraid_device(this, name
, 0, disknum
);
3127 const char * linux_smart_interface::get_valid_custom_dev_types_str()
3129 return "marvell, areca,N, 3ware,N, hpt,L/M/N, megaraid,N"
3130 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3139 /////////////////////////////////////////////////////////////////////////////
3140 /// Initialize platform interface and register with smi()
3142 void smart_interface::init()
3144 static os_linux::linux_smart_interface the_interface
;
3145 smart_interface::set(&the_interface
);