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