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