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 Hank Wu <hank@areca.com.tw>
9 * Copyright (C) 2008 Oliver Bock <brevilo@users.sourceforge.net>
10 * Copyright (C) 2008-11 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 3317 2011-04-19 19:42:54Z 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 /dev/sg2\n"
200 " (Prints all SMART info for 3rd ATA disk on Areca RAID controller)\n"
204 /////////////////////////////////////////////////////////////////////////////
205 /// Linux ATA support
207 class linux_ata_device
208 : public /*implements*/ ata_device_with_command_set
,
209 public /*extends*/ linux_smart_device
212 linux_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
215 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
218 linux_ata_device::linux_ata_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
)
219 : smart_device(intf
, dev_name
, "ata", req_type
),
220 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
225 // This is an interface routine meant to isolate the OS dependent
226 // parts of the code, and to provide a debugging interface. Each
227 // different port and OS needs to provide it's own interface. This
229 // DETAILED DESCRIPTION OF ARGUMENTS
230 // device: is the file descriptor provided by open()
231 // command: defines the different operations.
232 // select: additional input data if needed (which log, which type of
234 // data: location to write output data, if needed (512 bytes).
235 // Note: not all commands use all arguments.
237 // -1 if the command failed
238 // 0 if the command succeeded,
239 // STATUS_CHECK routine:
240 // -1 if the command failed
241 // 0 if the command succeeded and disk SMART status is "OK"
242 // 1 if the command succeeded and disk SMART status is "FAILING"
245 #define BUFFER_LENGTH (4+512)
247 int linux_ata_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
249 unsigned char buff
[BUFFER_LENGTH
];
250 // positive: bytes to write to caller. negative: bytes to READ from
251 // caller. zero: non-data command
254 const int HDIO_DRIVE_CMD_OFFSET
= 4;
256 // See struct hd_drive_cmd_hdr in hdreg.h. Before calling ioctl()
257 // buff[0]: ATA COMMAND CODE REGISTER
258 // buff[1]: ATA SECTOR NUMBER REGISTER == LBA LOW REGISTER
259 // buff[2]: ATA FEATURES REGISTER
260 // buff[3]: ATA SECTOR COUNT REGISTER
262 // Note that on return:
263 // buff[2] contains the ATA SECTOR COUNT REGISTER
265 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
266 memset(buff
, 0, BUFFER_LENGTH
);
268 buff
[0]=ATA_SMART_CMD
;
270 case CHECK_POWER_MODE
:
271 buff
[0]=ATA_CHECK_POWER_MODE
;
275 buff
[2]=ATA_SMART_READ_VALUES
;
279 case READ_THRESHOLDS
:
280 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
285 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
293 buff
[0]=ATA_IDENTIFY_DEVICE
;
298 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
303 buff
[2]=ATA_SMART_ENABLE
;
307 buff
[2]=ATA_SMART_DISABLE
;
311 // this command only says if SMART is working. It could be
312 // replaced with STATUS_CHECK below.
313 buff
[2]=ATA_SMART_STATUS
;
316 // NOTE: According to ATAPI 4 and UP, this command is obsolete
317 // select == 241 for enable but no data transfer. Use TASK ioctl.
318 buff
[1]=ATA_SMART_AUTO_OFFLINE
;
322 // select == 248 for enable but no data transfer. Use TASK ioctl.
323 buff
[1]=ATA_SMART_AUTOSAVE
;
326 case IMMEDIATE_OFFLINE
:
327 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
331 // This command uses HDIO_DRIVE_TASK and has different syntax than
332 // the other commands.
333 buff
[1]=ATA_SMART_STATUS
;
336 pout("Unrecognized command %d in linux_ata_command_interface()\n"
337 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
342 // This command uses the HDIO_DRIVE_TASKFILE ioctl(). This is the
343 // only ioctl() that can be used to WRITE data to the disk.
344 if (command
==WRITE_LOG
) {
345 unsigned char task
[sizeof(ide_task_request_t
)+512];
346 ide_task_request_t
*reqtask
=(ide_task_request_t
*) task
;
347 task_struct_t
*taskfile
=(task_struct_t
*) reqtask
->io_ports
;
350 memset(task
, 0, sizeof(task
));
353 taskfile
->feature
= ATA_SMART_WRITE_LOG_SECTOR
;
354 taskfile
->sector_count
= 1;
355 taskfile
->sector_number
= select
;
356 taskfile
->low_cylinder
= 0x4f;
357 taskfile
->high_cylinder
= 0xc2;
358 taskfile
->device_head
= 0;
359 taskfile
->command
= ATA_SMART_CMD
;
361 reqtask
->data_phase
= TASKFILE_OUT
;
362 reqtask
->req_cmd
= IDE_DRIVE_TASK_OUT
;
363 reqtask
->out_size
= 512;
364 reqtask
->in_size
= 0;
366 // copy user data into the task request structure
367 memcpy(task
+sizeof(ide_task_request_t
), data
, 512);
369 if ((retval
=ioctl(get_fd(), HDIO_DRIVE_TASKFILE
, task
))) {
371 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
377 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
379 if (command
==STATUS_CHECK
|| command
==AUTOSAVE
|| command
==AUTO_OFFLINE
){
382 // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
383 // have to read the IDE driver source code. Sigh.
384 // buff[0]: ATA COMMAND CODE REGISTER
385 // buff[1]: ATA FEATURES REGISTER
386 // buff[2]: ATA SECTOR_COUNT
387 // buff[3]: ATA SECTOR NUMBER
388 // buff[4]: ATA CYL LO REGISTER
389 // buff[5]: ATA CYL HI REGISTER
390 // buff[6]: ATA DEVICE HEAD
392 unsigned const char normal_lo
=0x4f, normal_hi
=0xc2;
393 unsigned const char failed_lo
=0xf4, failed_hi
=0x2c;
397 if ((retval
=ioctl(get_fd(), HDIO_DRIVE_TASK
, buff
))) {
398 if (retval
==-EINVAL
) {
399 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
400 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
403 syserror("Error SMART Status command failed");
407 // Cyl low and Cyl high unchanged means "Good SMART status"
408 if (buff
[4]==normal_lo
&& buff
[5]==normal_hi
)
411 // These values mean "Bad SMART status"
412 if (buff
[4]==failed_lo
&& buff
[5]==failed_hi
)
415 // We haven't gotten output that makes sense; print out some debugging info
416 syserror("Error SMART Status command failed");
417 pout("Please get assistance from " PACKAGE_HOMEPAGE
"\n");
418 pout("Register values returned from SMART Status command are:\n");
419 pout("ST =0x%02x\n",(int)buff
[0]);
420 pout("ERR=0x%02x\n",(int)buff
[1]);
421 pout("NS =0x%02x\n",(int)buff
[2]);
422 pout("SC =0x%02x\n",(int)buff
[3]);
423 pout("CL =0x%02x\n",(int)buff
[4]);
424 pout("CH =0x%02x\n",(int)buff
[5]);
425 pout("SEL=0x%02x\n",(int)buff
[6]);
430 // Note to people doing ports to other OSes -- don't worry about
431 // this block -- you can safely ignore it. I have put it here
432 // because under linux when you do IDENTIFY DEVICE to a packet
433 // device, it generates an ugly kernel syslog error message. This
434 // is harmless but frightens users. So this block detects packet
435 // devices and make IDENTIFY DEVICE fail "nicely" without a syslog
438 // If you read only the ATA specs, it appears as if a packet device
439 // *might* respond to the IDENTIFY DEVICE command. This is
440 // misleading - it's because around the time that SFF-8020 was
441 // incorporated into the ATA-3/4 standard, the ATA authors were
442 // sloppy. See SFF-8020 and you will see that ATAPI devices have
443 // *always* had IDENTIFY PACKET DEVICE as a mandatory part of their
444 // command set, and return 'Command Aborted' to IDENTIFY DEVICE.
445 if (command
==IDENTIFY
|| command
==PIDENTIFY
){
446 unsigned short deviceid
[256];
447 // check the device identity, as seen when the system was booted
448 // or the device was FIRST registered. This will not be current
449 // if the user has subsequently changed some of the parameters. If
450 // device is a packet device, swap the command interpretations.
451 if (!ioctl(get_fd(), HDIO_GET_IDENTITY
, deviceid
) && (deviceid
[0] & 0x8000))
452 buff
[0]=(command
==IDENTIFY
)?ATA_IDENTIFY_PACKET_DEVICE
:ATA_IDENTIFY_DEVICE
;
456 // We are now doing the HDIO_DRIVE_CMD type ioctl.
457 if ((ioctl(get_fd(), HDIO_DRIVE_CMD
, buff
)))
460 // CHECK POWER MODE command returns information in the Sector Count
461 // register (buff[3]). Copy to return data buffer.
462 if (command
==CHECK_POWER_MODE
)
463 buff
[HDIO_DRIVE_CMD_OFFSET
]=buff
[2];
465 // if the command returns data then copy it back
467 memcpy(data
, buff
+HDIO_DRIVE_CMD_OFFSET
, copydata
);
472 // >>>>>> Start of general SCSI specific linux code
474 /* Linux specific code.
475 * Historically smartmontools (and smartsuite before it) used the
476 * SCSI_IOCTL_SEND_COMMAND ioctl which is available to all linux device
477 * nodes that use the SCSI subsystem. A better interface has been available
478 * via the SCSI generic (sg) driver but this involves the extra step of
479 * mapping disk devices (e.g. /dev/sda) to the corresponding sg device
480 * (e.g. /dev/sg2). In the linux kernel 2.6 series most of the facilities of
481 * the sg driver have become available via the SG_IO ioctl which is available
482 * on all SCSI devices (on SCSI tape devices from lk 2.6.6).
483 * So the strategy below is to find out if the SG_IO ioctl is available and
484 * if so use it; failing that use the older SCSI_IOCTL_SEND_COMMAND ioctl.
485 * Should work in 2.0, 2.2, 2.4 and 2.6 series linux kernels. */
487 #define MAX_DXFER_LEN 1024 /* can be increased if necessary */
488 #define SEND_IOCTL_RESP_SENSE_LEN 16 /* ioctl limitation */
489 #define SG_IO_RESP_SENSE_LEN 64 /* large enough see buffer */
490 #define LSCSI_DRIVER_MASK 0xf /* mask out "suggestions" */
491 #define LSCSI_DRIVER_SENSE 0x8 /* alternate CHECK CONDITION indication */
492 #define LSCSI_DID_ERROR 0x7 /* Need to work around aacraid driver quirk */
493 #define LSCSI_DRIVER_TIMEOUT 0x6
494 #define LSCSI_DID_TIME_OUT 0x3
495 #define LSCSI_DID_BUS_BUSY 0x2
496 #define LSCSI_DID_NO_CONNECT 0x1
498 #ifndef SCSI_IOCTL_SEND_COMMAND
499 #define SCSI_IOCTL_SEND_COMMAND 1
502 #define SG_IO_PRESENT_UNKNOWN 0
503 #define SG_IO_PRESENT_YES 1
504 #define SG_IO_PRESENT_NO 2
506 static int sg_io_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
,
508 static int sisc_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
);
510 static int sg_io_state
= SG_IO_PRESENT_UNKNOWN
;
512 /* Preferred implementation for issuing SCSI commands in linux. This
513 * function uses the SG_IO ioctl. Return 0 if command issued successfully
514 * (various status values should still be checked). If the SCSI command
515 * cannot be issued then a negative errno value is returned. */
516 static int sg_io_cmnd_io(int dev_fd
, struct scsi_cmnd_io
* iop
, int report
,
520 ARGUSED(dev_fd
); ARGUSED(iop
); ARGUSED(report
);
523 struct sg_io_hdr io_hdr
;
527 const unsigned char * ucp
= iop
->cmnd
;
530 const int sz
= (int)sizeof(buff
);
532 np
= scsi_get_opcode_name(ucp
[0]);
533 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
534 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
535 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
537 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
538 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
540 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
541 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
542 (trunc
? " [only first 256 bytes shown]" : ""));
543 dStrHex((const char *)iop
->dxferp
,
544 (trunc
? 256 : iop
->dxfer_len
) , 1);
547 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
550 memset(&io_hdr
, 0, sizeof(struct sg_io_hdr
));
551 io_hdr
.interface_id
= 'S';
552 io_hdr
.cmd_len
= iop
->cmnd_len
;
553 io_hdr
.mx_sb_len
= iop
->max_sense_len
;
554 io_hdr
.dxfer_len
= iop
->dxfer_len
;
555 io_hdr
.dxferp
= iop
->dxferp
;
556 io_hdr
.cmdp
= iop
->cmnd
;
557 io_hdr
.sbp
= iop
->sensep
;
558 /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
559 defaults to 60 seconds. */
560 io_hdr
.timeout
= ((0 == iop
->timeout
) ? 60 : iop
->timeout
) * 1000;
561 switch (iop
->dxfer_dir
) {
563 io_hdr
.dxfer_direction
= SG_DXFER_NONE
;
565 case DXFER_FROM_DEVICE
:
566 io_hdr
.dxfer_direction
= SG_DXFER_FROM_DEV
;
568 case DXFER_TO_DEVICE
:
569 io_hdr
.dxfer_direction
= SG_DXFER_TO_DEV
;
572 pout("do_scsi_cmnd_io: bad dxfer_dir\n");
575 iop
->resp_sense_len
= 0;
576 iop
->scsi_status
= 0;
578 if (ioctl(dev_fd
, SG_IO
, &io_hdr
) < 0) {
579 if (report
&& (! unknown
))
580 pout(" SG_IO ioctl failed, errno=%d [%s]\n", errno
,
584 iop
->resid
= io_hdr
.resid
;
585 iop
->scsi_status
= io_hdr
.status
;
587 pout(" scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
588 " info=0x%x duration=%d milliseconds resid=%d\n", io_hdr
.status
,
589 io_hdr
.host_status
, io_hdr
.driver_status
, io_hdr
.info
,
590 io_hdr
.duration
, io_hdr
.resid
);
592 if (DXFER_FROM_DEVICE
== iop
->dxfer_dir
) {
595 len
= iop
->dxfer_len
- iop
->resid
;
596 trunc
= (len
> 256) ? 1 : 0;
598 pout(" Incoming data, len=%d%s:\n", len
,
599 (trunc
? " [only first 256 bytes shown]" : ""));
600 dStrHex((const char*)iop
->dxferp
, (trunc
? 256 : len
),
603 pout(" Incoming data trimmed to nothing by resid\n");
608 if (io_hdr
.info
| SG_INFO_CHECK
) { /* error or warning */
609 int masked_driver_status
= (LSCSI_DRIVER_MASK
& io_hdr
.driver_status
);
611 if (0 != io_hdr
.host_status
) {
612 if ((LSCSI_DID_NO_CONNECT
== io_hdr
.host_status
) ||
613 (LSCSI_DID_BUS_BUSY
== io_hdr
.host_status
) ||
614 (LSCSI_DID_TIME_OUT
== io_hdr
.host_status
))
617 /* Check for DID_ERROR - workaround for aacraid driver quirk */
618 if (LSCSI_DID_ERROR
!= io_hdr
.host_status
) {
619 return -EIO
; /* catch all if not DID_ERR */
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
,
831 const char * req_type
, bool scanning
= false);
833 virtual smart_device
* autodetect_open();
835 virtual bool scsi_pass_through(scsi_cmnd_io
* iop
);
838 bool m_scanning
; ///< true if created within scan_smart_devices
841 linux_scsi_device::linux_scsi_device(smart_interface
* intf
,
842 const char * dev_name
, const char * req_type
, bool scanning
/*= false*/)
843 : smart_device(intf
, dev_name
, "scsi", req_type
),
844 // If opened with O_RDWR, a SATA disk in standby mode
845 // may spin-up after device close().
846 linux_smart_device(O_RDONLY
| O_NONBLOCK
),
852 bool linux_scsi_device::scsi_pass_through(scsi_cmnd_io
* iop
)
854 int status
= do_normal_scsi_cmnd_io(get_fd(), iop
, scsi_debugmode
);
856 return set_err(-status
);
860 /////////////////////////////////////////////////////////////////////////////
861 /// LSI MegaRAID support
863 class linux_megaraid_device
864 : public /* implements */ scsi_device
,
865 public /* extends */ linux_smart_device
868 linux_megaraid_device(smart_interface
*intf
, const char *name
,
869 unsigned int bus
, unsigned int tgt
);
871 virtual ~linux_megaraid_device() throw();
873 virtual smart_device
* autodetect_open();
876 virtual bool close();
878 virtual bool scsi_pass_through(scsi_cmnd_io
*iop
);
881 unsigned int m_disknum
;
882 unsigned int m_busnum
;
886 bool (linux_megaraid_device::*pt_cmd
)(int cdblen
, void *cdb
, int dataLen
, void *data
,
887 int senseLen
, void *sense
, int report
);
888 bool megasas_cmd(int cdbLen
, void *cdb
, int dataLen
, void *data
,
889 int senseLen
, void *sense
, int report
);
890 bool megadev_cmd(int cdbLen
, void *cdb
, int dataLen
, void *data
,
891 int senseLen
, void *sense
, int report
);
894 linux_megaraid_device::linux_megaraid_device(smart_interface
*intf
,
895 const char *dev_name
, unsigned int bus
, unsigned int tgt
)
896 : smart_device(intf
, dev_name
, "megaraid", "megaraid"),
897 linux_smart_device(O_RDWR
| O_NONBLOCK
),
898 m_disknum(tgt
), m_busnum(bus
), m_hba(0),
901 set_info().info_name
= strprintf("%s [megaraid_disk_%02d]", dev_name
, m_disknum
);
904 linux_megaraid_device::~linux_megaraid_device() throw()
910 smart_device
* linux_megaraid_device::autodetect_open()
912 int report
= scsi_debugmode
;
918 // The code below is based on smartd.cpp:SCSIFilterKnown()
919 if (strcmp(get_req_type(), "megaraid"))
923 unsigned char req_buff
[64] = {0, };
925 if (scsiStdInquiry(this, req_buff
, req_len
)) {
927 set_err(EIO
, "INQUIRY failed");
931 int avail_len
= req_buff
[4] + 5;
932 int len
= (avail_len
< req_len
? avail_len
: req_len
);
937 pout("Got MegaRAID inquiry.. %s\n", req_buff
+8);
939 // Use INQUIRY to detect type
942 ata_device
* newdev
= smi()->autodetect_sat_device(this, req_buff
, len
);
944 // NOTE: 'this' is now owned by '*newdev'
948 // Nothing special found
953 bool linux_megaraid_device::open()
958 int report
= scsi_debugmode
;
960 if (!linux_smart_device::open())
964 struct sg_scsi_id sgid
;
965 if (ioctl(get_fd(), SG_GET_SCSI_ID
, &sgid
) == 0) {
966 m_hba
= sgid
.host_no
;
968 else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER
, &m_hba
) != 0) {
970 linux_smart_device::close();
971 return set_err(err
, "can't get bus number");
974 /* Perform mknod of device ioctl node */
975 fp
= fopen("/proc/devices", "r");
976 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
978 if (sscanf(line
, "%d megaraid_sas_ioctl%n", &mjr
, &n1
) == 1 && n1
== 22) {
979 n1
=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR
, makedev(mjr
, 0));
981 pout("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1
>= 0 ? 0 : errno
);
982 if (n1
>= 0 || errno
== EEXIST
)
985 else if (sscanf(line
, "%d megadev%n", &mjr
, &n1
) == 1 && n1
== 11) {
986 n1
=mknod("/dev/megadev0", S_IFCHR
, makedev(mjr
, 0));
988 pout("Creating /dev/megadev0 = %d\n", n1
>= 0 ? 0 : errno
);
989 if (n1
>= 0 || errno
== EEXIST
)
995 /* Open Device IOCTL node */
996 if ((m_fd
= ::open("/dev/megaraid_sas_ioctl_node", O_RDWR
)) >= 0) {
997 pt_cmd
= &linux_megaraid_device::megasas_cmd
;
999 else if ((m_fd
= ::open("/dev/megadev0", O_RDWR
)) >= 0) {
1000 pt_cmd
= &linux_megaraid_device::megadev_cmd
;
1004 linux_smart_device::close();
1005 return set_err(err
, "cannot open /dev/megaraid_sas_ioctl_node or /dev/megadev0");
1011 bool linux_megaraid_device::close()
1015 m_fd
= -1; m_hba
= 0; pt_cmd
= 0;
1016 return linux_smart_device::close();
1019 bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io
*iop
)
1021 int report
= scsi_debugmode
;
1025 const unsigned char * ucp
= iop
->cmnd
;
1028 const int sz
= (int)sizeof(buff
);
1030 np
= scsi_get_opcode_name(ucp
[0]);
1031 j
= snprintf(buff
, sz
, " [%s: ", np
? np
: "<unknown opcode>");
1032 for (k
= 0; k
< (int)iop
->cmnd_len
; ++k
)
1033 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "%02x ", ucp
[k
]);
1035 (DXFER_TO_DEVICE
== iop
->dxfer_dir
) && (iop
->dxferp
)) {
1036 int trunc
= (iop
->dxfer_len
> 256) ? 1 : 0;
1038 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n Outgoing "
1039 "data, len=%d%s:\n", (int)iop
->dxfer_len
,
1040 (trunc
? " [only first 256 bytes shown]" : ""));
1041 dStrHex((const char *)iop
->dxferp
,
1042 (trunc
? 256 : iop
->dxfer_len
) , 1);
1045 j
+= snprintf(&buff
[j
], (sz
> j
? (sz
- j
) : 0), "]\n");
1049 // Controller rejects Test Unit Ready
1050 if (iop
->cmnd
[0] == 0x00)
1053 if (iop
->cmnd
[0] == 0xa1 || iop
->cmnd
[0] == 0x85) { // SAT_ATA_PASSTHROUGH_12/16
1054 // Controller does not return ATA output registers in SAT sense data
1055 if (iop
->cmnd
[2] & (1 << 5)) // chk_cond
1056 return set_err(ENOSYS
, "ATA return descriptor not supported by controller firmware");
1061 return (this->*pt_cmd
)(iop
->cmnd_len
, iop
->cmnd
,
1062 iop
->dxfer_len
, iop
->dxferp
,
1063 iop
->max_sense_len
, iop
->sensep
, report
);
1066 /* Issue passthrough scsi command to PERC5/6 controllers */
1067 bool linux_megaraid_device::megasas_cmd(int cdbLen
, void *cdb
,
1068 int dataLen
, void *data
,
1069 int /*senseLen*/, void * /*sense*/, int /*report*/)
1071 struct megasas_pthru_frame
*pthru
;
1072 struct megasas_iocpacket uio
;
1075 memset(&uio
, 0, sizeof(uio
));
1076 pthru
= &uio
.frame
.pthru
;
1077 pthru
->cmd
= MFI_CMD_PD_SCSI_IO
;
1078 pthru
->cmd_status
= 0xFF;
1079 pthru
->scsi_status
= 0x0;
1080 pthru
->target_id
= m_disknum
;
1082 pthru
->cdb_len
= cdbLen
;
1084 pthru
->flags
= MFI_FRAME_DIR_READ
;
1086 pthru
->sge_count
= 1;
1087 pthru
->data_xfer_len
= dataLen
;
1088 pthru
->sgl
.sge32
[0].phys_addr
= (intptr_t)data
;
1089 pthru
->sgl
.sge32
[0].length
= (uint32_t)dataLen
;
1091 memcpy(pthru
->cdb
, cdb
, cdbLen
);
1093 uio
.host_no
= m_hba
;
1096 uio
.sgl_off
= offsetof(struct megasas_pthru_frame
, sgl
);
1097 uio
.sgl
[0].iov_base
= data
;
1098 uio
.sgl
[0].iov_len
= dataLen
;
1103 rc
= ioctl(m_fd
, MEGASAS_IOC_FIRMWARE
, &uio
);
1104 if (pthru
->cmd_status
|| rc
!= 0) {
1105 if (pthru
->cmd_status
== 12) {
1106 return set_err(EIO
, "megasas_cmd: Device %d does not exist\n", m_disknum
);
1108 return set_err((errno
? errno
: EIO
), "megasas_cmd result: %d.%d = %d/%d",
1109 m_hba
, m_disknum
, errno
,
1115 /* Issue passthrough scsi commands to PERC2/3/4 controllers */
1116 bool linux_megaraid_device::megadev_cmd(int cdbLen
, void *cdb
,
1117 int dataLen
, void *data
,
1118 int senseLen
, void *sense
, int /*report*/)
1120 struct uioctl_t uio
;
1126 /* Don't issue to the controller */
1130 memset(&uio
, 0, sizeof(uio
));
1131 uio
.inlen
= dataLen
;
1132 uio
.outlen
= dataLen
;
1134 memset(data
, 0, dataLen
);
1135 uio
.ui
.fcs
.opcode
= 0x80; // M_RD_IOCTL_CMD
1136 uio
.ui
.fcs
.adapno
= MKADAP(m_hba
);
1138 uio
.data
.pointer
= (uint8_t *)data
;
1140 uio
.mbox
.cmd
= MEGA_MBOXCMD_PASSTHRU
;
1141 uio
.mbox
.xferaddr
= (intptr_t)&uio
.pthru
;
1144 uio
.pthru
.timeout
= 2;
1145 uio
.pthru
.channel
= 0;
1146 uio
.pthru
.target
= m_disknum
;
1147 uio
.pthru
.cdblen
= cdbLen
;
1148 uio
.pthru
.reqsenselen
= MAX_REQ_SENSE_LEN
;
1149 uio
.pthru
.dataxferaddr
= (intptr_t)data
;
1150 uio
.pthru
.dataxferlen
= dataLen
;
1151 memcpy(uio
.pthru
.cdb
, cdb
, cdbLen
);
1153 rc
=ioctl(m_fd
, MEGAIOCCMD
, &uio
);
1154 if (uio
.pthru
.scsistatus
|| rc
!= 0) {
1155 return set_err((errno
? errno
: EIO
), "megadev_cmd result: %d.%d = %d/%d",
1156 m_hba
, m_disknum
, errno
,
1157 uio
.pthru
.scsistatus
);
1162 /////////////////////////////////////////////////////////////////////////////
1163 /// CCISS RAID support
1165 #ifdef HAVE_LINUX_CCISS_IOCTL_H
1167 class linux_cciss_device
1168 : public /*implements*/ scsi_device
,
1169 public /*extends*/ linux_smart_device
1172 linux_cciss_device(smart_interface
* intf
, const char * name
, unsigned char disknum
);
1174 virtual bool scsi_pass_through(scsi_cmnd_io
* iop
);
1177 unsigned char m_disknum
; ///< Disk number.
1180 linux_cciss_device::linux_cciss_device(smart_interface
* intf
,
1181 const char * dev_name
, unsigned char disknum
)
1182 : smart_device(intf
, dev_name
, "cciss", "cciss"),
1183 linux_smart_device(O_RDWR
| O_NONBLOCK
),
1186 set_info().info_name
= strprintf("%s [cciss_disk_%02d]", dev_name
, disknum
);
1189 bool linux_cciss_device::scsi_pass_through(scsi_cmnd_io
* iop
)
1191 int status
= cciss_io_interface(get_fd(), m_disknum
, iop
, scsi_debugmode
);
1193 return set_err(-status
);
1197 #endif // HAVE_LINUX_CCISS_IOCTL_H
1199 /////////////////////////////////////////////////////////////////////////////
1200 /// AMCC/3ware RAID support
1202 class linux_escalade_device
1203 : public /*implements*/ ata_device
,
1204 public /*extends*/ linux_smart_device
1207 enum escalade_type_t
{
1209 AMCC_3WARE_678K_CHAR
,
1210 AMCC_3WARE_9000_CHAR
,
1211 AMCC_3WARE_9700_CHAR
1214 linux_escalade_device(smart_interface
* intf
, const char * dev_name
,
1215 escalade_type_t escalade_type
, int disknum
);
1217 virtual bool open();
1219 virtual bool ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
);
1222 escalade_type_t m_escalade_type
; ///< Controller type
1223 int m_disknum
; ///< Disk number.
1226 linux_escalade_device::linux_escalade_device(smart_interface
* intf
, const char * dev_name
,
1227 escalade_type_t escalade_type
, int disknum
)
1228 : smart_device(intf
, dev_name
, "3ware", "3ware"),
1229 linux_smart_device(O_RDONLY
| O_NONBLOCK
),
1230 m_escalade_type(escalade_type
), m_disknum(disknum
)
1232 set_info().info_name
= strprintf("%s [3ware_disk_%02d]", dev_name
, disknum
);
1235 /* This function will setup and fix device nodes for a 3ware controller. */
1236 #define MAJOR_STRING_LENGTH 3
1237 #define DEVICE_STRING_LENGTH 32
1238 #define NODE_STRING_LENGTH 16
1239 static int setup_3ware_nodes(const char *nodename
, const char *driver_name
)
1243 char majorstring
[MAJOR_STRING_LENGTH
+1];
1244 char device_name
[DEVICE_STRING_LENGTH
+1];
1245 char nodestring
[NODE_STRING_LENGTH
];
1246 struct stat stat_buf
;
1250 security_context_t orig_context
= NULL
;
1251 security_context_t node_context
= NULL
;
1252 int selinux_enabled
= is_selinux_enabled();
1253 int selinux_enforced
= security_getenforce();
1257 /* First try to open up /proc/devices */
1258 if (!(file
= fopen("/proc/devices", "r"))) {
1259 pout("Error opening /proc/devices to check/create 3ware device nodes\n");
1261 return 0; // don't fail here: user might not have /proc !
1264 /* Attempt to get device major number */
1265 while (EOF
!= fscanf(file
, "%3s %32s", majorstring
, device_name
)) {
1266 majorstring
[MAJOR_STRING_LENGTH
]='\0';
1267 device_name
[DEVICE_STRING_LENGTH
]='\0';
1268 if (!strncmp(device_name
, nodename
, DEVICE_STRING_LENGTH
)) {
1269 tw_major
= atoi(majorstring
);
1275 /* See if we found a major device number */
1277 pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename
, driver_name
);
1281 /* Prepare a database of contexts for files in /dev
1282 * and save the current context */
1283 if (selinux_enabled
) {
1284 if (matchpathcon_init_prefix(NULL
, "/dev") < 0)
1285 pout("Error initializing contexts database for /dev");
1286 if (getfscreatecon(&orig_context
) < 0) {
1287 pout("Error retrieving original SELinux fscreate context");
1288 if (selinux_enforced
)
1289 matchpathcon_fini();
1294 /* Now check if nodes are correct */
1295 for (index
=0; index
<16; index
++) {
1296 sprintf(nodestring
, "/dev/%s%d", nodename
, index
);
1298 /* Get context of the node and set it as the default */
1299 if (selinux_enabled
) {
1300 if (matchpathcon(nodestring
, S_IRUSR
| S_IWUSR
, &node_context
) < 0) {
1301 pout("Could not retrieve context for %s", nodestring
);
1302 if (selinux_enforced
) {
1307 if (setfscreatecon(node_context
) < 0) {
1308 pout ("Error setting default fscreate context");
1309 if (selinux_enforced
) {
1316 /* Try to stat the node */
1317 if ((stat(nodestring
, &stat_buf
))) {
1318 pout("Node %s does not exist and must be created. Check the udev rules.\n", nodestring
);
1319 /* Create a new node if it doesn't exist */
1320 if (mknod(nodestring
, S_IFCHR
|0600, makedev(tw_major
, index
))) {
1321 pout("problem creating 3ware device nodes %s", nodestring
);
1327 if (selinux_enabled
&& node_context
) {
1328 freecon(node_context
);
1329 node_context
= NULL
;
1336 /* See if nodes major and minor numbers are correct */
1337 if ((tw_major
!= (int)(major(stat_buf
.st_rdev
))) ||
1338 (index
!= (int)(minor(stat_buf
.st_rdev
))) ||
1339 (!S_ISCHR(stat_buf
.st_mode
))) {
1340 pout("Node %s has wrong major/minor number and must be created anew."
1341 " Check the udev rules.\n", nodestring
);
1342 /* Delete the old node */
1343 if (unlink(nodestring
)) {
1344 pout("problem unlinking stale 3ware device node %s", nodestring
);
1350 /* Make a new node */
1351 if (mknod(nodestring
, S_IFCHR
|0600, makedev(tw_major
, index
))) {
1352 pout("problem creating 3ware device nodes %s", nodestring
);
1359 if (selinux_enabled
&& node_context
) {
1360 freecon(node_context
);
1361 node_context
= NULL
;
1367 if (selinux_enabled
) {
1368 if(setfscreatecon(orig_context
) < 0) {
1369 pout("Error re-setting original fscreate context");
1370 if (selinux_enforced
)
1374 freecon(orig_context
);
1376 freecon(node_context
);
1377 matchpathcon_fini();
1383 bool linux_escalade_device::open()
1385 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
||
1386 m_escalade_type
== AMCC_3WARE_678K_CHAR
) {
1387 // the device nodes for these controllers are dynamically assigned,
1388 // so we need to check that they exist with the correct major
1389 // numbers and if not, create them
1390 const char * node
= (m_escalade_type
== AMCC_3WARE_9700_CHAR
? "twl" :
1391 m_escalade_type
== AMCC_3WARE_9000_CHAR
? "twa" :
1393 const char * driver
= (m_escalade_type
== AMCC_3WARE_9700_CHAR
? "3w-sas" :
1394 m_escalade_type
== AMCC_3WARE_9000_CHAR
? "3w-9xxx" :
1396 if (setup_3ware_nodes(node
, driver
))
1397 return set_err((errno
? errno
: ENXIO
), "setup_3ware_nodes(\"%s\", \"%s\") failed", node
, driver
);
1399 // Continue with default open
1400 return linux_smart_device::open();
1403 // TODO: Function no longer useful
1404 //void printwarning(smart_command_set command);
1407 // This is an interface routine meant to isolate the OS dependent
1408 // parts of the code, and to provide a debugging interface. Each
1409 // different port and OS needs to provide it's own interface. This
1410 // is the linux interface to the 3ware 3w-xxxx driver. It allows ATA
1411 // commands to be passed through the SCSI driver.
1412 // DETAILED DESCRIPTION OF ARGUMENTS
1413 // fd: is the file descriptor provided by open()
1414 // disknum is the disk number (0 to 15) in the RAID array
1415 // escalade_type indicates the type of controller type, and if scsi or char interface is used
1416 // command: defines the different operations.
1417 // select: additional input data if needed (which log, which type of
1419 // data: location to write output data, if needed (512 bytes).
1420 // Note: not all commands use all arguments.
1422 // -1 if the command failed
1423 // 0 if the command succeeded,
1424 // STATUS_CHECK routine:
1425 // -1 if the command failed
1426 // 0 if the command succeeded and disk SMART status is "OK"
1427 // 1 if the command succeeded and disk SMART status is "FAILING"
1430 /* 512 is the max payload size: increase if needed */
1431 #define BUFFER_LEN_678K ( sizeof(TW_Ioctl) ) // 1044 unpacked, 1041 packed
1432 #define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1 ) // 1539 unpacked, 1536 packed
1433 #define BUFFER_LEN_9000 ( sizeof(TW_Ioctl_Buf_Apache)+512-1 ) // 2051 unpacked, 2048 packed
1434 #define TW_IOCTL_BUFFER_SIZE ( MAX(MAX(BUFFER_LEN_678K, BUFFER_LEN_9000), BUFFER_LEN_678K_CHAR) )
1436 bool linux_escalade_device::ata_pass_through(const ata_cmd_in
& in
, ata_cmd_out
& out
)
1438 if (!ata_cmd_is_ok(in
,
1439 true, // data_out_support
1440 false, // TODO: multi_sector_support
1441 true) // ata_48bit_support
1445 // Used by both the SCSI and char interfaces
1446 TW_Passthru
*passthru
=NULL
;
1447 char ioctl_buffer
[TW_IOCTL_BUFFER_SIZE
];
1449 // only used for SCSI device interface
1450 TW_Ioctl
*tw_ioctl
=NULL
;
1451 TW_Output
*tw_output
=NULL
;
1453 // only used for 6000/7000/8000 char device interface
1454 TW_New_Ioctl
*tw_ioctl_char
=NULL
;
1456 // only used for 9000 character device interface
1457 TW_Ioctl_Buf_Apache
*tw_ioctl_apache
=NULL
;
1459 memset(ioctl_buffer
, 0, TW_IOCTL_BUFFER_SIZE
);
1461 // TODO: Handle controller differences by different classes
1462 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
) {
1463 tw_ioctl_apache
= (TW_Ioctl_Buf_Apache
*)ioctl_buffer
;
1464 tw_ioctl_apache
->driver_command
.control_code
= TW_IOCTL_FIRMWARE_PASS_THROUGH
;
1465 tw_ioctl_apache
->driver_command
.buffer_length
= 512; /* payload size */
1466 passthru
= (TW_Passthru
*)&(tw_ioctl_apache
->firmware_command
.command
.oldcommand
);
1468 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
) {
1469 tw_ioctl_char
= (TW_New_Ioctl
*)ioctl_buffer
;
1470 tw_ioctl_char
->data_buffer_length
= 512;
1471 passthru
= (TW_Passthru
*)&(tw_ioctl_char
->firmware_command
);
1473 else if (m_escalade_type
==AMCC_3WARE_678K
) {
1474 tw_ioctl
= (TW_Ioctl
*)ioctl_buffer
;
1475 tw_ioctl
->cdb
[0] = TW_IOCTL
;
1476 tw_ioctl
->opcode
= TW_ATA_PASSTHRU
;
1477 tw_ioctl
->input_length
= 512; // correct even for non-data commands
1478 tw_ioctl
->output_length
= 512; // correct even for non-data commands
1479 tw_output
= (TW_Output
*)tw_ioctl
;
1480 passthru
= (TW_Passthru
*)&(tw_ioctl
->input_data
);
1483 return set_err(ENOSYS
,
1484 "Unrecognized escalade_type %d in linux_3ware_command_interface(disk %d)\n"
1485 "Please contact " PACKAGE_BUGREPORT
"\n", (int)m_escalade_type
, m_disknum
);
1488 // Same for (almost) all commands - but some reset below
1489 passthru
->byte0
.opcode
= TW_OP_ATA_PASSTHRU
;
1490 passthru
->request_id
= 0xFF;
1491 passthru
->unit
= m_disknum
;
1492 passthru
->status
= 0;
1493 passthru
->flags
= 0x1;
1497 const ata_in_regs_48bit
& r
= in
.in_regs
;
1498 passthru
->features
= r
.features_16
;
1499 passthru
->sector_count
= r
.sector_count_16
;
1500 passthru
->sector_num
= r
.lba_low_16
;
1501 passthru
->cylinder_lo
= r
.lba_mid_16
;
1502 passthru
->cylinder_hi
= r
.lba_high_16
;
1503 passthru
->drive_head
= r
.device
;
1504 passthru
->command
= r
.command
;
1507 // Is this a command that reads or returns 512 bytes?
1508 // passthru->param values are:
1509 // 0x0 - non data command without TFR write check,
1510 // 0x8 - non data command with TFR write check,
1511 // 0xD - data command that returns data to host from device
1512 // 0xF - data command that writes data from host to device
1513 // passthru->size values are 0x5 for non-data and 0x07 for data
1514 bool readdata
= false;
1515 if (in
.direction
== ata_cmd_in::data_in
) {
1517 passthru
->byte0
.sgloff
= 0x5;
1518 passthru
->size
= 0x7; // TODO: Other value for multi-sector ?
1519 passthru
->param
= 0xD;
1520 // For 64-bit to work correctly, up the size of the command packet
1521 // in dwords by 1 to account for the 64-bit single sgl 'address'
1522 // field. Note that this doesn't agree with the typedefs but it's
1523 // right (agree with kernel driver behavior/typedefs).
1524 if ((m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1525 && sizeof(long) == 8)
1528 else if (in
.direction
== ata_cmd_in::no_data
) {
1529 // Non data command -- but doesn't use large sector
1530 // count register values.
1531 passthru
->byte0
.sgloff
= 0x0;
1532 passthru
->size
= 0x5;
1533 passthru
->param
= 0x8;
1534 passthru
->sector_count
= 0x0;
1536 else if (in
.direction
== ata_cmd_in::data_out
) {
1537 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1538 memcpy(tw_ioctl_apache
->data_buffer
, in
.buffer
, in
.size
);
1539 else if (m_escalade_type
== AMCC_3WARE_678K_CHAR
)
1540 memcpy(tw_ioctl_char
->data_buffer
, in
.buffer
, in
.size
);
1542 // COMMAND NOT SUPPORTED VIA SCSI IOCTL INTERFACE
1543 // memcpy(tw_output->output_data, data, 512);
1544 // printwarning(command); // TODO: Parameter no longer valid
1545 return set_err(ENOTSUP
, "DATA OUT not supported for this 3ware controller type");
1547 passthru
->byte0
.sgloff
= 0x5;
1548 passthru
->size
= 0x7; // TODO: Other value for multi-sector ?
1549 passthru
->param
= 0xF; // PIO data write
1550 if ((m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1551 && sizeof(long) == 8)
1555 return set_err(EINVAL
);
1557 // Now send the command down through an ioctl()
1559 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1560 ioctlreturn
=ioctl(get_fd(), TW_IOCTL_FIRMWARE_PASS_THROUGH
, tw_ioctl_apache
);
1561 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
)
1562 ioctlreturn
=ioctl(get_fd(), TW_CMD_PACKET_WITH_DATA
, tw_ioctl_char
);
1564 ioctlreturn
=ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND
, tw_ioctl
);
1566 // Deal with the different error cases
1568 if (AMCC_3WARE_678K
==m_escalade_type
1569 && in
.in_regs
.command
==ATA_SMART_CMD
1570 && ( in
.in_regs
.features
== ATA_SMART_AUTO_OFFLINE
1571 || in
.in_regs
.features
== ATA_SMART_AUTOSAVE
)
1572 && in
.in_regs
.lba_low
) {
1573 // error here is probably a kernel driver whose version is too old
1574 // printwarning(command); // TODO: Parameter no longer valid
1575 return set_err(ENOTSUP
, "Probably kernel driver too old");
1577 return set_err(EIO
);
1580 // The passthru structure is valid after return from an ioctl if:
1581 // - we are using the character interface OR
1582 // - we are using the SCSI interface and this is a NON-READ-DATA command
1583 // For SCSI interface, note that we set passthru to a different
1584 // value after ioctl().
1585 if (AMCC_3WARE_678K
==m_escalade_type
) {
1589 passthru
=(TW_Passthru
*)&(tw_output
->output_data
);
1592 // See if the ATA command failed. Now that we have returned from
1593 // the ioctl() call, if passthru is valid, then:
1594 // - passthru->status contains the 3ware controller STATUS
1595 // - passthru->command contains the ATA STATUS register
1596 // - passthru->features contains the ATA ERROR register
1598 // Check bits 0 (error bit) and 5 (device fault) of the ATA STATUS
1599 // If bit 0 (error bit) is set, then ATA ERROR register is valid.
1600 // While we *might* decode the ATA ERROR register, at the moment it
1601 // doesn't make much sense: we don't care in detail why the error
1604 if (passthru
&& (passthru
->status
|| (passthru
->command
& 0x21))) {
1605 return set_err(EIO
);
1608 // If this is a read data command, copy data to output buffer
1610 if (m_escalade_type
== AMCC_3WARE_9700_CHAR
|| m_escalade_type
== AMCC_3WARE_9000_CHAR
)
1611 memcpy(in
.buffer
, tw_ioctl_apache
->data_buffer
, in
.size
);
1612 else if (m_escalade_type
==AMCC_3WARE_678K_CHAR
)
1613 memcpy(in
.buffer
, tw_ioctl_char
->data_buffer
, in
.size
);
1615 memcpy(in
.buffer
, tw_output
->output_data
, in
.size
);
1618 // Return register values
1620 ata_out_regs_48bit
& r
= out
.out_regs
;
1621 r
.error
= passthru
->features
;
1622 r
.sector_count_16
= passthru
->sector_count
;
1623 r
.lba_low_16
= passthru
->sector_num
;
1624 r
.lba_mid_16
= passthru
->cylinder_lo
;
1625 r
.lba_high_16
= passthru
->cylinder_hi
;
1626 r
.device
= passthru
->drive_head
;
1627 r
.status
= passthru
->command
;
1630 // look for nonexistent devices/ports
1631 if ( in
.in_regs
.command
== ATA_IDENTIFY_DEVICE
1632 && !nonempty(in
.buffer
, in
.size
)) {
1633 return set_err(ENODEV
, "No drive on port %d", m_disknum
);
1640 /////////////////////////////////////////////////////////////////////////////
1641 /// Areca RAID support
1643 class linux_areca_device
1644 : public /*implements*/ ata_device_with_command_set
,
1645 public /*extends*/ linux_smart_device
1648 linux_areca_device(smart_interface
* intf
, const char * dev_name
, int disknum
);
1651 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
1654 int m_disknum
; ///< Disk number.
1659 // This is an interface routine meant to isolate the OS dependent
1660 // parts of the code, and to provide a debugging interface. Each
1661 // different port and OS needs to provide it's own interface. This
1662 // is the linux interface to the Areca "arcmsr" driver. It allows ATA
1663 // commands to be passed through the SCSI driver.
1664 // DETAILED DESCRIPTION OF ARGUMENTS
1665 // fd: is the file descriptor provided by open()
1666 // disknum is the disk number (0 to 15) in the RAID array
1667 // command: defines the different operations.
1668 // select: additional input data if needed (which log, which type of
1670 // data: location to write output data, if needed (512 bytes).
1671 // Note: not all commands use all arguments.
1673 // -1 if the command failed
1674 // 0 if the command succeeded,
1675 // STATUS_CHECK routine:
1676 // -1 if the command failed
1677 // 0 if the command succeeded and disk SMART status is "OK"
1678 // 1 if the command succeeded and disk SMART status is "FAILING"
1682 #define ARECA_SATA_RAID 0x90000000
1684 #define FUNCTION_READ_RQBUFFER 0x0801
1685 #define FUNCTION_WRITE_WQBUFFER 0x0802
1686 #define FUNCTION_CLEAR_RQBUFFER 0x0803
1687 #define FUNCTION_CLEAR_WQBUFFER 0x0804
1689 /* ARECA IO CONTROL CODE*/
1690 #define ARCMSR_IOCTL_READ_RQBUFFER (ARECA_SATA_RAID | FUNCTION_READ_RQBUFFER)
1691 #define ARCMSR_IOCTL_WRITE_WQBUFFER (ARECA_SATA_RAID | FUNCTION_WRITE_WQBUFFER)
1692 #define ARCMSR_IOCTL_CLEAR_RQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_RQBUFFER)
1693 #define ARCMSR_IOCTL_CLEAR_WQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_WQBUFFER)
1694 #define ARECA_SIG_STR "ARCMSR"
1696 // The SRB_IO_CONTROL & SRB_BUFFER structures are used to communicate(to/from) to areca driver
1697 typedef struct _SRB_IO_CONTROL
1699 unsigned int HeaderLength
;
1700 unsigned char Signature
[8];
1701 unsigned int Timeout
;
1702 unsigned int ControlCode
;
1703 unsigned int ReturnCode
;
1704 unsigned int Length
;
1707 typedef struct _SRB_BUFFER
1709 sSRB_IO_CONTROL srbioctl
;
1710 unsigned char ioctldatabuffer
[1032]; // the buffer to put the command data to/from firmware
1713 // Looks in /proc/scsi to suggest correct areca devices
1714 // If hint not NULL, return device path guess
1715 static int find_areca_in_proc(char *hint
)
1717 const char* proc_format_string
="host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n";
1719 // check data formwat
1720 FILE *fp
=fopen("/proc/scsi/sg/device_hdr", "r");
1722 pout("Unable to open /proc/scsi/sg/device_hdr for reading\n");
1726 // get line, compare to format
1729 char *out
= fgets(linebuf
, 256, fp
);
1732 pout("Unable to read contents of /proc/scsi/sg/device_hdr\n");
1736 if (strcmp(linebuf
, proc_format_string
)) {
1738 // Fix this by comparing only tokens not white space!!
1739 pout("Unexpected format %s in /proc/scsi/sg/device_hdr\n", proc_format_string
);
1743 // Format is understood, now search for correct device
1744 fp
=fopen("/proc/scsi/sg/devices", "r");
1746 int host
, chan
, id
, lun
, type
, opens
, qdepth
, busy
, online
;
1749 // search all lines of /proc/scsi/sg/devices
1750 while (9 == fscanf(fp
, "%d %d %d %d %d %d %d %d %d", &host
, &chan
, &id
, &lun
, &type
, &opens
, &qdepth
, &busy
, &online
)) {
1752 if (id
== 16 && type
== 3) {
1753 // devices with id=16 and type=3 might be Areca controllers
1754 if (!found
&& hint
) {
1755 sprintf(hint
, "/dev/sg%d", dev
);
1757 pout("Device /dev/sg%d appears to be an Areca controller.\n", dev
);
1766 #if 0 // For debugging areca code
1768 static void dumpdata(unsigned char *block
, int len
)
1770 int ln
= (len
/ 16) + 1; // total line#
1774 printf(" Address = %p, Length = (0x%x)%d\n", block
, len
, len
);
1775 printf(" 0 1 2 3 4 5 6 7 8 9 A B C D E F ASCII \n");
1776 printf("=====================================================================\n");
1778 for ( int l
= 0; l
< ln
&& len
; l
++ )
1780 // printf the line# and the HEX data
1781 // if a line data length < 16 then append the space to the tail of line to reach 16 chars
1782 printf("%02X | ", l
);
1783 for ( pos
= 0; pos
< 16 && len
; pos
++, len
-- )
1785 c
= block
[l
*16+pos
];
1791 for ( int loop
= pos
; loop
< 16; loop
++ )
1798 for ( int loop
= 0; loop
< pos
; loop
++ )
1800 c
= block
[l
*16+loop
];
1801 if ( c
>= 0x20 && c
<= 0x7F )
1812 printf("=====================================================================\n");
1817 static int arcmsr_command_handler(int fd
, unsigned long arcmsr_cmd
, unsigned char *data
, int data_len
, void *ext_data
/* reserved for further use */)
1821 int ioctlreturn
= 0;
1823 struct scsi_cmnd_io io_hdr
;
1824 int dir
= DXFER_TO_DEVICE
;
1829 unsigned char *areca_return_packet
;
1832 unsigned char return_buff
[2048];
1833 unsigned char *ptr
= &return_buff
[0];
1834 memset(return_buff
, 0, sizeof(return_buff
));
1836 memset((unsigned char *)&sBuf
, 0, sizeof(sBuf
));
1837 memset(&io_hdr
, 0, sizeof(io_hdr
));
1838 memset(cdb
, 0, sizeof(cdb
));
1839 memset(sense
, 0, sizeof(sense
));
1842 sBuf
.srbioctl
.HeaderLength
= sizeof(sSRB_IO_CONTROL
);
1843 memcpy(sBuf
.srbioctl
.Signature
, ARECA_SIG_STR
, strlen(ARECA_SIG_STR
));
1844 sBuf
.srbioctl
.Timeout
= 10000;
1845 sBuf
.srbioctl
.ControlCode
= ARCMSR_IOCTL_READ_RQBUFFER
;
1847 switch ( arcmsr_cmd
)
1849 // command for writing data to driver
1850 case ARCMSR_IOCTL_WRITE_WQBUFFER
:
1851 if ( data
&& data_len
)
1853 sBuf
.srbioctl
.Length
= data_len
;
1854 memcpy((unsigned char *)sBuf
.ioctldatabuffer
, (unsigned char *)data
, data_len
);
1856 // commands for clearing related buffer of driver
1857 case ARCMSR_IOCTL_CLEAR_RQBUFFER
:
1858 case ARCMSR_IOCTL_CLEAR_WQBUFFER
:
1859 cdb
[0] = 0x3B; //SCSI_WRITE_BUF command;
1861 // command for reading data from driver
1862 case ARCMSR_IOCTL_READ_RQBUFFER
:
1863 cdb
[0] = 0x3C; //SCSI_READ_BUF command;
1864 dir
= DXFER_FROM_DEVICE
;
1867 // unknown arcmsr commands
1874 // cdb[5][6][7][8] areca defined command code( to/from driver )
1876 cdb
[5] = (char)( arcmsr_cmd
>> 24);
1877 cdb
[6] = (char)( arcmsr_cmd
>> 16);
1878 cdb
[7] = (char)( arcmsr_cmd
>> 8);
1879 cdb
[8] = (char)( arcmsr_cmd
& 0x0F );
1881 io_hdr
.dxfer_dir
= dir
;
1882 io_hdr
.dxfer_len
= sizeof(sBuf
);
1883 io_hdr
.dxferp
= (unsigned char *)&sBuf
;
1885 io_hdr
.cmnd_len
= sizeof(cdb
);
1886 io_hdr
.sensep
= sense
;
1887 io_hdr
.max_sense_len
= sizeof(sense
);
1888 io_hdr
.timeout
= SCSI_TIMEOUT_DEFAULT
;
1892 ioctlreturn
= do_normal_scsi_cmnd_io(fd
, &io_hdr
, 0);
1893 if ( ioctlreturn
|| io_hdr
.scsi_status
)
1899 if ( arcmsr_cmd
!= ARCMSR_IOCTL_READ_RQBUFFER
)
1901 // if succeeded, just returns the length of outgoing data
1905 if ( sBuf
.srbioctl
.Length
)
1907 //dumpdata(&sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
1908 memcpy(ptr
, &sBuf
.ioctldatabuffer
[0], sBuf
.srbioctl
.Length
);
1909 ptr
+= sBuf
.srbioctl
.Length
;
1910 total
+= sBuf
.srbioctl
.Length
;
1911 // the returned bytes enough to compute payload length ?
1912 if ( expected
< 0 && total
>= 5 )
1914 areca_return_packet
= (unsigned char *)&return_buff
[0];
1915 if ( areca_return_packet
[0] == 0x5E &&
1916 areca_return_packet
[1] == 0x01 &&
1917 areca_return_packet
[2] == 0x61 )
1919 // valid header, let's compute the returned payload length,
1920 // we expected the total length is
1921 // payload + 3 bytes header + 2 bytes length + 1 byte checksum
1922 expected
= areca_return_packet
[4] * 256 + areca_return_packet
[3] + 6;
1926 if ( total
>= 7 && total
>= expected
)
1928 //printf("total bytes received = %d, expected length = %d\n", total, expected);
1930 // ------ Okay! we received enough --------
1936 // Deal with the different error cases
1939 pout("do_scsi_cmnd_io with write buffer failed code = %x\n", ioctlreturn
);
1944 if ( io_hdr
.scsi_status
)
1946 pout("io_hdr.scsi_status with write buffer failed code = %x\n", io_hdr
.scsi_status
);
1953 memcpy(data
, return_buff
, total
);
1960 linux_areca_device::linux_areca_device(smart_interface
* intf
, const char * dev_name
, int disknum
)
1961 : smart_device(intf
, dev_name
, "areca", "areca"),
1962 linux_smart_device(O_RDWR
| O_EXCL
| O_NONBLOCK
),
1965 set_info().info_name
= strprintf("%s [areca_%02d]", dev_name
, disknum
);
1968 // Areca RAID Controller
1969 int linux_areca_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
1971 // ATA input registers
1972 typedef struct _ATA_INPUT_REGISTERS
1974 unsigned char features
;
1975 unsigned char sector_count
;
1976 unsigned char sector_number
;
1977 unsigned char cylinder_low
;
1978 unsigned char cylinder_high
;
1979 unsigned char device_head
;
1980 unsigned char command
;
1981 unsigned char reserved
[8];
1982 unsigned char data
[512]; // [in/out] buffer for outgoing/incoming data
1983 } sATA_INPUT_REGISTERS
;
1985 // ATA output registers
1986 // Note: The output registers is re-sorted for areca internal use only
1987 typedef struct _ATA_OUTPUT_REGISTERS
1989 unsigned char error
;
1990 unsigned char status
;
1991 unsigned char sector_count
;
1992 unsigned char sector_number
;
1993 unsigned char cylinder_low
;
1994 unsigned char cylinder_high
;
1995 }sATA_OUTPUT_REGISTERS
;
1997 // Areca packet format for outgoing:
1998 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
1999 // B[3~4] : 2 bytes command length + variant data length, little endian
2000 // B[5] : 1 bytes areca defined command code, ATA passthrough command code is 0x1c
2001 // B[6~last-1] : variant bytes payload data
2002 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
2005 // header 3 bytes length 2 bytes cmd 1 byte payload data x bytes cs 1 byte
2006 // +--------------------------------------------------------------------------------+
2007 // + 0x5E 0x01 0x61 | 0x00 0x00 | 0x1c | .................... | 0x00 |
2008 // +--------------------------------------------------------------------------------+
2011 //Areca packet format for incoming:
2012 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
2013 // B[3~4] : 2 bytes payload length, little endian
2014 // B[5~last-1] : variant bytes returned payload data
2015 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
2018 // header 3 bytes length 2 bytes payload data x bytes cs 1 byte
2019 // +-------------------------------------------------------------------+
2020 // + 0x5E 0x01 0x61 | 0x00 0x00 | .................... | 0x00 |
2021 // +-------------------------------------------------------------------+
2022 unsigned char areca_packet
[640];
2023 int areca_packet_len
= sizeof(areca_packet
);
2024 unsigned char cs
= 0;
2026 sATA_INPUT_REGISTERS
*ata_cmd
;
2030 memset(sInq
, 0, sizeof(sInq
));
2031 scsiStdInquiry(fd
, (unsigned char *)sInq
, (int)sizeof(sInq
));
2032 dumpdata((unsigned char *)sInq
, sizeof(sInq
));
2034 memset(areca_packet
, 0, areca_packet_len
);
2036 // ----- BEGIN TO SETUP HEADERS -------
2037 areca_packet
[0] = 0x5E;
2038 areca_packet
[1] = 0x01;
2039 areca_packet
[2] = 0x61;
2040 areca_packet
[3] = (unsigned char)((areca_packet_len
- 6) & 0xff);
2041 areca_packet
[4] = (unsigned char)(((areca_packet_len
- 6) >> 8) & 0xff);
2042 areca_packet
[5] = 0x1c; // areca defined code for ATA passthrough command
2045 // ----- BEGIN TO SETUP PAYLOAD DATA -----
2047 memcpy(&areca_packet
[7], "SmrT", 4); // areca defined password
2049 ata_cmd
= (sATA_INPUT_REGISTERS
*)&areca_packet
[12];
2050 ata_cmd
->cylinder_low
= 0x4F;
2051 ata_cmd
->cylinder_high
= 0xC2;
2054 if ( command
== READ_VALUES
||
2055 command
== READ_THRESHOLDS
||
2056 command
== READ_LOG
||
2057 command
== IDENTIFY
||
2058 command
== PIDENTIFY
)
2060 // the commands will return data
2061 areca_packet
[6] = 0x13;
2062 ata_cmd
->sector_count
= 0x1;
2064 else if ( command
== WRITE_LOG
)
2066 // the commands will write data
2067 areca_packet
[6] = 0x14;
2071 // the commands will return no data
2072 areca_packet
[6] = 0x15;
2076 ata_cmd
->command
= ATA_SMART_CMD
;
2077 // Now set ATA registers depending upon command
2080 case CHECK_POWER_MODE
:
2081 //printf("command = CHECK_POWER_MODE\n");
2082 ata_cmd
->command
= ATA_CHECK_POWER_MODE
;
2085 //printf("command = READ_VALUES\n");
2086 ata_cmd
->features
= ATA_SMART_READ_VALUES
;
2088 case READ_THRESHOLDS
:
2089 //printf("command = READ_THRESHOLDS\n");
2090 ata_cmd
->features
= ATA_SMART_READ_THRESHOLDS
;
2093 //printf("command = READ_LOG\n");
2094 ata_cmd
->features
= ATA_SMART_READ_LOG_SECTOR
;
2095 ata_cmd
->sector_number
= select
;
2098 //printf("command = WRITE_LOG\n");
2099 ata_cmd
->features
= ATA_SMART_WRITE_LOG_SECTOR
;
2100 memcpy(ata_cmd
->data
, data
, 512);
2101 ata_cmd
->sector_count
= 1;
2102 ata_cmd
->sector_number
= select
;
2105 //printf("command = IDENTIFY\n");
2106 ata_cmd
->command
= ATA_IDENTIFY_DEVICE
;
2109 //printf("command = PIDENTIFY\n");
2113 //printf("command = ENABLE\n");
2114 ata_cmd
->features
= ATA_SMART_ENABLE
;
2117 //printf("command = DISABLE\n");
2118 ata_cmd
->features
= ATA_SMART_DISABLE
;
2121 //printf("command = AUTO_OFFLINE\n");
2122 ata_cmd
->features
= ATA_SMART_AUTO_OFFLINE
;
2123 // Enable or disable?
2124 ata_cmd
->sector_count
= select
;
2127 //printf("command = AUTOSAVE\n");
2128 ata_cmd
->features
= ATA_SMART_AUTOSAVE
;
2129 // Enable or disable?
2130 ata_cmd
->sector_count
= select
;
2132 case IMMEDIATE_OFFLINE
:
2133 //printf("command = IMMEDIATE_OFFLINE\n");
2134 ata_cmd
->features
= ATA_SMART_IMMEDIATE_OFFLINE
;
2135 // What test type to run?
2136 ata_cmd
->sector_number
= select
;
2139 //printf("command = STATUS_CHECK\n");
2140 ata_cmd
->features
= ATA_SMART_STATUS
;
2143 //printf("command = STATUS\n");
2144 ata_cmd
->features
= ATA_SMART_STATUS
;
2147 //printf("command = UNKNOWN\n");
2152 areca_packet
[11] = m_disknum
- 1; // drive number
2154 // ----- BEGIN TO SETUP CHECKSUM -----
2155 for ( int loop
= 3; loop
< areca_packet_len
- 1; loop
++ )
2157 cs
+= areca_packet
[loop
];
2159 areca_packet
[areca_packet_len
-1] = cs
;
2161 // ----- BEGIN TO SEND TO ARECA DRIVER ------
2163 unsigned char return_buff
[2048];
2164 memset(return_buff
, 0, sizeof(return_buff
));
2166 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_RQBUFFER
, NULL
, 0, NULL
);
2168 find_areca_in_proc(NULL
);
2172 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_WQBUFFER
, NULL
, 0, NULL
);
2173 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_WRITE_WQBUFFER
, areca_packet
, areca_packet_len
, NULL
);
2176 expected
= arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_READ_RQBUFFER
, return_buff
, sizeof(return_buff
), NULL
);
2183 // ----- VERIFY THE CHECKSUM -----
2185 for ( int loop
= 3; loop
< expected
- 1; loop
++ )
2187 cs
+= return_buff
[loop
];
2190 if ( return_buff
[expected
- 1] != cs
)
2196 sATA_OUTPUT_REGISTERS
*ata_out
= (sATA_OUTPUT_REGISTERS
*)&return_buff
[5] ;
2197 if ( ata_out
->status
)
2199 if ( command
== IDENTIFY
)
2201 pout("The firmware of your Areca RAID controller appears to be outdated!\n" \
2202 "Please update your controller to firmware version 1.46 or later.\n" \
2203 "You may download it here: ftp://ftp.areca.com.tw/RaidCards/BIOS_Firmware\n\n");
2209 // returns with data
2210 if ( command
== READ_VALUES
||
2211 command
== READ_THRESHOLDS
||
2212 command
== READ_LOG
||
2213 command
== IDENTIFY
||
2214 command
== PIDENTIFY
)
2216 memcpy(data
, &return_buff
[7], 512);
2219 if ( command
== CHECK_POWER_MODE
)
2221 data
[0] = ata_out
->sector_count
;
2224 if ( command
== STATUS_CHECK
&&
2225 ( ata_out
->cylinder_low
== 0xF4 && ata_out
->cylinder_high
== 0x2C ) )
2234 /////////////////////////////////////////////////////////////////////////////
2237 class linux_marvell_device
2238 : public /*implements*/ ata_device_with_command_set
,
2239 public /*extends*/ linux_smart_device
2242 linux_marvell_device(smart_interface
* intf
, const char * dev_name
, const char * req_type
);
2245 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2248 linux_marvell_device::linux_marvell_device(smart_interface
* intf
,
2249 const char * dev_name
, const char * req_type
)
2250 : smart_device(intf
, dev_name
, "marvell", req_type
),
2251 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
2255 int linux_marvell_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2264 mvsata_scsi_cmd smart_command
;
2265 unsigned char *buff
= (unsigned char *)&smart_command
.cmd
[6];
2266 // See struct hd_drive_cmd_hdr in hdreg.h
2267 // buff[0]: ATA COMMAND CODE REGISTER
2268 // buff[1]: ATA SECTOR NUMBER REGISTER
2269 // buff[2]: ATA FEATURES REGISTER
2270 // buff[3]: ATA SECTOR COUNT REGISTER
2272 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
2273 memset(&smart_command
, 0, sizeof(smart_command
));
2274 smart_command
.inlen
= 540;
2275 smart_command
.outlen
= 540;
2276 smart_command
.cmd
[0] = 0xC; //Vendor-specific code
2277 smart_command
.cmd
[4] = 6; //command length
2279 buff
[0] = ATA_SMART_CMD
;
2281 case CHECK_POWER_MODE
:
2282 buff
[0]=ATA_CHECK_POWER_MODE
;
2285 buff
[2]=ATA_SMART_READ_VALUES
;
2288 case READ_THRESHOLDS
:
2289 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
2290 copydata
=buff
[1]=buff
[3]=1;
2293 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
2298 buff
[0]=ATA_IDENTIFY_DEVICE
;
2302 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
2306 buff
[2]=ATA_SMART_ENABLE
;
2310 buff
[2]=ATA_SMART_DISABLE
;
2315 // this command only says if SMART is working. It could be
2316 // replaced with STATUS_CHECK below.
2317 buff
[2] = ATA_SMART_STATUS
;
2320 buff
[2]=ATA_SMART_AUTO_OFFLINE
;
2321 buff
[3]=select
; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2324 buff
[2]=ATA_SMART_AUTOSAVE
;
2325 buff
[3]=select
; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2327 case IMMEDIATE_OFFLINE
:
2328 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
2332 pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command
);
2336 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
2338 // We are now doing the HDIO_DRIVE_CMD type ioctl.
2339 if (ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND
, (void *)&smart_command
))
2342 if (command
==CHECK_POWER_MODE
) {
2343 // LEON -- CHECK THIS PLEASE. THIS SHOULD BE THE SECTOR COUNT
2344 // REGISTER, AND IT MIGHT BE buff[2] NOT buff[3]. Bruce
2349 // Always succeed on a SMART status, as a disk that failed returned
2350 // buff[4]=0xF4, buff[5]=0x2C, i.e. "Bad SMART status" (see below).
2351 if (command
== STATUS
)
2353 //Data returned is starting from 0 offset
2354 if (command
== STATUS_CHECK
)
2356 // Cyl low and Cyl high unchanged means "Good SMART status"
2357 if (buff
[4] == 0x4F && buff
[5] == 0xC2)
2359 // These values mean "Bad SMART status"
2360 if (buff
[4] == 0xF4 && buff
[5] == 0x2C)
2362 // We haven't gotten output that makes sense; print out some debugging info
2363 syserror("Error SMART Status command failed");
2364 pout("Please get assistance from %s\n",PACKAGE_BUGREPORT
);
2365 pout("Register values returned from SMART Status command are:\n");
2366 pout("CMD =0x%02x\n",(int)buff
[0]);
2367 pout("FR =0x%02x\n",(int)buff
[1]);
2368 pout("NS =0x%02x\n",(int)buff
[2]);
2369 pout("SC =0x%02x\n",(int)buff
[3]);
2370 pout("CL =0x%02x\n",(int)buff
[4]);
2371 pout("CH =0x%02x\n",(int)buff
[5]);
2372 pout("SEL=0x%02x\n",(int)buff
[6]);
2377 memcpy(data
, buff
, 512);
2382 /////////////////////////////////////////////////////////////////////////////
2383 /// Highpoint RAID support
2385 class linux_highpoint_device
2386 : public /*implements*/ ata_device_with_command_set
,
2387 public /*extends*/ linux_smart_device
2390 linux_highpoint_device(smart_interface
* intf
, const char * dev_name
,
2391 unsigned char controller
, unsigned char channel
, unsigned char port
);
2394 virtual int ata_command_interface(smart_command_set command
, int select
, char * data
);
2397 unsigned char m_hpt_data
[3]; ///< controller/channel/port
2400 linux_highpoint_device::linux_highpoint_device(smart_interface
* intf
, const char * dev_name
,
2401 unsigned char controller
, unsigned char channel
, unsigned char port
)
2402 : smart_device(intf
, dev_name
, "hpt", "hpt"),
2403 linux_smart_device(O_RDONLY
| O_NONBLOCK
)
2405 m_hpt_data
[0] = controller
; m_hpt_data
[1] = channel
; m_hpt_data
[2] = port
;
2406 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]);
2409 // this implementation is derived from ata_command_interface with a header
2410 // packing for highpoint linux driver ioctl interface
2412 // ioctl(fd,HPTIO_CTL,buff)
2415 // structure of hpt_buff
2416 // +----+----+----+----+--------------------.....---------------------+
2417 // | 1 | 2 | 3 | 4 | 5 |
2418 // +----+----+----+----+--------------------.....---------------------+
2420 // 1: The target controller [ int ( 4 Bytes ) ]
2421 // 2: The channel of the target controllee [ int ( 4 Bytes ) ]
2422 // 3: HDIO_ ioctl call [ int ( 4 Bytes ) ]
2423 // available from ${LINUX_KERNEL_SOURCE}/Documentation/ioctl/hdio
2424 // 4: the pmport that disk attached, [ int ( 4 Bytes ) ]
2425 // if no pmport device, set to 1 or leave blank
2426 // 5: data [ void * ( var leangth ) ]
2428 #define STRANGE_BUFFER_LENGTH (4+512*0xf8)
2430 int linux_highpoint_device::ata_command_interface(smart_command_set command
, int select
, char * data
)
2432 unsigned char hpt_buff
[4*sizeof(int) + STRANGE_BUFFER_LENGTH
];
2433 unsigned int *hpt
= (unsigned int *)hpt_buff
;
2434 unsigned char *buff
= &hpt_buff
[4*sizeof(int)];
2436 const int HDIO_DRIVE_CMD_OFFSET
= 4;
2438 memset(hpt_buff
, 0, 4*sizeof(int) + STRANGE_BUFFER_LENGTH
);
2439 hpt
[0] = m_hpt_data
[0]; // controller id
2440 hpt
[1] = m_hpt_data
[1]; // channel number
2441 hpt
[3] = m_hpt_data
[2]; // pmport number
2443 buff
[0]=ATA_SMART_CMD
;
2445 case CHECK_POWER_MODE
:
2446 buff
[0]=ATA_CHECK_POWER_MODE
;
2450 buff
[2]=ATA_SMART_READ_VALUES
;
2454 case READ_THRESHOLDS
:
2455 buff
[2]=ATA_SMART_READ_THRESHOLDS
;
2460 buff
[2]=ATA_SMART_READ_LOG_SECTOR
;
2468 buff
[0]=ATA_IDENTIFY_DEVICE
;
2473 buff
[0]=ATA_IDENTIFY_PACKET_DEVICE
;
2478 buff
[2]=ATA_SMART_ENABLE
;
2482 buff
[2]=ATA_SMART_DISABLE
;
2486 buff
[2]=ATA_SMART_STATUS
;
2489 buff
[2]=ATA_SMART_AUTO_OFFLINE
;
2493 buff
[2]=ATA_SMART_AUTOSAVE
;
2496 case IMMEDIATE_OFFLINE
:
2497 buff
[2]=ATA_SMART_IMMEDIATE_OFFLINE
;
2501 buff
[1]=ATA_SMART_STATUS
;
2504 pout("Unrecognized command %d in linux_highpoint_command_interface()\n"
2505 "Please contact " PACKAGE_BUGREPORT
"\n", command
);
2510 if (command
==WRITE_LOG
) {
2511 unsigned char task
[4*sizeof(int)+sizeof(ide_task_request_t
)+512];
2512 unsigned int *hpt_tf
= (unsigned int *)task
;
2513 ide_task_request_t
*reqtask
= (ide_task_request_t
*)(&task
[4*sizeof(int)]);
2514 task_struct_t
*taskfile
= (task_struct_t
*)reqtask
->io_ports
;
2517 memset(task
, 0, sizeof(task
));
2519 hpt_tf
[0] = m_hpt_data
[0]; // controller id
2520 hpt_tf
[1] = m_hpt_data
[1]; // channel number
2521 hpt_tf
[3] = m_hpt_data
[2]; // pmport number
2522 hpt_tf
[2] = HDIO_DRIVE_TASKFILE
; // real hd ioctl
2525 taskfile
->feature
= ATA_SMART_WRITE_LOG_SECTOR
;
2526 taskfile
->sector_count
= 1;
2527 taskfile
->sector_number
= select
;
2528 taskfile
->low_cylinder
= 0x4f;
2529 taskfile
->high_cylinder
= 0xc2;
2530 taskfile
->device_head
= 0;
2531 taskfile
->command
= ATA_SMART_CMD
;
2533 reqtask
->data_phase
= TASKFILE_OUT
;
2534 reqtask
->req_cmd
= IDE_DRIVE_TASK_OUT
;
2535 reqtask
->out_size
= 512;
2536 reqtask
->in_size
= 0;
2538 memcpy(task
+sizeof(ide_task_request_t
)+4*sizeof(int), data
, 512);
2540 if ((retval
=ioctl(get_fd(), HPTIO_CTL
, task
))) {
2541 if (retval
==-EINVAL
)
2542 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
2548 if (command
==STATUS_CHECK
){
2550 unsigned const char normal_lo
=0x4f, normal_hi
=0xc2;
2551 unsigned const char failed_lo
=0xf4, failed_hi
=0x2c;
2555 hpt
[2] = HDIO_DRIVE_TASK
;
2557 if ((retval
=ioctl(get_fd(), HPTIO_CTL
, hpt_buff
))) {
2558 if (retval
==-EINVAL
) {
2559 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
2560 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
2563 syserror("Error SMART Status command failed");
2567 if (buff
[4]==normal_lo
&& buff
[5]==normal_hi
)
2570 if (buff
[4]==failed_lo
&& buff
[5]==failed_hi
)
2573 syserror("Error SMART Status command failed");
2574 pout("Please get assistance from " PACKAGE_HOMEPAGE
"\n");
2575 pout("Register values returned from SMART Status command are:\n");
2576 pout("CMD=0x%02x\n",(int)buff
[0]);
2577 pout("FR =0x%02x\n",(int)buff
[1]);
2578 pout("NS =0x%02x\n",(int)buff
[2]);
2579 pout("SC =0x%02x\n",(int)buff
[3]);
2580 pout("CL =0x%02x\n",(int)buff
[4]);
2581 pout("CH =0x%02x\n",(int)buff
[5]);
2582 pout("SEL=0x%02x\n",(int)buff
[6]);
2587 if (command
==IDENTIFY
|| command
==PIDENTIFY
) {
2588 unsigned char deviceid
[4*sizeof(int)+512*sizeof(char)];
2589 unsigned int *hpt_id
= (unsigned int *)deviceid
;
2591 hpt_id
[0] = m_hpt_data
[0]; // controller id
2592 hpt_id
[1] = m_hpt_data
[1]; // channel number
2593 hpt_id
[3] = m_hpt_data
[2]; // pmport number
2595 hpt_id
[2] = HDIO_GET_IDENTITY
;
2596 if (!ioctl(get_fd(), HPTIO_CTL
, deviceid
) && (deviceid
[4*sizeof(int)] & 0x8000))
2597 buff
[0]=(command
==IDENTIFY
)?ATA_IDENTIFY_PACKET_DEVICE
:ATA_IDENTIFY_DEVICE
;
2601 hpt
[2] = HDIO_DRIVE_CMD
;
2602 if ((ioctl(get_fd(), HPTIO_CTL
, hpt_buff
)))
2605 if (command
==CHECK_POWER_MODE
)
2606 buff
[HDIO_DRIVE_CMD_OFFSET
]=buff
[2];
2609 memcpy(data
, buff
+HDIO_DRIVE_CMD_OFFSET
, copydata
);
2615 #if 0 // TODO: Migrate from 'smart_command_set' to 'ata_in_regs' OR remove the function
2616 // Utility function for printing warnings
2617 void printwarning(smart_command_set command
){
2618 static int printed
[4]={0,0,0,0};
2619 const char* message
=
2620 "can not be passed through the 3ware 3w-xxxx driver. This can be fixed by\n"
2621 "applying a simple 3w-xxxx driver patch that can be found here:\n"
2622 PACKAGE_HOMEPAGE
"\n"
2623 "Alternatively, upgrade your 3w-xxxx driver to version 1.02.00.037 or greater.\n\n";
2625 if (command
==AUTO_OFFLINE
&& !printed
[0]) {
2627 pout("The SMART AUTO-OFFLINE ENABLE command (smartmontools -o on option/Directive)\n%s", message
);
2629 else if (command
==AUTOSAVE
&& !printed
[1]) {
2631 pout("The SMART AUTOSAVE ENABLE command (smartmontools -S on option/Directive)\n%s", message
);
2633 else if (command
==STATUS_CHECK
&& !printed
[2]) {
2635 pout("The SMART RETURN STATUS return value (smartmontools -H option/Directive)\n%s", message
);
2637 else if (command
==WRITE_LOG
&& !printed
[3]) {
2639 pout("The SMART WRITE LOG command (smartmontools -t selective) only supported via char /dev/tw[ae] interface\n");
2647 /////////////////////////////////////////////////////////////////////////////
2648 /// SCSI open with autodetection support
2650 smart_device
* linux_scsi_device::autodetect_open()
2656 // No Autodetection if device type was specified by user
2657 bool sat_only
= false;
2658 if (*get_req_type()) {
2659 // Detect SAT if device object was created by scan_smart_devices().
2660 if (!(m_scanning
&& !strcmp(get_req_type(), "sat")))
2665 // The code below is based on smartd.cpp:SCSIFilterKnown()
2668 unsigned char req_buff
[64] = {0, };
2670 if (scsiStdInquiry(this, req_buff
, req_len
)) {
2671 // Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices
2672 // watch this spot ... other devices could lock up here
2674 if (scsiStdInquiry(this, req_buff
, req_len
)) {
2675 // device doesn't like INQUIRY commands
2677 set_err(EIO
, "INQUIRY failed");
2682 int avail_len
= req_buff
[4] + 5;
2683 int len
= (avail_len
< req_len
? avail_len
: req_len
);
2687 set_err(EIO
, "INQUIRY too short for SAT");
2692 // Use INQUIRY to detect type
2696 if (!memcmp(req_buff
+ 8, "3ware", 5) || !memcmp(req_buff
+ 8, "AMCC", 4)) {
2698 set_err(EINVAL
, "AMCC/3ware controller, please try adding '-d 3ware,N',\n"
2699 "you may need to replace %s with /dev/twlN, /dev/twaN or /dev/tweN", get_dev_name());
2704 if (!memcmp(req_buff
+ 8, "DELL PERC", 12) || !memcmp(req_buff
+ 8, "MegaRAID", 8)) {
2706 set_err(EINVAL
, "DELL or MegaRaid controller, please try adding '-d megaraid,N'");
2711 if (len
>= 42 && !memcmp(req_buff
+ 36, "MVSATA", 6)) {
2712 //pout("Device %s: using '-d marvell' for ATA disk with Marvell driver\n", get_dev_name());
2714 smart_device_auto_ptr
newdev(
2715 new linux_marvell_device(smi(), get_dev_name(), get_req_type())
2717 newdev
->open(); // TODO: Can possibly pass open fd
2719 return newdev
.release();
2725 smart_device
* newdev
= smi()->autodetect_sat_device(this, req_buff
, len
);
2727 // NOTE: 'this' is now owned by '*newdev'
2731 // Nothing special found
2735 set_err(EIO
, "Not a SAT device");
2741 //////////////////////////////////////////////////////////////////////
2742 // USB bridge ID detection
2744 // Read USB ID from /sys file
2745 static bool read_id(const std::string
& path
, unsigned short & id
)
2747 FILE * f
= fopen(path
.c_str(), "r");
2751 bool ok
= (fscanf(f
, "%hx%n", &id
, &n
) == 1 && n
== 4);
2756 // Get USB bridge ID for "sdX"
2757 static bool get_usb_id(const char * name
, unsigned short & vendor_id
,
2758 unsigned short & product_id
, unsigned short & version
)
2760 // Only "sdX" supported
2761 if (!(!strncmp(name
, "sd", 2) && !strchr(name
, '/')))
2764 // Start search at dir referenced by symlink "/sys/block/sdX/device"
2765 // -> "/sys/devices/.../usb*/.../host*/target*/..."
2766 std::string dir
= strprintf("/sys/block/%s/device", name
);
2768 // Stop search at "/sys/devices"
2770 if (stat("/sys/devices", &st
))
2772 ino_t stop_ino
= st
.st_ino
;
2774 // Search in parent directories until "idVendor" is found,
2775 // fail if "/sys/devices" reached or too many iterations
2779 if (!(++cnt
< 10 && !stat(dir
.c_str(), &st
) && st
.st_ino
!= stop_ino
))
2781 } while (access((dir
+ "/idVendor").c_str(), 0));
2784 if (!( read_id(dir
+ "/idVendor", vendor_id
)
2785 && read_id(dir
+ "/idProduct", product_id
)
2786 && read_id(dir
+ "/bcdDevice", version
) ))
2789 if (scsi_debugmode
> 1)
2790 pout("USB ID = 0x%04x:0x%04x (0x%03x)\n", vendor_id
, product_id
, version
);
2795 //////////////////////////////////////////////////////////////////////
2798 class linux_smart_interface
2799 : public /*implements*/ smart_interface
2802 virtual std::string
get_os_version_str();
2804 virtual std::string
get_app_examples(const char * appname
);
2806 virtual bool scan_smart_devices(smart_device_list
& devlist
, const char * type
,
2807 const char * pattern
= 0);
2810 virtual ata_device
* get_ata_device(const char * name
, const char * type
);
2812 virtual scsi_device
* get_scsi_device(const char * name
, const char * type
);
2814 virtual smart_device
* autodetect_smart_device(const char * name
);
2816 virtual smart_device
* get_custom_smart_device(const char * name
, const char * type
);
2818 virtual std::string
get_valid_custom_dev_types_str();
2821 bool get_dev_list(smart_device_list
& devlist
, const char * pattern
,
2822 bool scan_ata
, bool scan_scsi
, const char * req_type
, bool autodetect
);
2824 smart_device
* missing_option(const char * opt
);
2827 std::string
linux_smart_interface::get_os_version_str()
2831 return strprintf("%s-linux-%s", u
.machine
, u
.release
);
2833 return SMARTMONTOOLS_BUILD_HOST
;
2836 std::string
linux_smart_interface::get_app_examples(const char * appname
)
2838 if (!strcmp(appname
, "smartctl"))
2839 return smartctl_examples
;
2844 // we are going to take advantage of the fact that Linux's devfs will only
2845 // have device entries for devices that exist. So if we get the equivalent of
2846 // ls /dev/hd[a-t], we have all the ATA devices on the system
2847 bool linux_smart_interface::get_dev_list(smart_device_list
& devlist
,
2848 const char * pattern
, bool scan_ata
, bool scan_scsi
,
2849 const char * req_type
, bool autodetect
)
2851 // Use glob to look for any directory entries matching the pattern
2853 memset(&globbuf
, 0, sizeof(globbuf
));
2854 int retglob
= glob(pattern
, GLOB_ERR
, NULL
, &globbuf
);
2856 // glob failed: free memory and return
2859 if (retglob
==GLOB_NOMATCH
){
2860 pout("glob(3) found no matches for pattern %s\n", pattern
);
2864 if (retglob
==GLOB_NOSPACE
)
2865 set_err(ENOMEM
, "glob(3) ran out of memory matching pattern %s", pattern
);
2866 #ifdef GLOB_ABORTED // missing in old versions of glob.h
2867 else if (retglob
==GLOB_ABORTED
)
2868 set_err(EINVAL
, "glob(3) aborted matching pattern %s", pattern
);
2871 set_err(EINVAL
, "Unexplained error in glob(3) of pattern %s", pattern
);
2876 // did we find too many paths?
2877 const int max_pathc
= 32;
2878 int n
= (int)globbuf
.gl_pathc
;
2879 if (n
> max_pathc
) {
2880 pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n",
2881 n
, max_pathc
, pattern
, n
- max_pathc
);
2885 // now step through the list returned by glob. If not a link, copy
2886 // to list. If it is a link, evaluate it and see if the path ends
2888 for (int i
= 0; i
< n
; i
++){
2889 // see if path is a link
2891 int retlink
= readlink(globbuf
.gl_pathv
[i
], linkbuf
, sizeof(linkbuf
)-1);
2893 char tmpname
[1024]={0};
2894 const char * name
= 0;
2895 bool is_scsi
= scan_scsi
;
2896 // if not a link (or a strange link), keep it
2897 if (retlink
<=0 || retlink
>1023)
2898 name
= globbuf
.gl_pathv
[i
];
2900 // or if it's a link that points to a disc, follow it
2901 linkbuf
[retlink
] = 0;
2903 if ((p
=strrchr(linkbuf
, '/')) && !strcmp(p
+1, "disc"))
2904 // This is the branch of the code that gets followed if we are
2905 // using devfs WITH traditional compatibility links. In this
2906 // case, we add the traditional device name to the list that
2908 name
= globbuf
.gl_pathv
[i
];
2910 // This is the branch of the code that gets followed if we are
2911 // using devfs WITHOUT traditional compatibility links. In
2912 // this case, we check that the link to the directory is of
2913 // the correct type, and then append "disc" to it.
2914 bool match_ata
= strstr(linkbuf
, "ide");
2915 bool match_scsi
= strstr(linkbuf
, "scsi");
2916 if (((match_ata
&& scan_ata
) || (match_scsi
&& scan_scsi
)) && !(match_ata
&& match_scsi
)) {
2917 is_scsi
= match_scsi
;
2918 snprintf(tmpname
, sizeof(tmpname
), "%s/disc", globbuf
.gl_pathv
[i
]);
2925 // Found a name, add device to list.
2928 dev
= autodetect_smart_device(name
);
2930 dev
= new linux_scsi_device(this, name
, req_type
, true /*scanning*/);
2932 dev
= new linux_ata_device(this, name
, req_type
);
2933 if (dev
) // autodetect_smart_device() may return nullptr.
2934 devlist
.push_back(dev
);
2944 bool linux_smart_interface::scan_smart_devices(smart_device_list
& devlist
,
2945 const char * type
, const char * pattern
/*= 0*/)
2948 set_err(EINVAL
, "DEVICESCAN with pattern not implemented yet");
2955 bool scan_ata
= (!*type
|| !strcmp(type
, "ata" ));
2956 // "sat" detection will be later handled in linux_scsi_device::autodetect_open()
2957 bool scan_scsi
= (!*type
|| !strcmp(type
, "scsi") || !strcmp(type
, "sat"));
2958 if (!(scan_ata
|| scan_scsi
))
2962 get_dev_list(devlist
, "/dev/hd[a-t]", true, false, type
, false);
2964 bool autodetect
= !*type
; // Try USB autodetection if no type specifed
2965 get_dev_list(devlist
, "/dev/sd[a-z]", false, true, type
, autodetect
);
2966 // Support up to 104 devices
2967 get_dev_list(devlist
, "/dev/sd[a-c][a-z]", false, true, type
, autodetect
);
2970 // if we found traditional links, we are done
2971 if (devlist
.size() > 0)
2974 // else look for devfs entries without traditional links
2975 // TODO: Add udev support
2976 return get_dev_list(devlist
, "/dev/discs/disc*", scan_ata
, scan_scsi
, type
, false);
2979 ata_device
* linux_smart_interface::get_ata_device(const char * name
, const char * type
)
2981 return new linux_ata_device(this, name
, type
);
2984 scsi_device
* linux_smart_interface::get_scsi_device(const char * name
, const char * type
)
2986 return new linux_scsi_device(this, name
, type
);
2989 smart_device
* linux_smart_interface::missing_option(const char * opt
)
2991 set_err(EINVAL
, "requires option '%s'", opt
);
2995 // Return true if STR starts with PREFIX.
2996 static inline bool str_starts_with(const char * str
, const char * prefix
)
2998 return !strncmp(str
, prefix
, strlen(prefix
));
3001 // Return kernel release as integer ("2.6.31" -> 206031)
3002 static unsigned get_kernel_release()
3007 unsigned x
= 0, y
= 0, z
= 0;
3008 if (!(sscanf(u
.release
, "%u.%u.%u", &x
, &y
, &z
) == 3
3009 && x
< 100 && y
< 100 && z
< 1000 ))
3011 return x
* 100000 + y
* 1000 + z
;
3014 // Guess device type (ata or scsi) based on device name (Linux
3015 // specific) SCSI device name in linux can be sd, sr, scd, st, nst,
3016 // osst, nosst and sg.
3017 smart_device
* linux_smart_interface::autodetect_smart_device(const char * name
)
3019 const char * test_name
= name
;
3021 // Dereference symlinks
3023 std::string pathbuf
;
3024 if (!lstat(name
, &st
) && S_ISLNK(st
.st_mode
)) {
3025 char * p
= realpath(name
, (char *)0);
3029 test_name
= pathbuf
.c_str();
3033 // Remove the leading /dev/... if it's there
3034 static const char dev_prefix
[] = "/dev/";
3035 if (str_starts_with(test_name
, dev_prefix
))
3036 test_name
+= strlen(dev_prefix
);
3038 // form /dev/h* or h*
3039 if (str_starts_with(test_name
, "h"))
3040 return new linux_ata_device(this, name
, "");
3042 // form /dev/ide/* or ide/*
3043 if (str_starts_with(test_name
, "ide/"))
3044 return new linux_ata_device(this, name
, "");
3046 // form /dev/s* or s*
3047 if (str_starts_with(test_name
, "s")) {
3049 // Try to detect possible USB->(S)ATA bridge
3050 unsigned short vendor_id
= 0, product_id
= 0, version
= 0;
3051 if (get_usb_id(test_name
, vendor_id
, product_id
, version
)) {
3052 const char * usbtype
= get_usb_dev_type_by_id(vendor_id
, product_id
, version
);
3056 // Kernels before 2.6.29 do not support the sense data length
3057 // required for SAT ATA PASS-THROUGH(16)
3058 if (!strcmp(usbtype
, "sat") && get_kernel_release() < 206029)
3061 // Return SAT/USB device for this type
3062 // (Note: linux_scsi_device::autodetect_open() will not be called in this case)
3063 return get_sat_device(usbtype
, new linux_scsi_device(this, name
, ""));
3066 // No USB bridge found, assume regular SCSI device
3067 return new linux_scsi_device(this, name
, "");
3070 // form /dev/scsi/* or scsi/*
3071 if (str_starts_with(test_name
, "scsi/"))
3072 return new linux_scsi_device(this, name
, "");
3074 // form /dev/ns* or ns*
3075 if (str_starts_with(test_name
, "ns"))
3076 return new linux_scsi_device(this, name
, "");
3078 // form /dev/os* or os*
3079 if (str_starts_with(test_name
, "os"))
3080 return new linux_scsi_device(this, name
, "");
3082 // form /dev/nos* or nos*
3083 if (str_starts_with(test_name
, "nos"))
3084 return new linux_scsi_device(this, name
, "");
3086 // form /dev/tw[ael]* or tw[ael]*
3087 if (str_starts_with(test_name
, "tw") && strchr("ael", test_name
[2]))
3088 return missing_option("-d 3ware,N");
3090 // form /dev/cciss/* or cciss/*
3091 if (str_starts_with(test_name
, "cciss/"))
3092 return missing_option("-d cciss,N");
3094 // we failed to recognize any of the forms
3098 smart_device
* linux_smart_interface::get_custom_smart_device(const char * name
, const char * type
)
3101 if (!strcmp(type
, "marvell"))
3102 return new linux_marvell_device(this, name
, type
);
3105 int disknum
= -1, n1
= -1, n2
= -1;
3106 if (sscanf(type
, "3ware,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3107 if (n2
!= (int)strlen(type
)) {
3108 set_err(EINVAL
, "Option -d 3ware,N requires N to be a non-negative integer");
3111 if (!(0 <= disknum
&& disknum
<= 127)) {
3112 set_err(EINVAL
, "Option -d 3ware,N (N=%d) must have 0 <= N <= 127", disknum
);
3116 if (!strncmp(name
, "/dev/twl", 8))
3117 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_9700_CHAR
, disknum
);
3118 else if (!strncmp(name
, "/dev/twa", 8))
3119 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_9000_CHAR
, disknum
);
3120 else if (!strncmp(name
, "/dev/twe", 8))
3121 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_678K_CHAR
, disknum
);
3123 return new linux_escalade_device(this, name
, linux_escalade_device::AMCC_3WARE_678K
, disknum
);
3127 disknum
= n1
= n2
= -1;
3128 if (sscanf(type
, "areca,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3129 if (n2
!= (int)strlen(type
)) {
3130 set_err(EINVAL
, "Option -d areca,N requires N to be a non-negative integer");
3133 if (!(1 <= disknum
&& disknum
<= 24)) {
3134 set_err(EINVAL
, "Option -d areca,N (N=%d) must have 1 <= N <= 24", disknum
);
3137 return new linux_areca_device(this, name
, disknum
);
3141 int controller
= -1, channel
= -1; disknum
= 1;
3142 n1
= n2
= -1; int n3
= -1;
3143 if (sscanf(type
, "hpt,%n%d/%d%n/%d%n", &n1
, &controller
, &channel
, &n2
, &disknum
, &n3
) >= 2 || n1
== 4) {
3144 int len
= strlen(type
);
3145 if (!(n2
== len
|| n3
== len
)) {
3146 set_err(EINVAL
, "Option '-d hpt,L/M/N' supports 2-3 items");
3149 if (!(1 <= controller
&& controller
<= 8)) {
3150 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid controller id L supplied");
3153 if (!(1 <= channel
&& channel
<= 8)) {
3154 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid channel number M supplied");
3157 if (!(1 <= disknum
&& disknum
<= 15)) {
3158 set_err(EINVAL
, "Option '-d hpt,L/M/N' invalid pmport number N supplied");
3161 return new linux_highpoint_device(this, name
, controller
, channel
, disknum
);
3164 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3166 disknum
= n1
= n2
= -1;
3167 if (sscanf(type
, "cciss,%n%d%n", &n1
, &disknum
, &n2
) == 1 || n1
== 6) {
3168 if (n2
!= (int)strlen(type
)) {
3169 set_err(EINVAL
, "Option -d cciss,N requires N to be a non-negative integer");
3172 if (!(0 <= disknum
&& disknum
<= 127)) {
3173 set_err(EINVAL
, "Option -d cciss,N (N=%d) must have 0 <= N <= 127", disknum
);
3176 return new linux_cciss_device(this, name
, disknum
);
3178 #endif // HAVE_LINUX_CCISS_IOCTL_H
3181 if (sscanf(type
, "megaraid,%d", &disknum
) == 1) {
3182 return new linux_megaraid_device(this, name
, 0, disknum
);
3187 std::string
linux_smart_interface::get_valid_custom_dev_types_str()
3189 return "marvell, areca,N, 3ware,N, hpt,L/M/N, megaraid,N"
3190 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3199 /////////////////////////////////////////////////////////////////////////////
3200 /// Initialize platform interface and register with smi()
3202 void smart_interface::init()
3204 static os_linux::linux_smart_interface the_interface
;
3205 smart_interface::set(&the_interface
);