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