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