]> git.proxmox.com Git - mirror_smartmontools-debian.git/blob - os_linux.cpp
Merge commit 'upstream/5.38+svn2956'
[mirror_smartmontools-debian.git] / os_linux.cpp
1 /*
2 * os_linux.cpp
3 *
4 * Home page of code is: http://smartmontools.sourceforge.net
5 *
6 * Copyright (C) 2003-8 Bruce Allen <smartmontools-support@lists.sourceforge.net>
7 * Copyright (C) 2003-8 Doug Gilbert <dougg@torque.net>
8 * Copyright (C) 2008 Hank Wu <hank@areca.com.tw>
9 * Copyright (C) 2008 Oliver Bock <brevilo@users.sourceforge.net>
10 * Copyright (C) 2008-9 Christian Franke <smartmontools-support@lists.sourceforge.net>
11 * Copyright (C) 2008 Jordan Hargrave <jordan_hargrave@dell.com>
12 *
13 * Parts of this file are derived from code that was
14 *
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>
19 *
20 * Copyright (C) 1999-2003 3ware Inc.
21 *
22 * Kernel compatablity By: Andre Hedrick <andre@suse.com>
23 * Non-Copyright (C) 2000 Andre Hedrick <andre@suse.com>
24 *
25 * Other ars of this file are derived from code that was
26 *
27 * Copyright (C) 1999-2000 Michael Cornwell <cornwell@acm.org>
28 * Copyright (C) 2000 Andre Hedrick <andre@linux-ide.org>
29 *
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)
33 * any later version.
34 *
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/>.
37 *
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/
42 *
43 */
44
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
48 // controllers.
49
50 #include "config.h"
51
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <glob.h>
55
56 #include <scsi/scsi.h>
57 #include <scsi/scsi_ioctl.h>
58 #include <scsi/sg.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sys/ioctl.h>
62 #include <sys/stat.h>
63 #include <sys/file.h>
64 #include <unistd.h>
65 #include <sys/uio.h>
66 #include <sys/types.h>
67 #ifndef makedev // old versions of types.h do not include sysmacros.h
68 #include <sys/sysmacros.h>
69 #endif
70 #ifdef WITH_SELINUX
71 #include <selinux/selinux.h>
72 #endif
73
74 #include "int64.h"
75 #include "atacmds.h"
76 #include "extern.h"
77 #include "os_linux.h"
78 #include "scsicmds.h"
79 #include "utility.h"
80 #include "extern.h"
81 #include "cciss.h"
82 #include "megaraid.h"
83
84 #include "dev_interface.h"
85 #include "dev_ata_cmd_set.h"
86
87 #ifndef ENOTSUP
88 #define ENOTSUP ENOSYS
89 #endif
90
91 #define ARGUSED(x) ((void)(x))
92
93 const char *os_XXXX_c_cvsid="$Id: os_linux.cpp 2951 2009-10-08 23:43:46Z samm2 $" \
94 ATACMDS_H_CVSID CONFIG_H_CVSID INT64_H_CVSID OS_LINUX_H_CVSID SCSICMDS_H_CVSID UTILITY_H_CVSID;
95
96 /* for passing global control variables */
97 // (con->reportscsiioctl only)
98 extern smartmonctrl *con;
99
100
101 namespace os_linux { // No need to publish anything, name provided for Doxygen
102
103 /////////////////////////////////////////////////////////////////////////////
104 /// Shared open/close routines
105
106 class linux_smart_device
107 : virtual public /*implements*/ smart_device
108 {
109 public:
110 explicit linux_smart_device(int flags, int retry_flags = -1)
111 : smart_device(never_called),
112 m_fd(-1),
113 m_flags(flags), m_retry_flags(retry_flags)
114 { }
115
116 virtual ~linux_smart_device() throw();
117
118 virtual bool is_open() const;
119
120 virtual bool open();
121
122 virtual bool close();
123
124 protected:
125 /// Return filedesc for derived classes.
126 int get_fd() const
127 { return m_fd; }
128
129 private:
130 int m_fd; ///< filedesc, -1 if not open.
131 int m_flags; ///< Flags for ::open()
132 int m_retry_flags; ///< Flags to retry ::open(), -1 if no retry
133 };
134
135
136 linux_smart_device::~linux_smart_device() throw()
137 {
138 if (m_fd >= 0)
139 ::close(m_fd);
140 }
141
142 bool linux_smart_device::is_open() const
143 {
144 return (m_fd >= 0);
145 }
146
147 bool linux_smart_device::open()
148 {
149 m_fd = ::open(get_dev_name(), m_flags);
150
151 if (m_fd < 0 && errno == EROFS && m_retry_flags != -1)
152 // Retry
153 m_fd = ::open(get_dev_name(), m_retry_flags);
154
155 if (m_fd < 0) {
156 if (errno == EBUSY && (m_flags & O_EXCL))
157 // device is locked
158 return set_err(EBUSY,
159 "The requested controller is used exclusively by another process!\n"
160 "(e.g. smartctl or smartd)\n"
161 "Please quit the impeding process or try again later...");
162 return set_err((errno==ENOENT || errno==ENOTDIR) ? ENODEV : errno);
163 }
164
165 if (m_fd >= 0) {
166 // sets FD_CLOEXEC on the opened device file descriptor. The
167 // descriptor is otherwise leaked to other applications (mail
168 // sender) which may be considered a security risk and may result
169 // in AVC messages on SELinux-enabled systems.
170 if (-1 == fcntl(m_fd, F_SETFD, FD_CLOEXEC))
171 // TODO: Provide an error printing routine in class smart_interface
172 pout("fcntl(set FD_CLOEXEC) failed, errno=%d [%s]\n", errno, strerror(errno));
173 }
174
175 return true;
176 }
177
178 // equivalent to close(file descriptor)
179 bool linux_smart_device::close()
180 {
181 int fd = m_fd; m_fd = -1;
182 if (::close(fd) < 0)
183 return set_err(errno);
184 return true;
185 }
186
187 // examples for smartctl
188 static const char smartctl_examples[] =
189 "=================================================== SMARTCTL EXAMPLES =====\n\n"
190 " smartctl --all /dev/hda (Prints all SMART information)\n\n"
191 " smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda\n"
192 " (Enables SMART on first disk)\n\n"
193 " smartctl --test=long /dev/hda (Executes extended disk self-test)\n\n"
194 " smartctl --attributes --log=selftest --quietmode=errorsonly /dev/hda\n"
195 " (Prints Self-Test & Attribute errors)\n"
196 " smartctl --all --device=3ware,2 /dev/sda\n"
197 " smartctl --all --device=3ware,2 /dev/twe0\n"
198 " smartctl --all --device=3ware,2 /dev/twa0\n"
199 " (Prints all SMART info for 3rd ATA disk on 3ware RAID controller)\n"
200 " smartctl --all --device=hpt,1/1/3 /dev/sda\n"
201 " (Prints all SMART info for the SATA disk attached to the 3rd PMPort\n"
202 " of the 1st channel on the 1st HighPoint RAID controller)\n"
203 " smartctl --all --device=areca,3 /dev/sg2\n"
204 " (Prints all SMART info for 3rd ATA disk on Areca RAID controller)\n"
205 ;
206
207
208 /////////////////////////////////////////////////////////////////////////////
209 /// Linux ATA support
210
211 class linux_ata_device
212 : public /*implements*/ ata_device_with_command_set,
213 public /*extends*/ linux_smart_device
214 {
215 public:
216 linux_ata_device(smart_interface * intf, const char * dev_name, const char * req_type);
217
218 protected:
219 virtual int ata_command_interface(smart_command_set command, int select, char * data);
220 };
221
222 linux_ata_device::linux_ata_device(smart_interface * intf, const char * dev_name, const char * req_type)
223 : smart_device(intf, dev_name, "ata", req_type),
224 linux_smart_device(O_RDONLY | O_NONBLOCK)
225 {
226 }
227
228 // PURPOSE
229 // This is an interface routine meant to isolate the OS dependent
230 // parts of the code, and to provide a debugging interface. Each
231 // different port and OS needs to provide it's own interface. This
232 // is the linux one.
233 // DETAILED DESCRIPTION OF ARGUMENTS
234 // device: is the file descriptor provided by open()
235 // command: defines the different operations.
236 // select: additional input data if needed (which log, which type of
237 // self-test).
238 // data: location to write output data, if needed (512 bytes).
239 // Note: not all commands use all arguments.
240 // RETURN VALUES
241 // -1 if the command failed
242 // 0 if the command succeeded,
243 // STATUS_CHECK routine:
244 // -1 if the command failed
245 // 0 if the command succeeded and disk SMART status is "OK"
246 // 1 if the command succeeded and disk SMART status is "FAILING"
247
248
249 #define BUFFER_LENGTH (4+512)
250
251 int linux_ata_device::ata_command_interface(smart_command_set command, int select, char * data)
252 {
253 unsigned char buff[BUFFER_LENGTH];
254 // positive: bytes to write to caller. negative: bytes to READ from
255 // caller. zero: non-data command
256 int copydata=0;
257
258 const int HDIO_DRIVE_CMD_OFFSET = 4;
259
260 // See struct hd_drive_cmd_hdr in hdreg.h. Before calling ioctl()
261 // buff[0]: ATA COMMAND CODE REGISTER
262 // buff[1]: ATA SECTOR NUMBER REGISTER == LBA LOW REGISTER
263 // buff[2]: ATA FEATURES REGISTER
264 // buff[3]: ATA SECTOR COUNT REGISTER
265
266 // Note that on return:
267 // buff[2] contains the ATA SECTOR COUNT REGISTER
268
269 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
270 memset(buff, 0, BUFFER_LENGTH);
271
272 buff[0]=ATA_SMART_CMD;
273 switch (command){
274 case CHECK_POWER_MODE:
275 buff[0]=ATA_CHECK_POWER_MODE;
276 copydata=1;
277 break;
278 case READ_VALUES:
279 buff[2]=ATA_SMART_READ_VALUES;
280 buff[3]=1;
281 copydata=512;
282 break;
283 case READ_THRESHOLDS:
284 buff[2]=ATA_SMART_READ_THRESHOLDS;
285 buff[1]=buff[3]=1;
286 copydata=512;
287 break;
288 case READ_LOG:
289 buff[2]=ATA_SMART_READ_LOG_SECTOR;
290 buff[1]=select;
291 buff[3]=1;
292 copydata=512;
293 break;
294 case WRITE_LOG:
295 break;
296 case IDENTIFY:
297 buff[0]=ATA_IDENTIFY_DEVICE;
298 buff[3]=1;
299 copydata=512;
300 break;
301 case PIDENTIFY:
302 buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
303 buff[3]=1;
304 copydata=512;
305 break;
306 case ENABLE:
307 buff[2]=ATA_SMART_ENABLE;
308 buff[1]=1;
309 break;
310 case DISABLE:
311 buff[2]=ATA_SMART_DISABLE;
312 buff[1]=1;
313 break;
314 case STATUS:
315 // this command only says if SMART is working. It could be
316 // replaced with STATUS_CHECK below.
317 buff[2]=ATA_SMART_STATUS;
318 break;
319 case AUTO_OFFLINE:
320 // NOTE: According to ATAPI 4 and UP, this command is obsolete
321 // select == 241 for enable but no data transfer. Use TASK ioctl.
322 buff[1]=ATA_SMART_AUTO_OFFLINE;
323 buff[2]=select;
324 break;
325 case AUTOSAVE:
326 // select == 248 for enable but no data transfer. Use TASK ioctl.
327 buff[1]=ATA_SMART_AUTOSAVE;
328 buff[2]=select;
329 break;
330 case IMMEDIATE_OFFLINE:
331 buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
332 buff[1]=select;
333 break;
334 case STATUS_CHECK:
335 // This command uses HDIO_DRIVE_TASK and has different syntax than
336 // the other commands.
337 buff[1]=ATA_SMART_STATUS;
338 break;
339 default:
340 pout("Unrecognized command %d in linux_ata_command_interface()\n"
341 "Please contact " PACKAGE_BUGREPORT "\n", command);
342 errno=ENOSYS;
343 return -1;
344 }
345
346 // This command uses the HDIO_DRIVE_TASKFILE ioctl(). This is the
347 // only ioctl() that can be used to WRITE data to the disk.
348 if (command==WRITE_LOG) {
349 unsigned char task[sizeof(ide_task_request_t)+512];
350 ide_task_request_t *reqtask=(ide_task_request_t *) task;
351 task_struct_t *taskfile=(task_struct_t *) reqtask->io_ports;
352 int retval;
353
354 memset(task, 0, sizeof(task));
355
356 taskfile->data = 0;
357 taskfile->feature = ATA_SMART_WRITE_LOG_SECTOR;
358 taskfile->sector_count = 1;
359 taskfile->sector_number = select;
360 taskfile->low_cylinder = 0x4f;
361 taskfile->high_cylinder = 0xc2;
362 taskfile->device_head = 0;
363 taskfile->command = ATA_SMART_CMD;
364
365 reqtask->data_phase = TASKFILE_OUT;
366 reqtask->req_cmd = IDE_DRIVE_TASK_OUT;
367 reqtask->out_size = 512;
368 reqtask->in_size = 0;
369
370 // copy user data into the task request structure
371 memcpy(task+sizeof(ide_task_request_t), data, 512);
372
373 if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASKFILE, task))) {
374 if (retval==-EINVAL)
375 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
376 return -1;
377 }
378 return 0;
379 }
380
381 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
382 // one is this:
383 if (command==STATUS_CHECK || command==AUTOSAVE || command==AUTO_OFFLINE){
384 int retval;
385
386 // NOT DOCUMENTED in /usr/src/linux/include/linux/hdreg.h. You
387 // have to read the IDE driver source code. Sigh.
388 // buff[0]: ATA COMMAND CODE REGISTER
389 // buff[1]: ATA FEATURES REGISTER
390 // buff[2]: ATA SECTOR_COUNT
391 // buff[3]: ATA SECTOR NUMBER
392 // buff[4]: ATA CYL LO REGISTER
393 // buff[5]: ATA CYL HI REGISTER
394 // buff[6]: ATA DEVICE HEAD
395
396 unsigned const char normal_lo=0x4f, normal_hi=0xc2;
397 unsigned const char failed_lo=0xf4, failed_hi=0x2c;
398 buff[4]=normal_lo;
399 buff[5]=normal_hi;
400
401 if ((retval=ioctl(get_fd(), HDIO_DRIVE_TASK, buff))) {
402 if (retval==-EINVAL) {
403 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
404 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
405 }
406 else
407 syserror("Error SMART Status command failed");
408 return -1;
409 }
410
411 // Cyl low and Cyl high unchanged means "Good SMART status"
412 if (buff[4]==normal_lo && buff[5]==normal_hi)
413 return 0;
414
415 // These values mean "Bad SMART status"
416 if (buff[4]==failed_lo && buff[5]==failed_hi)
417 return 1;
418
419 // We haven't gotten output that makes sense; print out some debugging info
420 syserror("Error SMART Status command failed");
421 pout("Please get assistance from " PACKAGE_HOMEPAGE "\n");
422 pout("Register values returned from SMART Status command are:\n");
423 pout("ST =0x%02x\n",(int)buff[0]);
424 pout("ERR=0x%02x\n",(int)buff[1]);
425 pout("NS =0x%02x\n",(int)buff[2]);
426 pout("SC =0x%02x\n",(int)buff[3]);
427 pout("CL =0x%02x\n",(int)buff[4]);
428 pout("CH =0x%02x\n",(int)buff[5]);
429 pout("SEL=0x%02x\n",(int)buff[6]);
430 return -1;
431 }
432
433 #if 1
434 // Note to people doing ports to other OSes -- don't worry about
435 // this block -- you can safely ignore it. I have put it here
436 // because under linux when you do IDENTIFY DEVICE to a packet
437 // device, it generates an ugly kernel syslog error message. This
438 // is harmless but frightens users. So this block detects packet
439 // devices and make IDENTIFY DEVICE fail "nicely" without a syslog
440 // error message.
441 //
442 // If you read only the ATA specs, it appears as if a packet device
443 // *might* respond to the IDENTIFY DEVICE command. This is
444 // misleading - it's because around the time that SFF-8020 was
445 // incorporated into the ATA-3/4 standard, the ATA authors were
446 // sloppy. See SFF-8020 and you will see that ATAPI devices have
447 // *always* had IDENTIFY PACKET DEVICE as a mandatory part of their
448 // command set, and return 'Command Aborted' to IDENTIFY DEVICE.
449 if (command==IDENTIFY || command==PIDENTIFY){
450 unsigned short deviceid[256];
451 // check the device identity, as seen when the system was booted
452 // or the device was FIRST registered. This will not be current
453 // if the user has subsequently changed some of the parameters. If
454 // device is a packet device, swap the command interpretations.
455 if (!ioctl(get_fd(), HDIO_GET_IDENTITY, deviceid) && (deviceid[0] & 0x8000))
456 buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
457 }
458 #endif
459
460 // We are now doing the HDIO_DRIVE_CMD type ioctl.
461 if ((ioctl(get_fd(), HDIO_DRIVE_CMD, buff)))
462 return -1;
463
464 // CHECK POWER MODE command returns information in the Sector Count
465 // register (buff[3]). Copy to return data buffer.
466 if (command==CHECK_POWER_MODE)
467 buff[HDIO_DRIVE_CMD_OFFSET]=buff[2];
468
469 // if the command returns data then copy it back
470 if (copydata)
471 memcpy(data, buff+HDIO_DRIVE_CMD_OFFSET, copydata);
472
473 return 0;
474 }
475
476 // >>>>>> Start of general SCSI specific linux code
477
478 /* Linux specific code.
479 * Historically smartmontools (and smartsuite before it) used the
480 * SCSI_IOCTL_SEND_COMMAND ioctl which is available to all linux device
481 * nodes that use the SCSI subsystem. A better interface has been available
482 * via the SCSI generic (sg) driver but this involves the extra step of
483 * mapping disk devices (e.g. /dev/sda) to the corresponding sg device
484 * (e.g. /dev/sg2). In the linux kernel 2.6 series most of the facilities of
485 * the sg driver have become available via the SG_IO ioctl which is available
486 * on all SCSI devices (on SCSI tape devices from lk 2.6.6).
487 * So the strategy below is to find out if the SG_IO ioctl is available and
488 * if so use it; failing that use the older SCSI_IOCTL_SEND_COMMAND ioctl.
489 * Should work in 2.0, 2.2, 2.4 and 2.6 series linux kernels. */
490
491 #define MAX_DXFER_LEN 1024 /* can be increased if necessary */
492 #define SEND_IOCTL_RESP_SENSE_LEN 16 /* ioctl limitation */
493 #define SG_IO_RESP_SENSE_LEN 64 /* large enough see buffer */
494 #define LSCSI_DRIVER_MASK 0xf /* mask out "suggestions" */
495 #define LSCSI_DRIVER_SENSE 0x8 /* alternate CHECK CONDITION indication */
496 #define LSCSI_DRIVER_TIMEOUT 0x6
497 #define LSCSI_DID_TIME_OUT 0x3
498 #define LSCSI_DID_BUS_BUSY 0x2
499 #define LSCSI_DID_NO_CONNECT 0x1
500
501 #ifndef SCSI_IOCTL_SEND_COMMAND
502 #define SCSI_IOCTL_SEND_COMMAND 1
503 #endif
504
505 #define SG_IO_PRESENT_UNKNOWN 0
506 #define SG_IO_PRESENT_YES 1
507 #define SG_IO_PRESENT_NO 2
508
509 static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
510 int unknown);
511 static int sisc_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report);
512
513 static int sg_io_state = SG_IO_PRESENT_UNKNOWN;
514
515 /* Preferred implementation for issuing SCSI commands in linux. This
516 * function uses the SG_IO ioctl. Return 0 if command issued successfully
517 * (various status values should still be checked). If the SCSI command
518 * cannot be issued then a negative errno value is returned. */
519 static int sg_io_cmnd_io(int dev_fd, struct scsi_cmnd_io * iop, int report,
520 int unknown)
521 {
522 #ifndef SG_IO
523 ARGUSED(dev_fd); ARGUSED(iop); ARGUSED(report);
524 return -ENOTTY;
525 #else
526 struct sg_io_hdr io_hdr;
527
528 if (report > 0) {
529 int k, j;
530 const unsigned char * ucp = iop->cmnd;
531 const char * np;
532 char buff[256];
533 const int sz = (int)sizeof(buff);
534
535 np = scsi_get_opcode_name(ucp[0]);
536 j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
537 for (k = 0; k < (int)iop->cmnd_len; ++k)
538 j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
539 if ((report > 1) &&
540 (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
541 int trunc = (iop->dxfer_len > 256) ? 1 : 0;
542
543 j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n Outgoing "
544 "data, len=%d%s:\n", (int)iop->dxfer_len,
545 (trunc ? " [only first 256 bytes shown]" : ""));
546 dStrHex((const char *)iop->dxferp,
547 (trunc ? 256 : iop->dxfer_len) , 1);
548 }
549 else
550 j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
551 pout("%s", buff);
552 }
553 memset(&io_hdr, 0, sizeof(struct sg_io_hdr));
554 io_hdr.interface_id = 'S';
555 io_hdr.cmd_len = iop->cmnd_len;
556 io_hdr.mx_sb_len = iop->max_sense_len;
557 io_hdr.dxfer_len = iop->dxfer_len;
558 io_hdr.dxferp = iop->dxferp;
559 io_hdr.cmdp = iop->cmnd;
560 io_hdr.sbp = iop->sensep;
561 /* sg_io_hdr interface timeout has millisecond units. Timeout of 0
562 defaults to 60 seconds. */
563 io_hdr.timeout = ((0 == iop->timeout) ? 60 : iop->timeout) * 1000;
564 switch (iop->dxfer_dir) {
565 case DXFER_NONE:
566 io_hdr.dxfer_direction = SG_DXFER_NONE;
567 break;
568 case DXFER_FROM_DEVICE:
569 io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
570 break;
571 case DXFER_TO_DEVICE:
572 io_hdr.dxfer_direction = SG_DXFER_TO_DEV;
573 break;
574 default:
575 pout("do_scsi_cmnd_io: bad dxfer_dir\n");
576 return -EINVAL;
577 }
578 iop->resp_sense_len = 0;
579 iop->scsi_status = 0;
580 iop->resid = 0;
581 if (ioctl(dev_fd, SG_IO, &io_hdr) < 0) {
582 if (report && (! unknown))
583 pout(" SG_IO ioctl failed, errno=%d [%s]\n", errno,
584 strerror(errno));
585 return -errno;
586 }
587 iop->resid = io_hdr.resid;
588 iop->scsi_status = io_hdr.status;
589 if (report > 0) {
590 pout(" scsi_status=0x%x, host_status=0x%x, driver_status=0x%x\n"
591 " info=0x%x duration=%d milliseconds resid=%d\n", io_hdr.status,
592 io_hdr.host_status, io_hdr.driver_status, io_hdr.info,
593 io_hdr.duration, io_hdr.resid);
594 if (report > 1) {
595 if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
596 int trunc, len;
597
598 len = iop->dxfer_len - iop->resid;
599 trunc = (len > 256) ? 1 : 0;
600 if (len > 0) {
601 pout(" Incoming data, len=%d%s:\n", len,
602 (trunc ? " [only first 256 bytes shown]" : ""));
603 dStrHex((const char*)iop->dxferp, (trunc ? 256 : len),
604 1);
605 } else
606 pout(" Incoming data trimmed to nothing by resid\n");
607 }
608 }
609 }
610
611 if (io_hdr.info | SG_INFO_CHECK) { /* error or warning */
612 int masked_driver_status = (LSCSI_DRIVER_MASK & io_hdr.driver_status);
613
614 if (0 != io_hdr.host_status) {
615 if ((LSCSI_DID_NO_CONNECT == io_hdr.host_status) ||
616 (LSCSI_DID_BUS_BUSY == io_hdr.host_status) ||
617 (LSCSI_DID_TIME_OUT == io_hdr.host_status))
618 return -ETIMEDOUT;
619 else
620 return -EIO; /* catch all */
621 }
622 if (0 != masked_driver_status) {
623 if (LSCSI_DRIVER_TIMEOUT == masked_driver_status)
624 return -ETIMEDOUT;
625 else if (LSCSI_DRIVER_SENSE != masked_driver_status)
626 return -EIO;
627 }
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)) {
633 if (report > 1) {
634 pout(" >>> Sense buffer, len=%d:\n",
635 (int)iop->resp_sense_len);
636 dStrHex((const char *)iop->sensep, iop->resp_sense_len , 1);
637 }
638 }
639 if (report) {
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]);
645 else
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]);
649 }
650 else
651 pout(" status=0x%x\n", iop->scsi_status);
652 }
653 }
654 return 0;
655 #endif
656 }
657
658 struct linux_ioctl_send_command
659 {
660 int inbufsize;
661 int outbufsize;
662 UINT8 buff[MAX_DXFER_LEN + 16];
663 };
664
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)
670 {
671 struct linux_ioctl_send_command wrk;
672 int status, buff_offset;
673 size_t len;
674
675 memcpy(wrk.buff, iop->cmnd, iop->cmnd_len);
676 buff_offset = iop->cmnd_len;
677 if (report > 0) {
678 int k, j;
679 const unsigned char * ucp = iop->cmnd;
680 const char * np;
681 char buff[256];
682 const int sz = (int)sizeof(buff);
683
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]);
688 if ((report > 1) &&
689 (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
690 int trunc = (iop->dxfer_len > 256) ? 1 : 0;
691
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);
697 }
698 else
699 j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
700 pout("%s", buff);
701 }
702 switch (iop->dxfer_dir) {
703 case DXFER_NONE:
704 wrk.inbufsize = 0;
705 wrk.outbufsize = 0;
706 break;
707 case DXFER_FROM_DEVICE:
708 wrk.inbufsize = 0;
709 if (iop->dxfer_len > MAX_DXFER_LEN)
710 return -EINVAL;
711 wrk.outbufsize = iop->dxfer_len;
712 break;
713 case DXFER_TO_DEVICE:
714 if (iop->dxfer_len > MAX_DXFER_LEN)
715 return -EINVAL;
716 memcpy(wrk.buff + buff_offset, iop->dxferp, iop->dxfer_len);
717 wrk.inbufsize = iop->dxfer_len;
718 wrk.outbufsize = 0;
719 break;
720 default:
721 pout("do_scsi_cmnd_io: bad dxfer_dir\n");
722 return -EINVAL;
723 }
724 iop->resp_sense_len = 0;
725 iop->scsi_status = 0;
726 iop->resid = 0;
727 status = ioctl(dev_fd, SCSI_IOCTL_SEND_COMMAND, &wrk);
728 if (-1 == status) {
729 if (report)
730 pout(" SCSI_IOCTL_SEND_COMMAND ioctl failed, errno=%d [%s]\n",
731 errno, strerror(errno));
732 return -errno;
733 }
734 if (0 == status) {
735 if (report > 0)
736 pout(" status=0\n");
737 if (DXFER_FROM_DEVICE == iop->dxfer_dir) {
738 memcpy(iop->dxferp, wrk.buff, iop->dxfer_len);
739 if (report > 1) {
740 int trunc = (iop->dxfer_len > 256) ? 1 : 0;
741
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);
746 }
747 }
748 return 0;
749 }
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;
759 if (report > 1) {
760 pout(" >>> Sense buffer, len=%d:\n", (int)len);
761 dStrHex((const char *)wrk.buff, len , 1);
762 }
763 }
764 if (report) {
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]);
768 }
769 else
770 pout(" status=0x%x\n", status);
771 }
772 if (iop->scsi_status > 0)
773 return 0;
774 else {
775 if (report > 0)
776 pout(" ioctl status=0x%x but scsi status=0, fail with EIO\n",
777 status);
778 return -EIO; /* give up, assume no device there */
779 }
780 }
781
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,
790 int report)
791 {
792 int res;
793
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;
804 return 0;
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);
813 default:
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 */
817 }
818 }
819
820 // >>>>>> End of general SCSI specific linux code
821
822 /////////////////////////////////////////////////////////////////////////////
823 /// Standard SCSI support
824
825 class linux_scsi_device
826 : public /*implements*/ scsi_device,
827 public /*extends*/ linux_smart_device
828 {
829 public:
830 linux_scsi_device(smart_interface * intf, const char * dev_name, const char * req_type);
831
832 virtual smart_device * autodetect_open();
833
834 virtual bool scsi_pass_through(scsi_cmnd_io * iop);
835 };
836
837 linux_scsi_device::linux_scsi_device(smart_interface * intf,
838 const char * dev_name, const char * req_type)
839 : smart_device(intf, dev_name, "scsi", req_type),
840 linux_smart_device(O_RDWR | O_NONBLOCK, O_RDONLY | O_NONBLOCK)
841 {
842 }
843
844
845 bool linux_scsi_device::scsi_pass_through(scsi_cmnd_io * iop)
846 {
847 int status = do_normal_scsi_cmnd_io(get_fd(), iop, con->reportscsiioctl);
848 if (status < 0)
849 return set_err(-status);
850 return true;
851 }
852
853 /////////////////////////////////////////////////////////////////////////////
854 /// LSI MegaRAID support
855
856 class linux_megaraid_device
857 : public /* implements */ scsi_device,
858 public /* extends */ linux_smart_device
859 {
860 public:
861 linux_megaraid_device(smart_interface *intf, const char *name,
862 unsigned int bus, unsigned int tgt);
863
864 virtual ~linux_megaraid_device() throw();
865
866 virtual smart_device * autodetect_open();
867
868 virtual bool open();
869 virtual bool close();
870
871 virtual bool scsi_pass_through(scsi_cmnd_io *iop);
872
873 private:
874 unsigned int m_disknum;
875 unsigned int m_busnum;
876 unsigned int m_hba;
877 int m_fd;
878
879 bool (linux_megaraid_device::*pt_cmd)(int cdblen, void *cdb, int dataLen, void *data,
880 int senseLen, void *sense, int report);
881 bool megasas_cmd(int cdbLen, void *cdb, int dataLen, void *data,
882 int senseLen, void *sense, int report);
883 bool megadev_cmd(int cdbLen, void *cdb, int dataLen, void *data,
884 int senseLen, void *sense, int report);
885 };
886
887 linux_megaraid_device::linux_megaraid_device(smart_interface *intf,
888 const char *dev_name, unsigned int bus, unsigned int tgt)
889 : smart_device(intf, dev_name, "megaraid", "megaraid"),
890 linux_smart_device(O_RDWR | O_NONBLOCK),
891 m_disknum(tgt), m_busnum(bus), m_hba(0),
892 m_fd(-1), pt_cmd(0)
893 {
894 set_info().info_name = strprintf("%s [megaraid_disk_%02d]", dev_name, m_disknum);
895 }
896
897 linux_megaraid_device::~linux_megaraid_device() throw()
898 {
899 if (m_fd >= 0)
900 ::close(m_fd);
901 }
902
903 smart_device * linux_megaraid_device::autodetect_open()
904 {
905 // Open device
906 if (!open())
907 return this;
908
909 // The code below is based on smartd.cpp:SCSIFilterKnown()
910 if (strcmp(get_req_type(), "megaraid"))
911 return this;
912
913 // Get INQUIRY
914 unsigned char req_buff[64] = {0, };
915 int req_len = 36;
916 if (scsiStdInquiry(this, req_buff, req_len)) {
917 close();
918 set_err(EIO, "INQUIRY failed");
919 return this;
920 }
921
922 int avail_len = req_buff[4] + 5;
923 int len = (avail_len < req_len ? avail_len : req_len);
924 if (len < 36)
925 return this;
926
927 printf("Got MegaRAID inquiry.. %s\n", req_buff+8);
928
929 // Use INQUIRY to detect type
930 smart_device * newdev = 0;
931 try {
932 // SAT or USB ?
933 newdev = smi()->autodetect_sat_device(this, req_buff, len);
934 if (newdev)
935 // NOTE: 'this' is now owned by '*newdev'
936 return newdev;
937 }
938 catch (...) {
939 // Cleanup if exception occurs after newdev was allocated
940 delete newdev;
941 throw;
942 }
943
944 // Nothing special found
945 return this;
946 }
947
948
949 bool linux_megaraid_device::open()
950 {
951 char line[128];
952 int mjr, n1;
953 FILE *fp;
954 int report = con->reportscsiioctl;
955
956 if (!linux_smart_device::open())
957 return false;
958
959 /* Get device HBA */
960 struct sg_scsi_id sgid;
961 if (ioctl(get_fd(), SG_GET_SCSI_ID, &sgid) == 0) {
962 m_hba = sgid.host_no;
963 }
964 else if (ioctl(get_fd(), SCSI_IOCTL_GET_BUS_NUMBER, &m_hba) != 0) {
965 int err = errno;
966 linux_smart_device::close();
967 return set_err(err, "can't get bus number");
968 }
969
970 /* Perform mknod of device ioctl node */
971 fp = fopen("/proc/devices", "r");
972 while (fgets(line, sizeof(line), fp) != NULL) {
973 n1=0;
974 if (sscanf(line, "%d megaraid_sas_ioctl%n", &mjr, &n1) == 1 && n1 == 22) {
975 n1=mknod("/dev/megaraid_sas_ioctl_node", S_IFCHR, makedev(mjr, 0));
976 if(report > 0)
977 printf("Creating /dev/megaraid_sas_ioctl_node = %d\n", n1 >= 0 ? 0 : errno);
978 if (n1 >= 0 || errno == EEXIST)
979 break;
980 }
981 else if (sscanf(line, "%d megadev%n", &mjr, &n1) == 1 && n1 == 11) {
982 n1=mknod("/dev/megadev0", S_IFCHR, makedev(mjr, 0));
983 if(report > 0)
984 printf("Creating /dev/megadev0 = %d\n", n1 >= 0 ? 0 : errno);
985 if (n1 >= 0 || errno == EEXIST)
986 break;
987 }
988 }
989 fclose(fp);
990
991 /* Open Device IOCTL node */
992 if ((m_fd = ::open("/dev/megaraid_sas_ioctl_node", O_RDWR)) >= 0) {
993 pt_cmd = &linux_megaraid_device::megasas_cmd;
994 }
995 else if ((m_fd = ::open("/dev/megadev0", O_RDWR)) >= 0) {
996 pt_cmd = &linux_megaraid_device::megadev_cmd;
997 }
998 else {
999 int err = errno;
1000 linux_smart_device::close();
1001 return set_err(err, "cannot open /dev/megaraid_sas_ioctl_node or /dev/megadev0");
1002 }
1003
1004 return true;
1005 }
1006
1007 bool linux_megaraid_device::close()
1008 {
1009 if (m_fd >= 0)
1010 ::close(m_fd);
1011 m_fd = -1; m_hba = 0; pt_cmd = 0;
1012 return linux_smart_device::close();
1013 }
1014
1015 bool linux_megaraid_device::scsi_pass_through(scsi_cmnd_io *iop)
1016 {
1017 int report = con->reportscsiioctl;
1018
1019 if (report > 0) {
1020 int k, j;
1021 const unsigned char * ucp = iop->cmnd;
1022 const char * np;
1023 char buff[256];
1024 const int sz = (int)sizeof(buff);
1025
1026 np = scsi_get_opcode_name(ucp[0]);
1027 j = snprintf(buff, sz, " [%s: ", np ? np : "<unknown opcode>");
1028 for (k = 0; k < (int)iop->cmnd_len; ++k)
1029 j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "%02x ", ucp[k]);
1030 if ((report > 1) &&
1031 (DXFER_TO_DEVICE == iop->dxfer_dir) && (iop->dxferp)) {
1032 int trunc = (iop->dxfer_len > 256) ? 1 : 0;
1033
1034 j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n Outgoing "
1035 "data, len=%d%s:\n", (int)iop->dxfer_len,
1036 (trunc ? " [only first 256 bytes shown]" : ""));
1037 dStrHex((const char *)iop->dxferp,
1038 (trunc ? 256 : iop->dxfer_len) , 1);
1039 }
1040 else
1041 j += snprintf(&buff[j], (sz > j ? (sz - j) : 0), "]\n");
1042 pout("%s", buff);
1043 }
1044
1045 /* Controller rejects Enable SMART and Test Unit Ready */
1046 if (iop->cmnd[0] == 0x00)
1047 return true;
1048 if (iop->cmnd[0] == 0x85 && iop->cmnd[1] == 0x06) {
1049 if(report > 0)
1050 pout("Rejecting SMART/ATA command to controller\n");
1051 // Emulate SMART STATUS CHECK drive reply
1052 // smartctl fail to work without this
1053 if(iop->cmnd[2]==0x2c) {
1054 iop->resp_sense_len=22;
1055 iop->sensep[0]=0x72; // response code
1056 iop->sensep[7]=0x0e; // no idea what it is, copied from sat device answer
1057 iop->sensep[8]=0x09; //
1058 iop->sensep[17]=0x4f; // lm
1059 iop->sensep[19]=0xc2; // lh
1060 }
1061 return true;
1062 }
1063
1064 if (pt_cmd == NULL)
1065 return false;
1066 return (this->*pt_cmd)(iop->cmnd_len, iop->cmnd,
1067 iop->dxfer_len, iop->dxferp,
1068 iop->max_sense_len, iop->sensep, report);
1069 }
1070
1071 /* Issue passthrough scsi command to PERC5/6 controllers */
1072 bool linux_megaraid_device::megasas_cmd(int cdbLen, void *cdb,
1073 int dataLen, void *data,
1074 int /*senseLen*/, void * /*sense*/, int /*report*/)
1075 {
1076 struct megasas_pthru_frame *pthru;
1077 struct megasas_iocpacket uio;
1078 int rc;
1079
1080 memset(&uio, 0, sizeof(uio));
1081 pthru = (struct megasas_pthru_frame *)uio.frame.raw;
1082 pthru->cmd = MFI_CMD_PD_SCSI_IO;
1083 pthru->cmd_status = 0xFF;
1084 pthru->scsi_status = 0x0;
1085 pthru->target_id = m_disknum;
1086 pthru->lun = 0;
1087 pthru->cdb_len = cdbLen;
1088 pthru->timeout = 0;
1089 pthru->flags = MFI_FRAME_DIR_READ;
1090 pthru->sge_count = 1;
1091 pthru->data_xfer_len = dataLen;
1092 pthru->sgl.sge32[0].phys_addr = (intptr_t)data;
1093 pthru->sgl.sge32[0].length = (uint32_t)dataLen;
1094 memcpy(pthru->cdb, cdb, cdbLen);
1095
1096 uio.host_no = m_hba;
1097 uio.sge_count = 1;
1098 uio.sgl_off = offsetof(struct megasas_pthru_frame, sgl);
1099 uio.sgl[0].iov_base = data;
1100 uio.sgl[0].iov_len = dataLen;
1101
1102 rc = 0;
1103 errno = 0;
1104 rc = ioctl(m_fd, MEGASAS_IOC_FIRMWARE, &uio);
1105 if (pthru->cmd_status || rc != 0) {
1106 if (pthru->cmd_status == 12) {
1107 return set_err(EIO, "megasas_cmd: Device %d does not exist\n", m_disknum);
1108 }
1109 return set_err((errno ? errno : EIO), "megasas_cmd result: %d.%d = %d/%d",
1110 m_hba, m_disknum, errno,
1111 pthru->cmd_status);
1112 }
1113 return true;
1114 }
1115
1116 /* Issue passthrough scsi commands to PERC2/3/4 controllers */
1117 bool linux_megaraid_device::megadev_cmd(int cdbLen, void *cdb,
1118 int dataLen, void *data,
1119 int senseLen, void *sense, int /*report*/)
1120 {
1121 struct uioctl_t uio;
1122 int rc;
1123
1124 sense = NULL;
1125 senseLen = 0;
1126
1127 /* Don't issue to the controller */
1128 if (m_disknum == 7)
1129 return false;
1130
1131 memset(&uio, 0, sizeof(uio));
1132 uio.inlen = dataLen;
1133 uio.outlen = dataLen;
1134
1135 memset(data, 0, dataLen);
1136 uio.ui.fcs.opcode = 0x80; // M_RD_IOCTL_CMD
1137 uio.ui.fcs.adapno = MKADAP(m_hba);
1138
1139 uio.data.pointer = (uint8_t *)data;
1140
1141 uio.mbox.cmd = MEGA_MBOXCMD_PASSTHRU;
1142 uio.mbox.xferaddr = (intptr_t)&uio.pthru;
1143
1144 uio.pthru.ars = 1;
1145 uio.pthru.timeout = 2;
1146 uio.pthru.channel = 0;
1147 uio.pthru.target = m_disknum;
1148 uio.pthru.cdblen = cdbLen;
1149 uio.pthru.reqsenselen = MAX_REQ_SENSE_LEN;
1150 uio.pthru.dataxferaddr = (intptr_t)data;
1151 uio.pthru.dataxferlen = dataLen;
1152 memcpy(uio.pthru.cdb, cdb, cdbLen);
1153
1154 rc=ioctl(m_fd, MEGAIOCCMD, &uio);
1155 if (uio.pthru.scsistatus || rc != 0) {
1156 return set_err((errno ? errno : EIO), "megadev_cmd result: %d.%d = %d/%d",
1157 m_hba, m_disknum, errno,
1158 uio.pthru.scsistatus);
1159 }
1160 return true;
1161 }
1162
1163 /////////////////////////////////////////////////////////////////////////////
1164 /// CCISS RAID support
1165
1166 #ifdef HAVE_LINUX_CCISS_IOCTL_H
1167
1168 class linux_cciss_device
1169 : public /*implements*/ scsi_device,
1170 public /*extends*/ linux_smart_device
1171 {
1172 public:
1173 linux_cciss_device(smart_interface * intf, const char * name, unsigned char disknum);
1174
1175 virtual bool scsi_pass_through(scsi_cmnd_io * iop);
1176
1177 private:
1178 unsigned char m_disknum; ///< Disk number.
1179 };
1180
1181 linux_cciss_device::linux_cciss_device(smart_interface * intf,
1182 const char * dev_name, unsigned char disknum)
1183 : smart_device(intf, dev_name, "cciss", "cciss"),
1184 linux_smart_device(O_RDWR | O_NONBLOCK),
1185 m_disknum(disknum)
1186 {
1187 set_info().info_name = strprintf("%s [cciss_disk_%02d]", dev_name, disknum);
1188 }
1189
1190 bool linux_cciss_device::scsi_pass_through(scsi_cmnd_io * iop)
1191 {
1192 int status = cciss_io_interface(get_fd(), m_disknum, iop, con->reportscsiioctl);
1193 if (status < 0)
1194 return set_err(-status);
1195 return true;
1196 }
1197
1198 #endif // HAVE_LINUX_CCISS_IOCTL_H
1199
1200 /////////////////////////////////////////////////////////////////////////////
1201 /// AMCC/3ware RAID support
1202
1203 class linux_escalade_device
1204 : public /*implements*/ ata_device,
1205 public /*extends*/ linux_smart_device
1206 {
1207 public:
1208 enum escalade_type_t {
1209 AMCC_3WARE_678K,
1210 AMCC_3WARE_678K_CHAR,
1211 AMCC_3WARE_9000_CHAR
1212 };
1213
1214 linux_escalade_device(smart_interface * intf, const char * dev_name,
1215 escalade_type_t escalade_type, int disknum);
1216
1217 virtual bool open();
1218
1219 virtual bool ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out);
1220
1221 private:
1222 escalade_type_t m_escalade_type; ///< Controller type
1223 int m_disknum; ///< Disk number.
1224 };
1225
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)
1231 {
1232 set_info().info_name = strprintf("%s [3ware_disk_%02d]", dev_name, disknum);
1233 }
1234
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 int setup_3ware_nodes(const char *nodename, const char *driver_name) {
1240 int tw_major = 0;
1241 int index = 0;
1242 char majorstring[MAJOR_STRING_LENGTH+1];
1243 char device_name[DEVICE_STRING_LENGTH+1];
1244 char nodestring[NODE_STRING_LENGTH];
1245 struct stat stat_buf;
1246 FILE *file;
1247 int retval = 0;
1248 #ifdef WITH_SELINUX
1249 security_context_t orig_context = NULL;
1250 security_context_t node_context = NULL;
1251 int selinux_enabled = is_selinux_enabled();
1252 int selinux_enforced = security_getenforce();
1253 #endif
1254
1255
1256 /* First try to open up /proc/devices */
1257 if (!(file = fopen("/proc/devices", "r"))) {
1258 pout("Error opening /proc/devices to check/create 3ware device nodes\n");
1259 syserror("fopen");
1260 return 0; // don't fail here: user might not have /proc !
1261 }
1262
1263 /* Attempt to get device major number */
1264 while (EOF != fscanf(file, "%3s %32s", majorstring, device_name)) {
1265 majorstring[MAJOR_STRING_LENGTH]='\0';
1266 device_name[DEVICE_STRING_LENGTH]='\0';
1267 if (!strncmp(device_name, nodename, DEVICE_STRING_LENGTH)) {
1268 tw_major = atoi(majorstring);
1269 break;
1270 }
1271 }
1272 fclose(file);
1273
1274 /* See if we found a major device number */
1275 if (!tw_major) {
1276 pout("No major number for /dev/%s listed in /proc/devices. Is the %s driver loaded?\n", nodename, driver_name);
1277 return 2;
1278 }
1279 #ifdef WITH_SELINUX
1280 /* Prepare a database of contexts for files in /dev
1281 * and save the current context */
1282 if (selinux_enabled) {
1283 if (matchpathcon_init_prefix(NULL, "/dev") < 0)
1284 pout("Error initializing contexts database for /dev");
1285 if (getfscreatecon(&orig_context) < 0) {
1286 pout("Error retrieving original SELinux fscreate context");
1287 if (selinux_enforced)
1288 matchpathcon_fini();
1289 return 6;
1290 }
1291 }
1292 #endif
1293 /* Now check if nodes are correct */
1294 for (index=0; index<16; index++) {
1295 sprintf(nodestring, "/dev/%s%d", nodename, index);
1296 #ifdef WITH_SELINUX
1297 /* Get context of the node and set it as the default */
1298 if (selinux_enabled) {
1299 if (matchpathcon(nodestring, S_IRUSR | S_IWUSR, &node_context) < 0) {
1300 pout("Could not retrieve context for %s", nodestring);
1301 if (selinux_enforced) {
1302 retval = 6;
1303 break;
1304 }
1305 }
1306 if (setfscreatecon(node_context) < 0) {
1307 pout ("Error setting default fscreate context");
1308 if (selinux_enforced) {
1309 retval = 6;
1310 break;
1311 }
1312 }
1313 }
1314 #endif
1315 /* Try to stat the node */
1316 if ((stat(nodestring, &stat_buf))) {
1317 pout("Node %s does not exist and must be created. Check the udev rules.\n", nodestring);
1318 /* Create a new node if it doesn't exist */
1319 if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
1320 pout("problem creating 3ware device nodes %s", nodestring);
1321 syserror("mknod");
1322 retval = 3;
1323 break;
1324 } else {
1325 #ifdef WITH_SELINUX
1326 if (selinux_enabled && node_context) {
1327 freecon(node_context);
1328 node_context = NULL;
1329 }
1330 #endif
1331 continue;
1332 }
1333 }
1334
1335 /* See if nodes major and minor numbers are correct */
1336 if ((tw_major != (int)(major(stat_buf.st_rdev))) ||
1337 (index != (int)(minor(stat_buf.st_rdev))) ||
1338 (!S_ISCHR(stat_buf.st_mode))) {
1339 pout("Node %s has wrong major/minor number and must be created anew."
1340 " Check the udev rules.\n", nodestring);
1341 /* Delete the old node */
1342 if (unlink(nodestring)) {
1343 pout("problem unlinking stale 3ware device node %s", nodestring);
1344 syserror("unlink");
1345 retval = 4;
1346 break;
1347 }
1348
1349 /* Make a new node */
1350 if (mknod(nodestring, S_IFCHR|0600, makedev(tw_major, index))) {
1351 pout("problem creating 3ware device nodes %s", nodestring);
1352 syserror("mknod");
1353 retval = 5;
1354 break;
1355 }
1356 }
1357 #ifdef WITH_SELINUX
1358 if (selinux_enabled && node_context) {
1359 freecon(node_context);
1360 node_context = NULL;
1361 }
1362 #endif
1363 }
1364
1365 #ifdef WITH_SELINUX
1366 if (selinux_enabled) {
1367 if(setfscreatecon(orig_context) < 0) {
1368 pout("Error re-setting original fscreate context");
1369 if (selinux_enforced)
1370 retval = 6;
1371 }
1372 if(orig_context)
1373 freecon(orig_context);
1374 if(node_context)
1375 freecon(node_context);
1376 matchpathcon_fini();
1377 }
1378 #endif
1379 return retval;
1380 }
1381
1382 bool linux_escalade_device::open()
1383 {
1384 if (m_escalade_type == AMCC_3WARE_9000_CHAR || m_escalade_type == AMCC_3WARE_678K_CHAR) {
1385 // the device nodes for these controllers are dynamically assigned,
1386 // so we need to check that they exist with the correct major
1387 // numbers and if not, create them
1388 const char * node = (m_escalade_type == AMCC_3WARE_9000_CHAR ? "twa" : "twe" );
1389 const char * driver = (m_escalade_type == AMCC_3WARE_9000_CHAR ? "3w-9xxx": "3w-xxxx");
1390 if (setup_3ware_nodes(node, driver))
1391 return set_err((errno ? errno : ENXIO), "setup_3ware_nodes(\"%s\", \"%s\") failed", node, driver);
1392 }
1393 // Continue with default open
1394 return linux_smart_device::open();
1395 }
1396
1397 // TODO: Function no longer useful
1398 //void printwarning(smart_command_set command);
1399
1400 // PURPOSE
1401 // This is an interface routine meant to isolate the OS dependent
1402 // parts of the code, and to provide a debugging interface. Each
1403 // different port and OS needs to provide it's own interface. This
1404 // is the linux interface to the 3ware 3w-xxxx driver. It allows ATA
1405 // commands to be passed through the SCSI driver.
1406 // DETAILED DESCRIPTION OF ARGUMENTS
1407 // fd: is the file descriptor provided by open()
1408 // disknum is the disk number (0 to 15) in the RAID array
1409 // escalade_type indicates the type of controller type, and if scsi or char interface is used
1410 // command: defines the different operations.
1411 // select: additional input data if needed (which log, which type of
1412 // self-test).
1413 // data: location to write output data, if needed (512 bytes).
1414 // Note: not all commands use all arguments.
1415 // RETURN VALUES
1416 // -1 if the command failed
1417 // 0 if the command succeeded,
1418 // STATUS_CHECK routine:
1419 // -1 if the command failed
1420 // 0 if the command succeeded and disk SMART status is "OK"
1421 // 1 if the command succeeded and disk SMART status is "FAILING"
1422
1423
1424 /* 512 is the max payload size: increase if needed */
1425 #define BUFFER_LEN_678K ( sizeof(TW_Ioctl) ) // 1044 unpacked, 1041 packed
1426 #define BUFFER_LEN_678K_CHAR ( sizeof(TW_New_Ioctl)+512-1 ) // 1539 unpacked, 1536 packed
1427 #define BUFFER_LEN_9000 ( sizeof(TW_Ioctl_Buf_Apache)+512-1 ) // 2051 unpacked, 2048 packed
1428 #define TW_IOCTL_BUFFER_SIZE ( MAX(MAX(BUFFER_LEN_678K, BUFFER_LEN_9000), BUFFER_LEN_678K_CHAR) )
1429
1430 bool linux_escalade_device::ata_pass_through(const ata_cmd_in & in, ata_cmd_out & out)
1431 {
1432 if (!ata_cmd_is_ok(in,
1433 true, // data_out_support
1434 false, // TODO: multi_sector_support
1435 true) // ata_48bit_support
1436 )
1437 return false;
1438
1439 // Used by both the SCSI and char interfaces
1440 TW_Passthru *passthru=NULL;
1441 char ioctl_buffer[TW_IOCTL_BUFFER_SIZE];
1442
1443 // only used for SCSI device interface
1444 TW_Ioctl *tw_ioctl=NULL;
1445 TW_Output *tw_output=NULL;
1446
1447 // only used for 6000/7000/8000 char device interface
1448 TW_New_Ioctl *tw_ioctl_char=NULL;
1449
1450 // only used for 9000 character device interface
1451 TW_Ioctl_Buf_Apache *tw_ioctl_apache=NULL;
1452
1453 memset(ioctl_buffer, 0, TW_IOCTL_BUFFER_SIZE);
1454
1455 // TODO: Handle controller differences by different classes
1456 if (m_escalade_type==AMCC_3WARE_9000_CHAR) {
1457 tw_ioctl_apache = (TW_Ioctl_Buf_Apache *)ioctl_buffer;
1458 tw_ioctl_apache->driver_command.control_code = TW_IOCTL_FIRMWARE_PASS_THROUGH;
1459 tw_ioctl_apache->driver_command.buffer_length = 512; /* payload size */
1460 passthru = (TW_Passthru *)&(tw_ioctl_apache->firmware_command.command.oldcommand);
1461 }
1462 else if (m_escalade_type==AMCC_3WARE_678K_CHAR) {
1463 tw_ioctl_char = (TW_New_Ioctl *)ioctl_buffer;
1464 tw_ioctl_char->data_buffer_length = 512;
1465 passthru = (TW_Passthru *)&(tw_ioctl_char->firmware_command);
1466 }
1467 else if (m_escalade_type==AMCC_3WARE_678K) {
1468 tw_ioctl = (TW_Ioctl *)ioctl_buffer;
1469 tw_ioctl->cdb[0] = TW_IOCTL;
1470 tw_ioctl->opcode = TW_ATA_PASSTHRU;
1471 tw_ioctl->input_length = 512; // correct even for non-data commands
1472 tw_ioctl->output_length = 512; // correct even for non-data commands
1473 tw_output = (TW_Output *)tw_ioctl;
1474 passthru = (TW_Passthru *)&(tw_ioctl->input_data);
1475 }
1476 else {
1477 return set_err(ENOSYS,
1478 "Unrecognized escalade_type %d in linux_3ware_command_interface(disk %d)\n"
1479 "Please contact " PACKAGE_BUGREPORT "\n", (int)m_escalade_type, m_disknum);
1480 }
1481
1482 // Same for (almost) all commands - but some reset below
1483 passthru->byte0.opcode = TW_OP_ATA_PASSTHRU;
1484 passthru->request_id = 0xFF;
1485 passthru->unit = m_disknum;
1486 passthru->status = 0;
1487 passthru->flags = 0x1;
1488
1489 // Set registers
1490 {
1491 const ata_in_regs_48bit & r = in.in_regs;
1492 passthru->features = r.features_16;
1493 passthru->sector_count = r.sector_count_16;
1494 passthru->sector_num = r.lba_low_16;
1495 passthru->cylinder_lo = r.lba_mid_16;
1496 passthru->cylinder_hi = r.lba_high_16;
1497 passthru->drive_head = r.device;
1498 passthru->command = r.command;
1499 }
1500
1501 // Is this a command that reads or returns 512 bytes?
1502 // passthru->param values are:
1503 // 0x0 - non data command without TFR write check,
1504 // 0x8 - non data command with TFR write check,
1505 // 0xD - data command that returns data to host from device
1506 // 0xF - data command that writes data from host to device
1507 // passthru->size values are 0x5 for non-data and 0x07 for data
1508 bool readdata = false;
1509 if (in.direction == ata_cmd_in::data_in) {
1510 readdata=true;
1511 passthru->byte0.sgloff = 0x5;
1512 passthru->size = 0x7; // TODO: Other value for multi-sector ?
1513 passthru->param = 0xD;
1514 // For 64-bit to work correctly, up the size of the command packet
1515 // in dwords by 1 to account for the 64-bit single sgl 'address'
1516 // field. Note that this doesn't agree with the typedefs but it's
1517 // right (agree with kernel driver behavior/typedefs).
1518 if (m_escalade_type==AMCC_3WARE_9000_CHAR && sizeof(long)==8)
1519 passthru->size++;
1520 }
1521 else if (in.direction == ata_cmd_in::no_data) {
1522 // Non data command -- but doesn't use large sector
1523 // count register values.
1524 passthru->byte0.sgloff = 0x0;
1525 passthru->size = 0x5;
1526 passthru->param = 0x8;
1527 passthru->sector_count = 0x0;
1528 }
1529 else if (in.direction == ata_cmd_in::data_out) {
1530 if (m_escalade_type == AMCC_3WARE_9000_CHAR)
1531 memcpy(tw_ioctl_apache->data_buffer, in.buffer, in.size);
1532 else if (m_escalade_type == AMCC_3WARE_678K_CHAR)
1533 memcpy(tw_ioctl_char->data_buffer, in.buffer, in.size);
1534 else {
1535 // COMMAND NOT SUPPORTED VIA SCSI IOCTL INTERFACE
1536 // memcpy(tw_output->output_data, data, 512);
1537 // printwarning(command); // TODO: Parameter no longer valid
1538 return set_err(ENOTSUP, "DATA OUT not supported for this 3ware controller type");
1539 }
1540 passthru->byte0.sgloff = 0x5;
1541 passthru->size = 0x7; // TODO: Other value for multi-sector ?
1542 passthru->param = 0xF; // PIO data write
1543 if (m_escalade_type==AMCC_3WARE_9000_CHAR && sizeof(long)==8)
1544 passthru->size++;
1545 }
1546 else
1547 set_err(EINVAL);
1548
1549 // Now send the command down through an ioctl()
1550 int ioctlreturn;
1551 if (m_escalade_type==AMCC_3WARE_9000_CHAR)
1552 ioctlreturn=ioctl(get_fd(), TW_IOCTL_FIRMWARE_PASS_THROUGH, tw_ioctl_apache);
1553 else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
1554 ioctlreturn=ioctl(get_fd(), TW_CMD_PACKET_WITH_DATA, tw_ioctl_char);
1555 else
1556 ioctlreturn=ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND, tw_ioctl);
1557
1558 // Deal with the different error cases
1559 if (ioctlreturn) {
1560 if (AMCC_3WARE_678K==m_escalade_type
1561 && in.in_regs.command==ATA_SMART_CMD
1562 && ( in.in_regs.features == ATA_SMART_AUTO_OFFLINE
1563 || in.in_regs.features == ATA_SMART_AUTOSAVE )
1564 && in.in_regs.lba_low) {
1565 // error here is probably a kernel driver whose version is too old
1566 // printwarning(command); // TODO: Parameter no longer valid
1567 return set_err(ENOTSUP, "Probably kernel driver too old");
1568 }
1569 return set_err(EIO);
1570 }
1571
1572 // The passthru structure is valid after return from an ioctl if:
1573 // - we are using the character interface OR
1574 // - we are using the SCSI interface and this is a NON-READ-DATA command
1575 // For SCSI interface, note that we set passthru to a different
1576 // value after ioctl().
1577 if (AMCC_3WARE_678K==m_escalade_type) {
1578 if (readdata)
1579 passthru=NULL;
1580 else
1581 passthru=(TW_Passthru *)&(tw_output->output_data);
1582 }
1583
1584 // See if the ATA command failed. Now that we have returned from
1585 // the ioctl() call, if passthru is valid, then:
1586 // - passthru->status contains the 3ware controller STATUS
1587 // - passthru->command contains the ATA STATUS register
1588 // - passthru->features contains the ATA ERROR register
1589 //
1590 // Check bits 0 (error bit) and 5 (device fault) of the ATA STATUS
1591 // If bit 0 (error bit) is set, then ATA ERROR register is valid.
1592 // While we *might* decode the ATA ERROR register, at the moment it
1593 // doesn't make much sense: we don't care in detail why the error
1594 // happened.
1595
1596 if (passthru && (passthru->status || (passthru->command & 0x21))) {
1597 return set_err(EIO);
1598 }
1599
1600 // If this is a read data command, copy data to output buffer
1601 if (readdata) {
1602 if (m_escalade_type==AMCC_3WARE_9000_CHAR)
1603 memcpy(in.buffer, tw_ioctl_apache->data_buffer, in.size);
1604 else if (m_escalade_type==AMCC_3WARE_678K_CHAR)
1605 memcpy(in.buffer, tw_ioctl_char->data_buffer, in.size);
1606 else
1607 memcpy(in.buffer, tw_output->output_data, in.size);
1608 }
1609
1610 // Return register values
1611 {
1612 ata_out_regs_48bit & r = out.out_regs;
1613 r.error = passthru->features;
1614 r.sector_count_16 = passthru->sector_count;
1615 r.lba_low_16 = passthru->sector_num;
1616 r.lba_mid_16 = passthru->cylinder_lo;
1617 r.lba_high_16 = passthru->cylinder_hi;
1618 r.device = passthru->drive_head;
1619 r.status = passthru->command;
1620 }
1621
1622 // look for nonexistent devices/ports
1623 if ( in.in_regs.command == ATA_IDENTIFY_DEVICE
1624 && !nonempty((unsigned char *)in.buffer, in.size)) {
1625 return set_err(ENODEV, "No drive on port %d", m_disknum);
1626 }
1627
1628 return true;
1629 }
1630
1631
1632 /////////////////////////////////////////////////////////////////////////////
1633 /// Areca RAID support
1634
1635 class linux_areca_device
1636 : public /*implements*/ ata_device_with_command_set,
1637 public /*extends*/ linux_smart_device
1638 {
1639 public:
1640 linux_areca_device(smart_interface * intf, const char * dev_name, int disknum);
1641
1642 protected:
1643 virtual int ata_command_interface(smart_command_set command, int select, char * data);
1644
1645 private:
1646 int m_disknum; ///< Disk number.
1647 };
1648
1649
1650 // PURPOSE
1651 // This is an interface routine meant to isolate the OS dependent
1652 // parts of the code, and to provide a debugging interface. Each
1653 // different port and OS needs to provide it's own interface. This
1654 // is the linux interface to the Areca "arcmsr" driver. It allows ATA
1655 // commands to be passed through the SCSI driver.
1656 // DETAILED DESCRIPTION OF ARGUMENTS
1657 // fd: is the file descriptor provided by open()
1658 // disknum is the disk number (0 to 15) in the RAID array
1659 // command: defines the different operations.
1660 // select: additional input data if needed (which log, which type of
1661 // self-test).
1662 // data: location to write output data, if needed (512 bytes).
1663 // Note: not all commands use all arguments.
1664 // RETURN VALUES
1665 // -1 if the command failed
1666 // 0 if the command succeeded,
1667 // STATUS_CHECK routine:
1668 // -1 if the command failed
1669 // 0 if the command succeeded and disk SMART status is "OK"
1670 // 1 if the command succeeded and disk SMART status is "FAILING"
1671
1672
1673 /*DeviceType*/
1674 #define ARECA_SATA_RAID 0x90000000
1675 /*FunctionCode*/
1676 #define FUNCTION_READ_RQBUFFER 0x0801
1677 #define FUNCTION_WRITE_WQBUFFER 0x0802
1678 #define FUNCTION_CLEAR_RQBUFFER 0x0803
1679 #define FUNCTION_CLEAR_WQBUFFER 0x0804
1680
1681 /* ARECA IO CONTROL CODE*/
1682 #define ARCMSR_IOCTL_READ_RQBUFFER (ARECA_SATA_RAID | FUNCTION_READ_RQBUFFER)
1683 #define ARCMSR_IOCTL_WRITE_WQBUFFER (ARECA_SATA_RAID | FUNCTION_WRITE_WQBUFFER)
1684 #define ARCMSR_IOCTL_CLEAR_RQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_RQBUFFER)
1685 #define ARCMSR_IOCTL_CLEAR_WQBUFFER (ARECA_SATA_RAID | FUNCTION_CLEAR_WQBUFFER)
1686 #define ARECA_SIG_STR "ARCMSR"
1687
1688 // The SRB_IO_CONTROL & SRB_BUFFER structures are used to communicate(to/from) to areca driver
1689 typedef struct _SRB_IO_CONTROL
1690 {
1691 unsigned int HeaderLength;
1692 unsigned char Signature[8];
1693 unsigned int Timeout;
1694 unsigned int ControlCode;
1695 unsigned int ReturnCode;
1696 unsigned int Length;
1697 } sSRB_IO_CONTROL;
1698
1699 typedef struct _SRB_BUFFER
1700 {
1701 sSRB_IO_CONTROL srbioctl;
1702 unsigned char ioctldatabuffer[1032]; // the buffer to put the command data to/from firmware
1703 } sSRB_BUFFER;
1704
1705 // Looks in /proc/scsi to suggest correct areca devices
1706 // If hint not NULL, return device path guess
1707 int find_areca_in_proc(char *hint) {
1708
1709 const char* proc_format_string="host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n";
1710
1711 // check data formwat
1712 FILE *fp=fopen("/proc/scsi/sg/device_hdr", "r");
1713 if (!fp) {
1714 pout("Unable to open /proc/scsi/sg/device_hdr for reading\n");
1715 return 1;
1716 }
1717
1718 // get line, compare to format
1719 char linebuf[256];
1720 linebuf[255]='\0';
1721 char *out = fgets(linebuf, 256, fp);
1722 fclose(fp);
1723 if (!out) {
1724 pout("Unable to read contents of /proc/scsi/sg/device_hdr\n");
1725 return 2;
1726 }
1727
1728 if (strcmp(linebuf, proc_format_string)) {
1729 // wrong format!
1730 // Fix this by comparing only tokens not white space!!
1731 pout("Unexpected format %s in /proc/scsi/sg/device_hdr\n", proc_format_string);
1732 return 3;
1733 }
1734
1735 // Format is understood, now search for correct device
1736 fp=fopen("/proc/scsi/sg/devices", "r");
1737 if (!fp) return 1;
1738 int host, chan, id, lun, type, opens, qdepth, busy, online;
1739 int dev=-1;
1740 int found=0;
1741 // search all lines of /proc/scsi/sg/devices
1742 while (9 == fscanf(fp, "%d %d %d %d %d %d %d %d %d", &host, &chan, &id, &lun, &type, &opens, &qdepth, &busy, &online)) {
1743 dev++;
1744 if (id == 16 && type == 3) {
1745 // devices with id=16 and type=3 might be Areca controllers
1746 if (!found && hint) {
1747 sprintf(hint, "/dev/sg%d", dev);
1748 }
1749 pout("Device /dev/sg%d appears to be an Areca controller.\n", dev);
1750 found++;
1751 }
1752 }
1753 fclose(fp);
1754 return 0;
1755 }
1756
1757
1758
1759 void dumpdata( unsigned char *block, int len)
1760 {
1761 int ln = (len / 16) + 1; // total line#
1762 unsigned char c;
1763 int pos = 0;
1764
1765 printf(" Address = %p, Length = (0x%x)%d\n", block, len, len);
1766 printf(" 0 1 2 3 4 5 6 7 8 9 A B C D E F ASCII \n");
1767 printf("=====================================================================\n");
1768
1769 for ( int l = 0; l < ln && len; l++ )
1770 {
1771 // printf the line# and the HEX data
1772 // if a line data length < 16 then append the space to the tail of line to reach 16 chars
1773 printf("%02X | ", l);
1774 for ( pos = 0; pos < 16 && len; pos++, len-- )
1775 {
1776 c = block[l*16+pos];
1777 printf("%02X ", c);
1778 }
1779
1780 if ( pos < 16 )
1781 {
1782 for ( int loop = pos; loop < 16; loop++ )
1783 {
1784 printf(" ");
1785 }
1786 }
1787
1788 // print ASCII char
1789 for ( int loop = 0; loop < pos; loop++ )
1790 {
1791 c = block[l*16+loop];
1792 if ( c >= 0x20 && c <= 0x7F )
1793 {
1794 printf("%c", c);
1795 }
1796 else
1797 {
1798 printf(".");
1799 }
1800 }
1801 printf("\n");
1802 }
1803 printf("=====================================================================\n");
1804 }
1805
1806
1807
1808 int arcmsr_command_handler(int fd, unsigned long arcmsr_cmd, unsigned char *data, int data_len, void *ext_data /* reserved for further use */)
1809 {
1810 ARGUSED(ext_data);
1811
1812 int ioctlreturn = 0;
1813 sSRB_BUFFER sBuf;
1814 struct scsi_cmnd_io io_hdr;
1815 int dir = DXFER_TO_DEVICE;
1816
1817 UINT8 cdb[10];
1818 UINT8 sense[32];
1819
1820 unsigned char *areca_return_packet;
1821 int total = 0;
1822 int expected = -1;
1823 unsigned char return_buff[2048];
1824 unsigned char *ptr = &return_buff[0];
1825 memset(return_buff, 0, sizeof(return_buff));
1826
1827 memset((unsigned char *)&sBuf, 0, sizeof(sBuf));
1828 memset(&io_hdr, 0, sizeof(io_hdr));
1829 memset(cdb, 0, sizeof(cdb));
1830 memset(sense, 0, sizeof(sense));
1831
1832
1833 sBuf.srbioctl.HeaderLength = sizeof(sSRB_IO_CONTROL);
1834 memcpy(sBuf.srbioctl.Signature, ARECA_SIG_STR, strlen(ARECA_SIG_STR));
1835 sBuf.srbioctl.Timeout = 10000;
1836 sBuf.srbioctl.ControlCode = ARCMSR_IOCTL_READ_RQBUFFER;
1837
1838 switch ( arcmsr_cmd )
1839 {
1840 // command for writing data to driver
1841 case ARCMSR_IOCTL_WRITE_WQBUFFER:
1842 if ( data && data_len )
1843 {
1844 sBuf.srbioctl.Length = data_len;
1845 memcpy((unsigned char *)sBuf.ioctldatabuffer, (unsigned char *)data, data_len);
1846 }
1847 // commands for clearing related buffer of driver
1848 case ARCMSR_IOCTL_CLEAR_RQBUFFER:
1849 case ARCMSR_IOCTL_CLEAR_WQBUFFER:
1850 cdb[0] = 0x3B; //SCSI_WRITE_BUF command;
1851 break;
1852 // command for reading data from driver
1853 case ARCMSR_IOCTL_READ_RQBUFFER:
1854 cdb[0] = 0x3C; //SCSI_READ_BUF command;
1855 dir = DXFER_FROM_DEVICE;
1856 break;
1857 default:
1858 // unknown arcmsr commands
1859 return -1;
1860 }
1861
1862 cdb[1] = 0x01;
1863 cdb[2] = 0xf0;
1864 //
1865 // cdb[5][6][7][8] areca defined command code( to/from driver )
1866 //
1867 cdb[5] = (char)( arcmsr_cmd >> 24);
1868 cdb[6] = (char)( arcmsr_cmd >> 16);
1869 cdb[7] = (char)( arcmsr_cmd >> 8);
1870 cdb[8] = (char)( arcmsr_cmd & 0x0F );
1871
1872 io_hdr.dxfer_dir = dir;
1873 io_hdr.dxfer_len = sizeof(sBuf);
1874 io_hdr.dxferp = (unsigned char *)&sBuf;
1875 io_hdr.cmnd = cdb;
1876 io_hdr.cmnd_len = sizeof(cdb);
1877 io_hdr.sensep = sense;
1878 io_hdr.max_sense_len = sizeof(sense);
1879 io_hdr.timeout = SCSI_TIMEOUT_DEFAULT;
1880
1881 while ( 1 )
1882 {
1883 ioctlreturn = do_normal_scsi_cmnd_io(fd, &io_hdr, 0);
1884 if ( ioctlreturn || io_hdr.scsi_status )
1885 {
1886 // errors found
1887 break;
1888 }
1889
1890 if ( arcmsr_cmd != ARCMSR_IOCTL_READ_RQBUFFER )
1891 {
1892 // if succeeded, just returns the length of outgoing data
1893 return data_len;
1894 }
1895
1896 if ( sBuf.srbioctl.Length )
1897 {
1898 //dumpdata(&sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
1899 memcpy(ptr, &sBuf.ioctldatabuffer[0], sBuf.srbioctl.Length);
1900 ptr += sBuf.srbioctl.Length;
1901 total += sBuf.srbioctl.Length;
1902 // the returned bytes enough to compute payload length ?
1903 if ( expected < 0 && total >= 5 )
1904 {
1905 areca_return_packet = (unsigned char *)&return_buff[0];
1906 if ( areca_return_packet[0] == 0x5E &&
1907 areca_return_packet[1] == 0x01 &&
1908 areca_return_packet[2] == 0x61 )
1909 {
1910 // valid header, let's compute the returned payload length,
1911 // we expected the total length is
1912 // payload + 3 bytes header + 2 bytes length + 1 byte checksum
1913 expected = areca_return_packet[4] * 256 + areca_return_packet[3] + 6;
1914 }
1915 }
1916
1917 if ( total >= 7 && total >= expected )
1918 {
1919 //printf("total bytes received = %d, expected length = %d\n", total, expected);
1920
1921 // ------ Okay! we received enough --------
1922 break;
1923 }
1924 }
1925 }
1926
1927 // Deal with the different error cases
1928 if ( ioctlreturn )
1929 {
1930 printf("do_scsi_cmnd_io with write buffer failed code = %x\n", ioctlreturn);
1931 return -2;
1932 }
1933
1934
1935 if ( io_hdr.scsi_status )
1936 {
1937 printf("io_hdr.scsi_status with write buffer failed code = %x\n", io_hdr.scsi_status);
1938 return -3;
1939 }
1940
1941
1942 if ( data )
1943 {
1944 memcpy(data, return_buff, total);
1945 }
1946
1947 return total;
1948 }
1949
1950
1951 linux_areca_device::linux_areca_device(smart_interface * intf, const char * dev_name, int disknum)
1952 : smart_device(intf, dev_name, "areca", "areca"),
1953 linux_smart_device(O_RDWR | O_EXCL | O_NONBLOCK),
1954 m_disknum(disknum)
1955 {
1956 set_info().info_name = strprintf("%s [areca_%02d]", dev_name, disknum);
1957 }
1958
1959 // Areca RAID Controller
1960 int linux_areca_device::ata_command_interface(smart_command_set command, int select, char * data)
1961 {
1962 // ATA input registers
1963 typedef struct _ATA_INPUT_REGISTERS
1964 {
1965 unsigned char features;
1966 unsigned char sector_count;
1967 unsigned char sector_number;
1968 unsigned char cylinder_low;
1969 unsigned char cylinder_high;
1970 unsigned char device_head;
1971 unsigned char command;
1972 unsigned char reserved[8];
1973 unsigned char data[512]; // [in/out] buffer for outgoing/incoming data
1974 } sATA_INPUT_REGISTERS;
1975
1976 // ATA output registers
1977 // Note: The output registers is re-sorted for areca internal use only
1978 typedef struct _ATA_OUTPUT_REGISTERS
1979 {
1980 unsigned char error;
1981 unsigned char status;
1982 unsigned char sector_count;
1983 unsigned char sector_number;
1984 unsigned char cylinder_low;
1985 unsigned char cylinder_high;
1986 }sATA_OUTPUT_REGISTERS;
1987
1988 // Areca packet format for outgoing:
1989 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
1990 // B[3~4] : 2 bytes command length + variant data length, little endian
1991 // B[5] : 1 bytes areca defined command code, ATA passthrough command code is 0x1c
1992 // B[6~last-1] : variant bytes payload data
1993 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
1994 //
1995 //
1996 // header 3 bytes length 2 bytes cmd 1 byte payload data x bytes cs 1 byte
1997 // +--------------------------------------------------------------------------------+
1998 // + 0x5E 0x01 0x61 | 0x00 0x00 | 0x1c | .................... | 0x00 |
1999 // +--------------------------------------------------------------------------------+
2000 //
2001
2002 //Areca packet format for incoming:
2003 // B[0~2] : 3 bytes header, fixed value 0x5E, 0x01, 0x61
2004 // B[3~4] : 2 bytes payload length, little endian
2005 // B[5~last-1] : variant bytes returned payload data
2006 // B[last] : 1 byte checksum, simply sum(B[3] ~ B[last -1])
2007 //
2008 //
2009 // header 3 bytes length 2 bytes payload data x bytes cs 1 byte
2010 // +-------------------------------------------------------------------+
2011 // + 0x5E 0x01 0x61 | 0x00 0x00 | .................... | 0x00 |
2012 // +-------------------------------------------------------------------+
2013 unsigned char areca_packet[640];
2014 int areca_packet_len = sizeof(areca_packet);
2015 unsigned char cs = 0;
2016
2017 sATA_INPUT_REGISTERS *ata_cmd;
2018
2019 // For debugging
2020 #if 0
2021 memset(sInq, 0, sizeof(sInq));
2022 scsiStdInquiry(fd, (unsigned char *)sInq, (int)sizeof(sInq));
2023 dumpdata((unsigned char *)sInq, sizeof(sInq));
2024 #endif
2025 memset(areca_packet, 0, areca_packet_len);
2026
2027 // ----- BEGIN TO SETUP HEADERS -------
2028 areca_packet[0] = 0x5E;
2029 areca_packet[1] = 0x01;
2030 areca_packet[2] = 0x61;
2031 areca_packet[3] = (unsigned char)((areca_packet_len - 6) & 0xff);
2032 areca_packet[4] = (unsigned char)(((areca_packet_len - 6) >> 8) & 0xff);
2033 areca_packet[5] = 0x1c; // areca defined code for ATA passthrough command
2034
2035
2036 // ----- BEGIN TO SETUP PAYLOAD DATA -----
2037
2038 memcpy(&areca_packet[7], "SmrT", 4); // areca defined password
2039
2040 ata_cmd = (sATA_INPUT_REGISTERS *)&areca_packet[12];
2041 ata_cmd->cylinder_low = 0x4F;
2042 ata_cmd->cylinder_high = 0xC2;
2043
2044
2045 if ( command == READ_VALUES ||
2046 command == READ_THRESHOLDS ||
2047 command == READ_LOG ||
2048 command == IDENTIFY ||
2049 command == PIDENTIFY )
2050 {
2051 // the commands will return data
2052 areca_packet[6] = 0x13;
2053 ata_cmd->sector_count = 0x1;
2054 }
2055 else if ( command == WRITE_LOG )
2056 {
2057 // the commands will write data
2058 areca_packet[6] = 0x14;
2059 }
2060 else
2061 {
2062 // the commands will return no data
2063 areca_packet[6] = 0x15;
2064 }
2065
2066
2067 ata_cmd->command = ATA_SMART_CMD;
2068 // Now set ATA registers depending upon command
2069 switch ( command )
2070 {
2071 case CHECK_POWER_MODE:
2072 //printf("command = CHECK_POWER_MODE\n");
2073 ata_cmd->command = ATA_CHECK_POWER_MODE;
2074 break;
2075 case READ_VALUES:
2076 //printf("command = READ_VALUES\n");
2077 ata_cmd->features = ATA_SMART_READ_VALUES;
2078 break;
2079 case READ_THRESHOLDS:
2080 //printf("command = READ_THRESHOLDS\n");
2081 ata_cmd->features = ATA_SMART_READ_THRESHOLDS;
2082 break;
2083 case READ_LOG:
2084 //printf("command = READ_LOG\n");
2085 ata_cmd->features = ATA_SMART_READ_LOG_SECTOR;
2086 ata_cmd->sector_number = select;
2087 break;
2088 case WRITE_LOG:
2089 //printf("command = WRITE_LOG\n");
2090 ata_cmd->features = ATA_SMART_WRITE_LOG_SECTOR;
2091 memcpy(ata_cmd->data, data, 512);
2092 ata_cmd->sector_count = 1;
2093 ata_cmd->sector_number = select;
2094 break;
2095 case IDENTIFY:
2096 //printf("command = IDENTIFY\n");
2097 ata_cmd->command = ATA_IDENTIFY_DEVICE;
2098 break;
2099 case PIDENTIFY:
2100 //printf("command = PIDENTIFY\n");
2101 errno=ENODEV;
2102 return -1;
2103 case ENABLE:
2104 //printf("command = ENABLE\n");
2105 ata_cmd->features = ATA_SMART_ENABLE;
2106 break;
2107 case DISABLE:
2108 //printf("command = DISABLE\n");
2109 ata_cmd->features = ATA_SMART_DISABLE;
2110 break;
2111 case AUTO_OFFLINE:
2112 //printf("command = AUTO_OFFLINE\n");
2113 ata_cmd->features = ATA_SMART_AUTO_OFFLINE;
2114 // Enable or disable?
2115 ata_cmd->sector_count = select;
2116 break;
2117 case AUTOSAVE:
2118 //printf("command = AUTOSAVE\n");
2119 ata_cmd->features = ATA_SMART_AUTOSAVE;
2120 // Enable or disable?
2121 ata_cmd->sector_count = select;
2122 break;
2123 case IMMEDIATE_OFFLINE:
2124 //printf("command = IMMEDIATE_OFFLINE\n");
2125 ata_cmd->features = ATA_SMART_IMMEDIATE_OFFLINE;
2126 // What test type to run?
2127 ata_cmd->sector_number = select;
2128 break;
2129 case STATUS_CHECK:
2130 //printf("command = STATUS_CHECK\n");
2131 ata_cmd->features = ATA_SMART_STATUS;
2132 break;
2133 case STATUS:
2134 //printf("command = STATUS\n");
2135 ata_cmd->features = ATA_SMART_STATUS;
2136 break;
2137 default:
2138 //printf("command = UNKNOWN\n");
2139 errno=ENOSYS;
2140 return -1;
2141 };
2142
2143 areca_packet[11] = m_disknum - 1; // drive number
2144
2145 // ----- BEGIN TO SETUP CHECKSUM -----
2146 for ( int loop = 3; loop < areca_packet_len - 1; loop++ )
2147 {
2148 cs += areca_packet[loop];
2149 }
2150 areca_packet[areca_packet_len-1] = cs;
2151
2152 // ----- BEGIN TO SEND TO ARECA DRIVER ------
2153 int expected = 0;
2154 unsigned char return_buff[2048];
2155 memset(return_buff, 0, sizeof(return_buff));
2156
2157 expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_RQBUFFER, NULL, 0, NULL);
2158 if (expected==-3) {
2159 find_areca_in_proc(NULL);
2160 return -1;
2161 }
2162
2163 expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_CLEAR_WQBUFFER, NULL, 0, NULL);
2164 expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_WRITE_WQBUFFER, areca_packet, areca_packet_len, NULL);
2165 if ( expected > 0 )
2166 {
2167 expected = arcmsr_command_handler(get_fd(), ARCMSR_IOCTL_READ_RQBUFFER, return_buff, sizeof(return_buff), NULL);
2168 }
2169 if ( expected < 0 )
2170 {
2171 return -1;
2172 }
2173
2174 // ----- VERIFY THE CHECKSUM -----
2175 cs = 0;
2176 for ( int loop = 3; loop < expected - 1; loop++ )
2177 {
2178 cs += return_buff[loop];
2179 }
2180
2181 if ( return_buff[expected - 1] != cs )
2182 {
2183 errno = EIO;
2184 return -1;
2185 }
2186
2187 sATA_OUTPUT_REGISTERS *ata_out = (sATA_OUTPUT_REGISTERS *)&return_buff[5] ;
2188 if ( ata_out->status )
2189 {
2190 if ( command == IDENTIFY )
2191 {
2192 pout("The firmware of your Areca RAID controller appears to be outdated!\n" \
2193 "Please update your controller to firmware version 1.46 or later.\n" \
2194 "You may download it here: ftp://ftp.areca.com.tw/RaidCards/BIOS_Firmware\n\n");
2195 }
2196 errno = EIO;
2197 return -1;
2198 }
2199
2200 // returns with data
2201 if ( command == READ_VALUES ||
2202 command == READ_THRESHOLDS ||
2203 command == READ_LOG ||
2204 command == IDENTIFY ||
2205 command == PIDENTIFY )
2206 {
2207 memcpy(data, &return_buff[7], 512);
2208 }
2209
2210 if ( command == CHECK_POWER_MODE )
2211 {
2212 data[0] = ata_out->sector_count;
2213 }
2214
2215 if ( command == STATUS_CHECK &&
2216 ( ata_out->cylinder_low == 0xF4 && ata_out->cylinder_high == 0x2C ) )
2217 {
2218 return 1;
2219 }
2220
2221 return 0;
2222 }
2223
2224
2225 /////////////////////////////////////////////////////////////////////////////
2226 /// Marvell support
2227
2228 class linux_marvell_device
2229 : public /*implements*/ ata_device_with_command_set,
2230 public /*extends*/ linux_smart_device
2231 {
2232 public:
2233 linux_marvell_device(smart_interface * intf, const char * dev_name, const char * req_type);
2234
2235 protected:
2236 virtual int ata_command_interface(smart_command_set command, int select, char * data);
2237 };
2238
2239 linux_marvell_device::linux_marvell_device(smart_interface * intf,
2240 const char * dev_name, const char * req_type)
2241 : smart_device(intf, dev_name, "marvell", req_type),
2242 linux_smart_device(O_RDONLY | O_NONBLOCK)
2243 {
2244 }
2245
2246 int linux_marvell_device::ata_command_interface(smart_command_set command, int select, char * data)
2247 {
2248 typedef struct {
2249 int inlen;
2250 int outlen;
2251 char cmd[540];
2252 } mvsata_scsi_cmd;
2253
2254 int copydata = 0;
2255 mvsata_scsi_cmd smart_command;
2256 unsigned char *buff = (unsigned char *)&smart_command.cmd[6];
2257 // See struct hd_drive_cmd_hdr in hdreg.h
2258 // buff[0]: ATA COMMAND CODE REGISTER
2259 // buff[1]: ATA SECTOR NUMBER REGISTER
2260 // buff[2]: ATA FEATURES REGISTER
2261 // buff[3]: ATA SECTOR COUNT REGISTER
2262
2263 // clear out buff. Large enough for HDIO_DRIVE_CMD (4+512 bytes)
2264 memset(&smart_command, 0, sizeof(smart_command));
2265 smart_command.inlen = 540;
2266 smart_command.outlen = 540;
2267 smart_command.cmd[0] = 0xC; //Vendor-specific code
2268 smart_command.cmd[4] = 6; //command length
2269
2270 buff[0] = ATA_SMART_CMD;
2271 switch (command){
2272 case CHECK_POWER_MODE:
2273 buff[0]=ATA_CHECK_POWER_MODE;
2274 break;
2275 case READ_VALUES:
2276 buff[2]=ATA_SMART_READ_VALUES;
2277 copydata=buff[3]=1;
2278 break;
2279 case READ_THRESHOLDS:
2280 buff[2]=ATA_SMART_READ_THRESHOLDS;
2281 copydata=buff[1]=buff[3]=1;
2282 break;
2283 case READ_LOG:
2284 buff[2]=ATA_SMART_READ_LOG_SECTOR;
2285 buff[1]=select;
2286 copydata=buff[3]=1;
2287 break;
2288 case IDENTIFY:
2289 buff[0]=ATA_IDENTIFY_DEVICE;
2290 copydata=buff[3]=1;
2291 break;
2292 case PIDENTIFY:
2293 buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
2294 copydata=buff[3]=1;
2295 break;
2296 case ENABLE:
2297 buff[2]=ATA_SMART_ENABLE;
2298 buff[1]=1;
2299 break;
2300 case DISABLE:
2301 buff[2]=ATA_SMART_DISABLE;
2302 buff[1]=1;
2303 break;
2304 case STATUS:
2305 case STATUS_CHECK:
2306 // this command only says if SMART is working. It could be
2307 // replaced with STATUS_CHECK below.
2308 buff[2] = ATA_SMART_STATUS;
2309 break;
2310 case AUTO_OFFLINE:
2311 buff[2]=ATA_SMART_AUTO_OFFLINE;
2312 buff[3]=select; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2313 break;
2314 case AUTOSAVE:
2315 buff[2]=ATA_SMART_AUTOSAVE;
2316 buff[3]=select; // YET NOTE - THIS IS A NON-DATA COMMAND!!
2317 break;
2318 case IMMEDIATE_OFFLINE:
2319 buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
2320 buff[1]=select;
2321 break;
2322 default:
2323 pout("Unrecognized command %d in mvsata_os_specific_handler()\n", command);
2324 EXIT(1);
2325 break;
2326 }
2327 // There are two different types of ioctls(). The HDIO_DRIVE_TASK
2328 // one is this:
2329 // We are now doing the HDIO_DRIVE_CMD type ioctl.
2330 if (ioctl(get_fd(), SCSI_IOCTL_SEND_COMMAND, (void *)&smart_command))
2331 return -1;
2332
2333 if (command==CHECK_POWER_MODE) {
2334 // LEON -- CHECK THIS PLEASE. THIS SHOULD BE THE SECTOR COUNT
2335 // REGISTER, AND IT MIGHT BE buff[2] NOT buff[3]. Bruce
2336 data[0]=buff[3];
2337 return 0;
2338 }
2339
2340 // Always succeed on a SMART status, as a disk that failed returned
2341 // buff[4]=0xF4, buff[5]=0x2C, i.e. "Bad SMART status" (see below).
2342 if (command == STATUS)
2343 return 0;
2344 //Data returned is starting from 0 offset
2345 if (command == STATUS_CHECK)
2346 {
2347 // Cyl low and Cyl high unchanged means "Good SMART status"
2348 if (buff[4] == 0x4F && buff[5] == 0xC2)
2349 return 0;
2350 // These values mean "Bad SMART status"
2351 if (buff[4] == 0xF4 && buff[5] == 0x2C)
2352 return 1;
2353 // We haven't gotten output that makes sense; print out some debugging info
2354 syserror("Error SMART Status command failed");
2355 pout("Please get assistance from %s\n",PACKAGE_BUGREPORT);
2356 pout("Register values returned from SMART Status command are:\n");
2357 pout("CMD =0x%02x\n",(int)buff[0]);
2358 pout("FR =0x%02x\n",(int)buff[1]);
2359 pout("NS =0x%02x\n",(int)buff[2]);
2360 pout("SC =0x%02x\n",(int)buff[3]);
2361 pout("CL =0x%02x\n",(int)buff[4]);
2362 pout("CH =0x%02x\n",(int)buff[5]);
2363 pout("SEL=0x%02x\n",(int)buff[6]);
2364 return -1;
2365 }
2366
2367 if (copydata)
2368 memcpy(data, buff, 512);
2369 return 0;
2370 }
2371
2372
2373 /////////////////////////////////////////////////////////////////////////////
2374 /// Highpoint RAID support
2375
2376 class linux_highpoint_device
2377 : public /*implements*/ ata_device_with_command_set,
2378 public /*extends*/ linux_smart_device
2379 {
2380 public:
2381 linux_highpoint_device(smart_interface * intf, const char * dev_name,
2382 unsigned char controller, unsigned char channel, unsigned char port);
2383
2384 protected:
2385 virtual int ata_command_interface(smart_command_set command, int select, char * data);
2386
2387 private:
2388 unsigned char m_hpt_data[3]; ///< controller/channel/port
2389 };
2390
2391 linux_highpoint_device::linux_highpoint_device(smart_interface * intf, const char * dev_name,
2392 unsigned char controller, unsigned char channel, unsigned char port)
2393 : smart_device(intf, dev_name, "hpt", "hpt"),
2394 linux_smart_device(O_RDONLY | O_NONBLOCK)
2395 {
2396 m_hpt_data[0] = controller; m_hpt_data[1] = channel; m_hpt_data[2] = port;
2397 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]);
2398 }
2399
2400 // this implementation is derived from ata_command_interface with a header
2401 // packing for highpoint linux driver ioctl interface
2402 //
2403 // ioctl(fd,HPTIO_CTL,buff)
2404 // ^^^^^^^^^
2405 //
2406 // structure of hpt_buff
2407 // +----+----+----+----+--------------------.....---------------------+
2408 // | 1 | 2 | 3 | 4 | 5 |
2409 // +----+----+----+----+--------------------.....---------------------+
2410 //
2411 // 1: The target controller [ int ( 4 Bytes ) ]
2412 // 2: The channel of the target controllee [ int ( 4 Bytes ) ]
2413 // 3: HDIO_ ioctl call [ int ( 4 Bytes ) ]
2414 // available from ${LINUX_KERNEL_SOURCE}/Documentation/ioctl/hdio
2415 // 4: the pmport that disk attached, [ int ( 4 Bytes ) ]
2416 // if no pmport device, set to 1 or leave blank
2417 // 5: data [ void * ( var leangth ) ]
2418 //
2419 #define STRANGE_BUFFER_LENGTH (4+512*0xf8)
2420
2421 int linux_highpoint_device::ata_command_interface(smart_command_set command, int select, char * data)
2422 {
2423 unsigned char hpt_buff[4*sizeof(int) + STRANGE_BUFFER_LENGTH];
2424 unsigned int *hpt = (unsigned int *)hpt_buff;
2425 unsigned char *buff = &hpt_buff[4*sizeof(int)];
2426 int copydata = 0;
2427 const int HDIO_DRIVE_CMD_OFFSET = 4;
2428
2429 memset(hpt_buff, 0, 4*sizeof(int) + STRANGE_BUFFER_LENGTH);
2430 hpt[0] = m_hpt_data[0]; // controller id
2431 hpt[1] = m_hpt_data[1]; // channel number
2432 hpt[3] = m_hpt_data[2]; // pmport number
2433
2434 buff[0]=ATA_SMART_CMD;
2435 switch (command){
2436 case CHECK_POWER_MODE:
2437 buff[0]=ATA_CHECK_POWER_MODE;
2438 copydata=1;
2439 break;
2440 case READ_VALUES:
2441 buff[2]=ATA_SMART_READ_VALUES;
2442 buff[3]=1;
2443 copydata=512;
2444 break;
2445 case READ_THRESHOLDS:
2446 buff[2]=ATA_SMART_READ_THRESHOLDS;
2447 buff[1]=buff[3]=1;
2448 copydata=512;
2449 break;
2450 case READ_LOG:
2451 buff[2]=ATA_SMART_READ_LOG_SECTOR;
2452 buff[1]=select;
2453 buff[3]=1;
2454 copydata=512;
2455 break;
2456 case WRITE_LOG:
2457 break;
2458 case IDENTIFY:
2459 buff[0]=ATA_IDENTIFY_DEVICE;
2460 buff[3]=1;
2461 copydata=512;
2462 break;
2463 case PIDENTIFY:
2464 buff[0]=ATA_IDENTIFY_PACKET_DEVICE;
2465 buff[3]=1;
2466 copydata=512;
2467 break;
2468 case ENABLE:
2469 buff[2]=ATA_SMART_ENABLE;
2470 buff[1]=1;
2471 break;
2472 case DISABLE:
2473 buff[2]=ATA_SMART_DISABLE;
2474 buff[1]=1;
2475 break;
2476 case STATUS:
2477 buff[2]=ATA_SMART_STATUS;
2478 break;
2479 case AUTO_OFFLINE:
2480 buff[2]=ATA_SMART_AUTO_OFFLINE;
2481 buff[3]=select;
2482 break;
2483 case AUTOSAVE:
2484 buff[2]=ATA_SMART_AUTOSAVE;
2485 buff[3]=select;
2486 break;
2487 case IMMEDIATE_OFFLINE:
2488 buff[2]=ATA_SMART_IMMEDIATE_OFFLINE;
2489 buff[1]=select;
2490 break;
2491 case STATUS_CHECK:
2492 buff[1]=ATA_SMART_STATUS;
2493 break;
2494 default:
2495 pout("Unrecognized command %d in linux_highpoint_command_interface()\n"
2496 "Please contact " PACKAGE_BUGREPORT "\n", command);
2497 errno=ENOSYS;
2498 return -1;
2499 }
2500
2501 if (command==WRITE_LOG) {
2502 unsigned char task[4*sizeof(int)+sizeof(ide_task_request_t)+512];
2503 unsigned int *hpt = (unsigned int *)task;
2504 ide_task_request_t *reqtask = (ide_task_request_t *)(&task[4*sizeof(int)]);
2505 task_struct_t *taskfile = (task_struct_t *)reqtask->io_ports;
2506 int retval;
2507
2508 memset(task, 0, sizeof(task));
2509
2510 hpt[0] = m_hpt_data[0]; // controller id
2511 hpt[1] = m_hpt_data[1]; // channel number
2512 hpt[3] = m_hpt_data[2]; // pmport number
2513 hpt[2] = HDIO_DRIVE_TASKFILE; // real hd ioctl
2514
2515 taskfile->data = 0;
2516 taskfile->feature = ATA_SMART_WRITE_LOG_SECTOR;
2517 taskfile->sector_count = 1;
2518 taskfile->sector_number = select;
2519 taskfile->low_cylinder = 0x4f;
2520 taskfile->high_cylinder = 0xc2;
2521 taskfile->device_head = 0;
2522 taskfile->command = ATA_SMART_CMD;
2523
2524 reqtask->data_phase = TASKFILE_OUT;
2525 reqtask->req_cmd = IDE_DRIVE_TASK_OUT;
2526 reqtask->out_size = 512;
2527 reqtask->in_size = 0;
2528
2529 memcpy(task+sizeof(ide_task_request_t)+4*sizeof(int), data, 512);
2530
2531 if ((retval=ioctl(get_fd(), HPTIO_CTL, task))) {
2532 if (retval==-EINVAL)
2533 pout("Kernel lacks HDIO_DRIVE_TASKFILE support; compile kernel with CONFIG_IDE_TASKFILE_IO set\n");
2534 return -1;
2535 }
2536 return 0;
2537 }
2538
2539 if (command==STATUS_CHECK){
2540 int retval;
2541 unsigned const char normal_lo=0x4f, normal_hi=0xc2;
2542 unsigned const char failed_lo=0xf4, failed_hi=0x2c;
2543 buff[4]=normal_lo;
2544 buff[5]=normal_hi;
2545
2546 hpt[2] = HDIO_DRIVE_TASK;
2547
2548 if ((retval=ioctl(get_fd(), HPTIO_CTL, hpt_buff))) {
2549 if (retval==-EINVAL) {
2550 pout("Error SMART Status command via HDIO_DRIVE_TASK failed");
2551 pout("Rebuild older linux 2.2 kernels with HDIO_DRIVE_TASK support added\n");
2552 }
2553 else
2554 syserror("Error SMART Status command failed");
2555 return -1;
2556 }
2557
2558 if (buff[4]==normal_lo && buff[5]==normal_hi)
2559 return 0;
2560
2561 if (buff[4]==failed_lo && buff[5]==failed_hi)
2562 return 1;
2563
2564 syserror("Error SMART Status command failed");
2565 pout("Please get assistance from " PACKAGE_HOMEPAGE "\n");
2566 pout("Register values returned from SMART Status command are:\n");
2567 pout("CMD=0x%02x\n",(int)buff[0]);
2568 pout("FR =0x%02x\n",(int)buff[1]);
2569 pout("NS =0x%02x\n",(int)buff[2]);
2570 pout("SC =0x%02x\n",(int)buff[3]);
2571 pout("CL =0x%02x\n",(int)buff[4]);
2572 pout("CH =0x%02x\n",(int)buff[5]);
2573 pout("SEL=0x%02x\n",(int)buff[6]);
2574 return -1;
2575 }
2576
2577 #if 1
2578 if (command==IDENTIFY || command==PIDENTIFY) {
2579 unsigned char deviceid[4*sizeof(int)+512*sizeof(char)];
2580 unsigned int *hpt = (unsigned int *)deviceid;
2581
2582 hpt[0] = m_hpt_data[0]; // controller id
2583 hpt[1] = m_hpt_data[1]; // channel number
2584 hpt[3] = m_hpt_data[2]; // pmport number
2585
2586 hpt[2] = HDIO_GET_IDENTITY;
2587 if (!ioctl(get_fd(), HPTIO_CTL, deviceid) && (deviceid[4*sizeof(int)] & 0x8000))
2588 buff[0]=(command==IDENTIFY)?ATA_IDENTIFY_PACKET_DEVICE:ATA_IDENTIFY_DEVICE;
2589 }
2590 #endif
2591
2592 hpt[2] = HDIO_DRIVE_CMD;
2593 if ((ioctl(get_fd(), HPTIO_CTL, hpt_buff)))
2594 return -1;
2595
2596 if (command==CHECK_POWER_MODE)
2597 buff[HDIO_DRIVE_CMD_OFFSET]=buff[2];
2598
2599 if (copydata)
2600 memcpy(data, buff+HDIO_DRIVE_CMD_OFFSET, copydata);
2601
2602 return 0;
2603 }
2604
2605
2606 #if 0 // TODO: Migrate from 'smart_command_set' to 'ata_in_regs' OR remove the function
2607 // Utility function for printing warnings
2608 void printwarning(smart_command_set command){
2609 static int printed[4]={0,0,0,0};
2610 const char* message=
2611 "can not be passed through the 3ware 3w-xxxx driver. This can be fixed by\n"
2612 "applying a simple 3w-xxxx driver patch that can be found here:\n"
2613 PACKAGE_HOMEPAGE "\n"
2614 "Alternatively, upgrade your 3w-xxxx driver to version 1.02.00.037 or greater.\n\n";
2615
2616 if (command==AUTO_OFFLINE && !printed[0]) {
2617 printed[0]=1;
2618 pout("The SMART AUTO-OFFLINE ENABLE command (smartmontools -o on option/Directive)\n%s", message);
2619 }
2620 else if (command==AUTOSAVE && !printed[1]) {
2621 printed[1]=1;
2622 pout("The SMART AUTOSAVE ENABLE command (smartmontools -S on option/Directive)\n%s", message);
2623 }
2624 else if (command==STATUS_CHECK && !printed[2]) {
2625 printed[2]=1;
2626 pout("The SMART RETURN STATUS return value (smartmontools -H option/Directive)\n%s", message);
2627 }
2628 else if (command==WRITE_LOG && !printed[3]) {
2629 printed[3]=1;
2630 pout("The SMART WRITE LOG command (smartmontools -t selective) only supported via char /dev/tw[ae] interface\n");
2631 }
2632
2633 return;
2634 }
2635 #endif
2636
2637
2638 /////////////////////////////////////////////////////////////////////////////
2639 /// SCSI open with autodetection support
2640
2641 smart_device * linux_scsi_device::autodetect_open()
2642 {
2643 // Open device
2644 if (!open())
2645 return this;
2646
2647 // No Autodetection if device type was specified by user
2648 if (*get_req_type())
2649 return this;
2650
2651 // The code below is based on smartd.cpp:SCSIFilterKnown()
2652
2653 // Get INQUIRY
2654 unsigned char req_buff[64] = {0, };
2655 int req_len = 36;
2656 if (scsiStdInquiry(this, req_buff, req_len)) {
2657 // Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices
2658 // watch this spot ... other devices could lock up here
2659 req_len = 64;
2660 if (scsiStdInquiry(this, req_buff, req_len)) {
2661 // device doesn't like INQUIRY commands
2662 close();
2663 set_err(EIO, "INQUIRY failed");
2664 return this;
2665 }
2666 }
2667
2668 int avail_len = req_buff[4] + 5;
2669 int len = (avail_len < req_len ? avail_len : req_len);
2670 if (len < 36)
2671 return this;
2672
2673 // Use INQUIRY to detect type
2674 smart_device * newdev = 0;
2675 try {
2676 // 3ware ?
2677 if (!memcmp(req_buff + 8, "3ware", 5) || !memcmp(req_buff + 8, "AMCC", 4)) {
2678 close();
2679 set_err(EINVAL, "AMCC/3ware controller, please try adding '-d 3ware,N',\n"
2680 "you may need to replace %s with /dev/twaN or /dev/tweN", get_dev_name());
2681 return this;
2682 }
2683 // DELL?
2684 if (!memcmp(req_buff + 8, "DELL PERC", 12) || !memcmp(req_buff + 8, "MegaRAID", 8)) {
2685 close();
2686 set_err(EINVAL, "DELL or MegaRaid controller, please try adding '-d megaraid,N'");
2687 return this;
2688 }
2689
2690 // Marvell ?
2691 if (len >= 42 && !memcmp(req_buff + 36, "MVSATA", 6)) {
2692 //pout("Device %s: using '-d marvell' for ATA disk with Marvell driver\n", get_dev_name());
2693 close();
2694 newdev = new linux_marvell_device(smi(), get_dev_name(), get_req_type());
2695 newdev->open(); // TODO: Can possibly pass open fd
2696 delete this;
2697 return newdev;
2698 }
2699
2700 // SAT or USB ?
2701 newdev = smi()->autodetect_sat_device(this, req_buff, len);
2702 if (newdev)
2703 // NOTE: 'this' is now owned by '*newdev'
2704 return newdev;
2705 }
2706 catch (...) {
2707 // Cleanup if exception occurs after newdev was allocated
2708 delete newdev;
2709 throw;
2710 }
2711
2712 // Nothing special found
2713 return this;
2714 }
2715
2716
2717 //////////////////////////////////////////////////////////////////////
2718 // USB bridge ID detection
2719
2720 // Read USB ID from /sys file
2721 static bool read_id(const std::string & path, unsigned short & id)
2722 {
2723 FILE * f = fopen(path.c_str(), "r");
2724 if (!f)
2725 return false;
2726 int n = -1;
2727 bool ok = (fscanf(f, "%hx%n", &id, &n) == 1 && n == 4);
2728 fclose(f);
2729 return ok;
2730 }
2731
2732 // Get USB bridge ID for "sdX"
2733 static bool get_usb_id(const char * name, unsigned short & vendor_id,
2734 unsigned short & product_id, unsigned short & version)
2735 {
2736 // Only "sdX" supported
2737 if (!(!strncmp(name, "sd", 2) && !strchr(name, '/')))
2738 return false;
2739
2740 // Start search at dir referenced by symlink "/sys/block/sdX/device"
2741 // -> "/sys/devices/.../usb*/.../host*/target*/..."
2742 std::string dir = strprintf("/sys/block/%s/device", name);
2743
2744 // Stop search at "/sys/devices"
2745 struct stat st;
2746 if (stat("/sys/devices", &st))
2747 return false;
2748 ino_t stop_ino = st.st_ino;
2749
2750 // Search in parent directories until "idVendor" is found,
2751 // fail if "/sys/devices" reached or too many iterations
2752 int cnt = 0;
2753 do {
2754 dir += "/..";
2755 if (!(++cnt < 10 && !stat(dir.c_str(), &st) && st.st_ino != stop_ino))
2756 return false;
2757 } while (access((dir + "/idVendor").c_str(), 0));
2758
2759 // Read IDs
2760 if (!( read_id(dir + "/idVendor", vendor_id)
2761 && read_id(dir + "/idProduct", product_id)
2762 && read_id(dir + "/bcdDevice", version) ))
2763 return false;
2764
2765 if (con->reportscsiioctl > 1)
2766 pout("USB ID = 0x%04x:0x%04x (0x%03x)\n", vendor_id, product_id, version);
2767 return true;
2768 }
2769
2770
2771 //////////////////////////////////////////////////////////////////////
2772 /// Linux interface
2773
2774 class linux_smart_interface
2775 : public /*implements*/ smart_interface
2776 {
2777 public:
2778 virtual std::string get_app_examples(const char * appname);
2779
2780 virtual bool scan_smart_devices(smart_device_list & devlist, const char * type,
2781 const char * pattern = 0);
2782
2783 protected:
2784 virtual ata_device * get_ata_device(const char * name, const char * type);
2785
2786 virtual scsi_device * get_scsi_device(const char * name, const char * type);
2787
2788 virtual smart_device * autodetect_smart_device(const char * name);
2789
2790 virtual smart_device * get_custom_smart_device(const char * name, const char * type);
2791
2792 virtual std::string get_valid_custom_dev_types_str();
2793
2794 private:
2795 bool get_dev_list(smart_device_list & devlist, const char * pattern,
2796 bool scan_ata, bool scan_scsi, const char * req_type, bool autodetect);
2797
2798 smart_device * missing_option(const char * opt);
2799 };
2800
2801 std::string linux_smart_interface::get_app_examples(const char * appname)
2802 {
2803 if (!strcmp(appname, "smartctl"))
2804 return smartctl_examples;
2805 return "";
2806 }
2807
2808
2809 // we are going to take advantage of the fact that Linux's devfs will only
2810 // have device entries for devices that exist. So if we get the equivalent of
2811 // ls /dev/hd[a-t], we have all the ATA devices on the system
2812 bool linux_smart_interface::get_dev_list(smart_device_list & devlist,
2813 const char * pattern, bool scan_ata, bool scan_scsi,
2814 const char * req_type, bool autodetect)
2815 {
2816 // Use glob to look for any directory entries matching the pattern
2817 glob_t globbuf;
2818 memset(&globbuf, 0, sizeof(globbuf));
2819 int retglob = glob(pattern, GLOB_ERR, NULL, &globbuf);
2820 if (retglob) {
2821 // glob failed: free memory and return
2822 globfree(&globbuf);
2823
2824 if (retglob==GLOB_NOMATCH){
2825 pout("glob(3) found no matches for pattern %s\n", pattern);
2826 return true;
2827 }
2828
2829 if (retglob==GLOB_NOSPACE)
2830 set_err(ENOMEM, "glob(3) ran out of memory matching pattern %s", pattern);
2831 #ifdef GLOB_ABORTED // missing in old versions of glob.h
2832 else if (retglob==GLOB_ABORTED)
2833 set_err(EINVAL, "glob(3) aborted matching pattern %s", pattern);
2834 #endif
2835 else
2836 set_err(EINVAL, "Unexplained error in glob(3) of pattern %s", pattern);
2837
2838 return false;
2839 }
2840
2841 // did we find too many paths?
2842 const int max_pathc = 32;
2843 int n = (int)globbuf.gl_pathc;
2844 if (n > max_pathc) {
2845 pout("glob(3) found %d > MAX=%d devices matching pattern %s: ignoring %d paths\n",
2846 n, max_pathc, pattern, n - max_pathc);
2847 n = max_pathc;
2848 }
2849
2850 // now step through the list returned by glob. If not a link, copy
2851 // to list. If it is a link, evaluate it and see if the path ends
2852 // in "disc".
2853 for (int i = 0; i < n; i++){
2854 // see if path is a link
2855 char linkbuf[1024];
2856 int retlink = readlink(globbuf.gl_pathv[i], linkbuf, sizeof(linkbuf)-1);
2857
2858 char tmpname[1024]={0};
2859 const char * name = 0;
2860 bool is_scsi = scan_scsi;
2861 // if not a link (or a strange link), keep it
2862 if (retlink<=0 || retlink>1023)
2863 name = globbuf.gl_pathv[i];
2864 else {
2865 // or if it's a link that points to a disc, follow it
2866 linkbuf[retlink] = 0;
2867 const char *p;
2868 if ((p=strrchr(linkbuf, '/')) && !strcmp(p+1, "disc"))
2869 // This is the branch of the code that gets followed if we are
2870 // using devfs WITH traditional compatibility links. In this
2871 // case, we add the traditional device name to the list that
2872 // is returned.
2873 name = globbuf.gl_pathv[i];
2874 else {
2875 // This is the branch of the code that gets followed if we are
2876 // using devfs WITHOUT traditional compatibility links. In
2877 // this case, we check that the link to the directory is of
2878 // the correct type, and then append "disc" to it.
2879 bool match_ata = strstr(linkbuf, "ide");
2880 bool match_scsi = strstr(linkbuf, "scsi");
2881 if (((match_ata && scan_ata) || (match_scsi && scan_scsi)) && !(match_ata && match_scsi)) {
2882 is_scsi = match_scsi;
2883 snprintf(tmpname, sizeof(tmpname), "%s/disc", globbuf.gl_pathv[i]);
2884 name = tmpname;
2885 }
2886 }
2887 }
2888
2889 if (name) {
2890 // Found a name, add device to list.
2891 smart_device * dev;
2892 if (autodetect)
2893 dev = autodetect_smart_device(name);
2894 else if (is_scsi)
2895 dev = new linux_scsi_device(this, name, req_type);
2896 else
2897 dev = new linux_ata_device(this, name, req_type);
2898 if (dev) // autodetect_smart_device() may return nullptr.
2899 devlist.add(dev);
2900 }
2901 }
2902
2903 // free memory
2904 globfree(&globbuf);
2905
2906 return true;
2907 }
2908
2909 bool linux_smart_interface::scan_smart_devices(smart_device_list & devlist,
2910 const char * type, const char * pattern /*= 0*/)
2911 {
2912 if (pattern) {
2913 set_err(EINVAL, "DEVICESCAN with pattern not implemented yet");
2914 return false;
2915 }
2916
2917 if (!type)
2918 type = "";
2919
2920 bool scan_ata = (!*type || !strcmp(type, "ata" ));
2921 bool scan_scsi = (!*type || !strcmp(type, "scsi"));
2922 if (!(scan_ata || scan_scsi))
2923 return true;
2924
2925 if (scan_ata)
2926 get_dev_list(devlist, "/dev/hd[a-t]", true, false, type, false);
2927 if (scan_scsi) // Try USB autodetection if no type specifed
2928 get_dev_list(devlist, "/dev/sd[a-z]", false, true, type, !*type);
2929
2930 // if we found traditional links, we are done
2931 if (devlist.size() > 0)
2932 return true;
2933
2934 // else look for devfs entries without traditional links
2935 // TODO: Add udev support
2936 return get_dev_list(devlist, "/dev/discs/disc*", scan_ata, scan_scsi, type, false);
2937 }
2938
2939 ata_device * linux_smart_interface::get_ata_device(const char * name, const char * type)
2940 {
2941 return new linux_ata_device(this, name, type);
2942 }
2943
2944 scsi_device * linux_smart_interface::get_scsi_device(const char * name, const char * type)
2945 {
2946 return new linux_scsi_device(this, name, type);
2947 }
2948
2949 smart_device * linux_smart_interface::missing_option(const char * opt)
2950 {
2951 set_err(EINVAL, "requires option '%s'", opt);
2952 return 0;
2953 }
2954
2955 // Return true if STR starts with PREFIX.
2956 static bool str_starts_with(const char * str, const char * prefix)
2957 {
2958 return !strncmp(str, prefix, strlen(prefix));
2959 }
2960
2961 // Guess device type (ata or scsi) based on device name (Linux
2962 // specific) SCSI device name in linux can be sd, sr, scd, st, nst,
2963 // osst, nosst and sg.
2964 static const char * lin_dev_prefix = "/dev/";
2965 static const char * lin_dev_ata_disk_plus = "h";
2966 static const char * lin_dev_ata_devfs_disk_plus = "ide/";
2967 static const char * lin_dev_scsi_devfs_disk_plus = "scsi/";
2968 static const char * lin_dev_scsi_disk_plus = "s";
2969 static const char * lin_dev_scsi_tape1 = "ns";
2970 static const char * lin_dev_scsi_tape2 = "os";
2971 static const char * lin_dev_scsi_tape3 = "nos";
2972 static const char * lin_dev_3ware_9000_char = "twa";
2973 static const char * lin_dev_3ware_678k_char = "twe";
2974 static const char * lin_dev_cciss_dir = "cciss/";
2975 static const char * lin_dev_areca = "sg";
2976
2977 smart_device * linux_smart_interface::autodetect_smart_device(const char * name)
2978 {
2979 const char * dev_name = name; // TODO: Remove this hack
2980 int dev_prefix_len = strlen(lin_dev_prefix);
2981
2982 // if dev_name null, or string length zero
2983 int len;
2984 if (!dev_name || !(len = strlen(dev_name)))
2985 return 0;
2986
2987 // Dereference if /dev/disk/by-*/* symlink
2988 char linkbuf[100];
2989 if ( str_starts_with(dev_name, "/dev/disk/by-")
2990 && readlink(dev_name, linkbuf, sizeof(linkbuf)) > 0
2991 && str_starts_with(linkbuf, "../../")) {
2992 dev_name = linkbuf + sizeof("../../")-1;
2993 }
2994 // Remove the leading /dev/... if it's there
2995 else if (!strncmp(lin_dev_prefix, dev_name, dev_prefix_len)) {
2996 if (len <= dev_prefix_len)
2997 // if nothing else in the string, unrecognized
2998 return 0;
2999 // else advance pointer to following characters
3000 dev_name += dev_prefix_len;
3001 }
3002
3003 // form /dev/h* or h*
3004 if (!strncmp(lin_dev_ata_disk_plus, dev_name,
3005 strlen(lin_dev_ata_disk_plus)))
3006 return new linux_ata_device(this, name, "");
3007
3008 // form /dev/ide/* or ide/*
3009 if (!strncmp(lin_dev_ata_devfs_disk_plus, dev_name,
3010 strlen(lin_dev_ata_devfs_disk_plus)))
3011 return new linux_ata_device(this, name, "");
3012
3013 // form /dev/s* or s*
3014 if (!strncmp(lin_dev_scsi_disk_plus, dev_name,
3015 strlen(lin_dev_scsi_disk_plus))) {
3016
3017 // Try to detect possible USB->(S)ATA bridge
3018 unsigned short vendor_id = 0, product_id = 0, version = 0;
3019 if (get_usb_id(dev_name, vendor_id, product_id, version)) {
3020 const char * usbtype = get_usb_dev_type_by_id(vendor_id, product_id, version);
3021 if (!usbtype)
3022 return 0;
3023 // Linux USB layer does not support 16 byte SAT pass through command
3024 if (!strcmp(usbtype, "sat"))
3025 usbtype = "sat,12";
3026 // Return SAT/USB device for this type
3027 // (Note: linux_scsi_device::autodetect_open() will not be called in this case)
3028 return get_sat_device(usbtype, new linux_scsi_device(this, name, ""));
3029 }
3030
3031 // No USB bridge found, assume regular SCSI device
3032 return new linux_scsi_device(this, name, "");
3033 }
3034
3035 // form /dev/scsi/* or scsi/*
3036 if (!strncmp(lin_dev_scsi_devfs_disk_plus, dev_name,
3037 strlen(lin_dev_scsi_devfs_disk_plus)))
3038 return new linux_scsi_device(this, name, "");
3039
3040 // form /dev/ns* or ns*
3041 if (!strncmp(lin_dev_scsi_tape1, dev_name,
3042 strlen(lin_dev_scsi_tape1)))
3043 return new linux_scsi_device(this, name, "");
3044
3045 // form /dev/os* or os*
3046 if (!strncmp(lin_dev_scsi_tape2, dev_name,
3047 strlen(lin_dev_scsi_tape2)))
3048 return new linux_scsi_device(this, name, "");
3049
3050 // form /dev/nos* or nos*
3051 if (!strncmp(lin_dev_scsi_tape3, dev_name,
3052 strlen(lin_dev_scsi_tape3)))
3053 return new linux_scsi_device(this, name, "");
3054
3055 // form /dev/twa*
3056 if (!strncmp(lin_dev_3ware_9000_char, dev_name,
3057 strlen(lin_dev_3ware_9000_char)))
3058 return missing_option("-d 3ware,N");
3059
3060 // form /dev/twe*
3061 if (!strncmp(lin_dev_3ware_678k_char, dev_name,
3062 strlen(lin_dev_3ware_678k_char)))
3063 return missing_option("-d 3ware,N");
3064
3065 // form /dev/cciss*
3066 if (!strncmp(lin_dev_cciss_dir, dev_name,
3067 strlen(lin_dev_cciss_dir)))
3068 return missing_option("-d cciss,N");
3069
3070 // form /dev/sg*
3071 if ( !strncmp(lin_dev_areca, dev_name,
3072 strlen(lin_dev_areca)) )
3073 return missing_option("-d areca,N");
3074
3075 // we failed to recognize any of the forms
3076 return 0;
3077 }
3078
3079 smart_device * linux_smart_interface::get_custom_smart_device(const char * name, const char * type)
3080 {
3081 // Marvell ?
3082 if (!strcmp(type, "marvell"))
3083 return new linux_marvell_device(this, name, type);
3084
3085 // 3Ware ?
3086 int disknum = -1, n1 = -1, n2 = -1;
3087 if (sscanf(type, "3ware,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
3088 if (n2 != (int)strlen(type)) {
3089 set_err(EINVAL, "Option -d 3ware,N requires N to be a non-negative integer");
3090 return 0;
3091 }
3092 if (!(0 <= disknum && disknum <= 127)) {
3093 set_err(EINVAL, "Option -d 3ware,N (N=%d) must have 0 <= N <= 127", disknum);
3094 return 0;
3095 }
3096
3097 if (!strncmp(name, "/dev/twa", 8))
3098 return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_9000_CHAR, disknum);
3099 else if (!strncmp(name, "/dev/twe", 8))
3100 return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_678K_CHAR, disknum);
3101 else
3102 return new linux_escalade_device(this, name, linux_escalade_device::AMCC_3WARE_678K, disknum);
3103 }
3104
3105 // Areca?
3106 disknum = n1 = n2 = -1;
3107 if (sscanf(type, "areca,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
3108 if (n2 != (int)strlen(type)) {
3109 set_err(EINVAL, "Option -d areca,N requires N to be a non-negative integer");
3110 return 0;
3111 }
3112 if (!(1 <= disknum && disknum <= 24)) {
3113 set_err(EINVAL, "Option -d areca,N (N=%d) must have 1 <= N <= 24", disknum);
3114 return 0;
3115 }
3116 return new linux_areca_device(this, name, disknum);
3117 }
3118
3119 // Highpoint ?
3120 int controller = -1, channel = -1; disknum = 1;
3121 n1 = n2 = -1; int n3 = -1;
3122 if (sscanf(type, "hpt,%n%d/%d%n/%d%n", &n1, &controller, &channel, &n2, &disknum, &n3) >= 2 || n1 == 4) {
3123 int len = strlen(type);
3124 if (!(n2 == len || n3 == len)) {
3125 set_err(EINVAL, "Option '-d hpt,L/M/N' supports 2-3 items");
3126 return 0;
3127 }
3128 if (!(1 <= controller && controller <= 8)) {
3129 set_err(EINVAL, "Option '-d hpt,L/M/N' invalid controller id L supplied");
3130 return 0;
3131 }
3132 if (!(1 <= channel && channel <= 8)) {
3133 set_err(EINVAL, "Option '-d hpt,L/M/N' invalid channel number M supplied");
3134 return 0;
3135 }
3136 if (!(1 <= disknum && disknum <= 15)) {
3137 set_err(EINVAL, "Option '-d hpt,L/M/N' invalid pmport number N supplied");
3138 return 0;
3139 }
3140 return new linux_highpoint_device(this, name, controller, channel, disknum);
3141 }
3142
3143 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3144 // CCISS ?
3145 disknum = n1 = n2 = -1;
3146 if (sscanf(type, "cciss,%n%d%n", &n1, &disknum, &n2) == 1 || n1 == 6) {
3147 if (n2 != (int)strlen(type)) {
3148 set_err(EINVAL, "Option -d cciss,N requires N to be a non-negative integer");
3149 return 0;
3150 }
3151 if (!(0 <= disknum && disknum <= 15)) {
3152 set_err(EINVAL, "Option -d cciss,N (N=%d) must have 0 <= N <= 15", disknum);
3153 return 0;
3154 }
3155 return new linux_cciss_device(this, name, disknum);
3156 }
3157 #endif // HAVE_LINUX_CCISS_IOCTL_H
3158
3159 // MegaRAID ?
3160 if (sscanf(type, "megaraid,%d", &disknum) == 1) {
3161 return new linux_megaraid_device(this, name, 0, disknum);
3162 }
3163 return 0;
3164 }
3165
3166 std::string linux_smart_interface::get_valid_custom_dev_types_str()
3167 {
3168 return "marvell, areca,N, 3ware,N, hpt,L/M/N, megaraid,N"
3169 #ifdef HAVE_LINUX_CCISS_IOCTL_H
3170 ", cciss,N"
3171 #endif
3172 ;
3173 }
3174
3175 } // namespace
3176
3177
3178 /////////////////////////////////////////////////////////////////////////////
3179 /// Initialize platform interface and register with smi()
3180
3181 void smart_interface::init()
3182 {
3183 static os_linux::linux_smart_interface the_interface;
3184 smart_interface::set(&the_interface);
3185 }