patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / message / fusion / mptctl.c
1 /*
2  *  linux/drivers/message/fusion/mptctl.c
3  *      Fusion MPT misc device (ioctl) driver.
4  *      For use with PCI chip/adapter(s):
5  *          LSIFC9xx/LSI409xx Fibre Channel
6  *      running LSI Logic Fusion MPT (Message Passing Technology) firmware.
7  *
8  *  Credits:
9  *      This driver would not exist if not for Alan Cox's development
10  *      of the linux i2o driver.
11  *
12  *      A special thanks to Pamela Delaney (LSI Logic) for tons of work
13  *      and countless enhancements while adding support for the 1030
14  *      chip family.  Pam has been instrumental in the development of
15  *      of the 2.xx.xx series fusion drivers, and her contributions are
16  *      far too numerous to hope to list in one place.
17  *
18  *      A huge debt of gratitude is owed to David S. Miller (DaveM)
19  *      for fixing much of the stupid and broken stuff in the early
20  *      driver while porting to sparc64 platform.  THANK YOU!
21  *
22  *      A big THANKS to Eddie C. Dost for fixing the ioctl path
23  *      and most importantly f/w download on sparc64 platform!
24  *      (plus Eddie's other helpful hints and insights)
25  *
26  *      Thanks to Arnaldo Carvalho de Melo for finding and patching
27  *      a potential memory leak in mptctl_do_fw_download(),
28  *      and for some kmalloc insight:-)
29  *
30  *      (see also mptbase.c)
31  *
32  *  Copyright (c) 1999-2004 LSI Logic Corporation
33  *  Originally By: Steven J. Ralston, Noah Romer
34  *  (mailto:sjralston1@netscape.net)
35  *  (mailto:mpt_linux_developer@lsil.com)
36  *
37  *  $Id: mptctl.c,v 1.63 2002/12/03 21:26:33 pdelaney Exp $
38  */
39 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
40 /*
41     This program is free software; you can redistribute it and/or modify
42     it under the terms of the GNU General Public License as published by
43     the Free Software Foundation; version 2 of the License.
44
45     This program is distributed in the hope that it will be useful,
46     but WITHOUT ANY WARRANTY; without even the implied warranty of
47     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
48     GNU General Public License for more details.
49
50     NO WARRANTY
51     THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
52     CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
53     LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
54     MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
55     solely responsible for determining the appropriateness of using and
56     distributing the Program and assumes all risks associated with its
57     exercise of rights under this Agreement, including but not limited to
58     the risks and costs of program errors, damage to or loss of data,
59     programs or equipment, and unavailability or interruption of operations.
60
61     DISCLAIMER OF LIABILITY
62     NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
63     DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64     DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
65     ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
66     TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
67     USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
68     HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
69
70     You should have received a copy of the GNU General Public License
71     along with this program; if not, write to the Free Software
72     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
73 */
74 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
75
76 #include <linux/version.h>
77 #include <linux/kernel.h>
78 #include <linux/module.h>
79 #include <linux/errno.h>
80 #include <linux/init.h>
81 #include <linux/slab.h>
82 #include <linux/types.h>
83 #include <linux/pci.h>
84 #include <linux/miscdevice.h>
85 #include <linux/smp_lock.h>
86
87 #include <asm/io.h>
88 #include <asm/uaccess.h>
89
90 #include <linux/kdev_t.h>       /* needed for access to Scsi_Host struct */
91 #include <linux/blkdev.h>
92 #include "../../scsi/scsi.h"
93 #include "../../scsi/hosts.h"
94
95 #define COPYRIGHT       "Copyright (c) 1999-2004 LSI Logic Corporation"
96 #define MODULEAUTHOR    "Steven J. Ralston, Noah Romer, Pamela Delaney"
97 #include "mptbase.h"
98 #include "mptctl.h"
99
100 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
101 #define my_NAME         "Fusion MPT misc device (ioctl) driver"
102 #define my_VERSION      MPT_LINUX_VERSION_COMMON
103 #define MYNAM           "mptctl"
104
105 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,62)
106 EXPORT_NO_SYMBOLS;
107 #endif
108 MODULE_AUTHOR(MODULEAUTHOR);
109 MODULE_DESCRIPTION(my_NAME);
110 MODULE_LICENSE("GPL");
111
112 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
113
114 static int mptctl_id = -1;
115 static struct semaphore mptctl_syscall_sem_ioc[MPT_MAX_ADAPTERS];
116
117 static DECLARE_WAIT_QUEUE_HEAD ( mptctl_wait );
118
119 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
120
121 struct buflist {
122         u8      *kptr;
123         int      len;
124 };
125
126 /*
127  * Function prototypes. Called from OS entry point mptctl_ioctl.
128  * arg contents specific to function.
129  */
130 static int mptctl_fw_download(unsigned long arg);
131 static int mptctl_getiocinfo (unsigned long arg, unsigned int cmd);
132 static int mptctl_gettargetinfo (unsigned long arg);
133 static int mptctl_readtest (unsigned long arg);
134 static int mptctl_mpt_command (unsigned long arg);
135 static int mptctl_eventquery (unsigned long arg);
136 static int mptctl_eventenable (unsigned long arg);
137 static int mptctl_eventreport (unsigned long arg);
138 static int mptctl_replace_fw (unsigned long arg);
139
140 static int mptctl_do_reset(unsigned long arg);
141 static int mptctl_hp_hostinfo(unsigned long arg, unsigned int cmd);
142 static int mptctl_hp_targetinfo(unsigned long arg);
143
144 /*
145  * Private function calls.
146  */
147 static int mptctl_do_mpt_command (struct mpt_ioctl_command karg, char *mfPtr, int local);
148 static int mptctl_do_fw_download(int ioc, char *ufwbuf, size_t fwlen);
149 static MptSge_t *kbuf_alloc_2_sgl( int bytes, u32 dir, int sge_offset, int *frags,
150                 struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc);
151 static void kfree_sgl( MptSge_t *sgl, dma_addr_t sgl_dma,
152                 struct buflist *buflist, MPT_ADAPTER *ioc);
153 static void mptctl_timer_expired (unsigned long data);
154 static int  mptctl_bus_reset(MPT_IOCTL *ioctl);
155 static int mptctl_set_tm_flags(MPT_SCSI_HOST *hd);
156 static void mptctl_free_tm_flags(MPT_ADAPTER *ioc);
157
158 /*
159  * Reset Handler cleanup function
160  */
161 static int  mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase);
162
163 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
164 /*
165  * Scatter gather list (SGL) sizes and limits...
166  */
167 //#define MAX_SCSI_FRAGS        9
168 #define MAX_FRAGS_SPILL1        9
169 #define MAX_FRAGS_SPILL2        15
170 #define FRAGS_PER_BUCKET        (MAX_FRAGS_SPILL2 + 1)
171
172 //#define MAX_CHAIN_FRAGS       64
173 //#define MAX_CHAIN_FRAGS       (15+15+15+16)
174 #define MAX_CHAIN_FRAGS         (4 * MAX_FRAGS_SPILL2 + 1)
175
176 //  Define max sg LIST bytes ( == (#frags + #chains) * 8 bytes each)
177 //  Works out to: 592d bytes!     (9+1)*8 + 4*(15+1)*8
178 //                  ^----------------- 80 + 512
179 #define MAX_SGL_BYTES           ((MAX_FRAGS_SPILL1 + 1 + (4 * FRAGS_PER_BUCKET)) * 8)
180
181 /* linux only seems to ever give 128kB MAX contiguous (GFP_USER) mem bytes */
182 #define MAX_KMALLOC_SZ          (128*1024)
183
184 #define MPT_IOCTL_DEFAULT_TIMEOUT 10    /* Default timeout value (seconds) */
185
186 static u32 fwReplyBuffer[16];
187 static pMPIDefaultReply_t ReplyMsg = NULL;
188
189 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
190 /**
191  *      mptctl_syscall_down - Down the MPT adapter syscall semaphore.
192  *      @ioc: Pointer to MPT adapter
193  *      @nonblock: boolean, non-zero if O_NONBLOCK is set
194  *
195  *      All of the ioctl commands can potentially sleep, which is illegal
196  *      with a spinlock held, thus we perform mutual exclusion here.
197  *
198  *      Returns negative errno on error, or zero for success.
199  */
200 static inline int
201 mptctl_syscall_down(MPT_ADAPTER *ioc, int nonblock)
202 {
203         int rc = 0;
204         dctlprintk((KERN_INFO MYNAM "::mptctl_syscall_down(%p,%d) called\n", ioc, nonblock));
205
206         if (ioc->ioctl->tmPtr != NULL) {
207                 dctlprintk((KERN_INFO MYNAM "::mptctl_syscall_down BUSY\n"));
208                 return -EBUSY;
209         }
210
211         if (nonblock) {
212                 if (down_trylock(&mptctl_syscall_sem_ioc[ioc->id]))
213                         rc = -EAGAIN;
214         } else {
215                 if (down_interruptible(&mptctl_syscall_sem_ioc[ioc->id]))
216                         rc = -ERESTARTSYS;
217         }
218         dctlprintk((KERN_INFO MYNAM "::mptctl_syscall_down return %d\n", rc));
219         return rc;
220 }
221
222 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
223 /*
224  *  This is the callback for any message we have posted. The message itself
225  *  will be returned to the message pool when we return from the IRQ
226  *
227  *  This runs in irq context so be short and sweet.
228  */
229 static int
230 mptctl_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *req, MPT_FRAME_HDR *reply)
231 {
232         char *sense_data;
233         int sz, req_index;
234         u16 iocStatus;
235         u8 cmd;
236
237         dctlprintk((MYIOC_s_INFO_FMT ": mptctl_reply()!\n", ioc->name));
238         if (req)
239                  cmd = req->u.hdr.Function;
240         else
241                 return 1;
242
243         if (ioc->ioctl) {
244                 /* If timer is not running, then an error occurred.
245                  * A timeout will call the reset routine to reload the messaging
246                  * queues.
247                  * Main callback will free message and reply frames.
248                  */
249                 if (reply && (cmd == MPI_FUNCTION_SCSI_TASK_MGMT) &&
250                     (ioc->ioctl->status & MPT_IOCTL_STATUS_TMTIMER_ACTIVE)) {
251                         /* This is internally generated TM
252                          */
253                         del_timer (&ioc->ioctl->TMtimer);
254                         ioc->ioctl->status &= ~MPT_IOCTL_STATUS_TMTIMER_ACTIVE;
255
256                         mptctl_free_tm_flags(ioc);
257
258                         /* If TM failed, reset the timer on the existing command,
259                          * will trigger an adapter reset.
260                          */
261                         iocStatus = reply->u.reply.IOCStatus & MPI_IOCSTATUS_MASK;
262                         if (iocStatus == MPI_IOCSTATUS_SCSI_TASK_MGMT_FAILED) {
263                                 if (ioc->ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE) {
264                                         ioc->ioctl->reset &= ~MPTCTL_RESET_OK;
265                                         del_timer (&ioc->ioctl->timer);
266                                         ioc->ioctl->timer.expires = jiffies + HZ;
267                                         add_timer(&ioc->ioctl->timer);
268                                 }
269                         }
270                         ioc->ioctl->tmPtr = NULL;
271
272                 } else if (ioc->ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE) {
273                         /* Delete this timer
274                          */
275                         del_timer (&ioc->ioctl->timer);
276                         ioc->ioctl->status &= ~MPT_IOCTL_STATUS_TIMER_ACTIVE;
277
278                         /* Set the overall status byte.  Good if:
279                          * IOC status is good OR if no reply and a SCSI IO request
280                          */
281                         if (reply) {
282                                 /* Copy the reply frame (which much exist
283                                  * for non-SCSI I/O) to the IOC structure.
284                                  */
285                                 dctlprintk((MYIOC_s_INFO_FMT ": Copying Reply Frame @%p to IOC!\n",
286                                                 ioc->name, reply));
287                                 memcpy(ioc->ioctl->ReplyFrame, reply,
288                                         min(ioc->reply_sz, 4*reply->u.reply.MsgLength));
289                                 ioc->ioctl->status |= MPT_IOCTL_STATUS_RF_VALID;
290
291                                 /* Set the command status to GOOD if IOC Status is GOOD
292                                  * OR if SCSI I/O cmd and data underrun or recovered error.
293                                  */
294                                 iocStatus = reply->u.reply.IOCStatus & MPI_IOCSTATUS_MASK;
295                                 if (iocStatus  == MPI_IOCSTATUS_SUCCESS)
296                                         ioc->ioctl->status |= MPT_IOCTL_STATUS_COMMAND_GOOD;
297
298                                 if ((cmd == MPI_FUNCTION_SCSI_IO_REQUEST) ||
299                                         (cmd == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
300                                         ioc->ioctl->reset &= ~MPTCTL_RESET_OK;
301
302                                         if ((iocStatus == MPI_IOCSTATUS_SCSI_DATA_UNDERRUN) ||
303                                                 (iocStatus == MPI_IOCSTATUS_SCSI_RECOVERED_ERROR)) {
304                                                 ioc->ioctl->status |= MPT_IOCTL_STATUS_COMMAND_GOOD;
305                                         }
306                                 }
307
308                                 /* Copy the sense data - if present
309                                  */
310                                 if ((cmd == MPI_FUNCTION_SCSI_IO_REQUEST) &&
311                                         (reply->u.sreply.SCSIState & MPI_SCSI_STATE_AUTOSENSE_VALID)){
312
313                                         sz = req->u.scsireq.SenseBufferLength;
314                                         req_index = le16_to_cpu(req->u.frame.hwhdr.msgctxu.fld.req_idx);
315                                         sense_data = ((u8 *)ioc->sense_buf_pool + (req_index * MPT_SENSE_BUFFER_ALLOC));
316                                         memcpy(ioc->ioctl->sense, sense_data, sz);
317                                         ioc->ioctl->status |= MPT_IOCTL_STATUS_SENSE_VALID;
318                                 }
319
320                                 if (cmd == MPI_FUNCTION_SCSI_TASK_MGMT)
321                                         mptctl_free_tm_flags(ioc);
322
323
324                         } else if ((cmd == MPI_FUNCTION_SCSI_IO_REQUEST) ||
325                                         (cmd == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
326                                 ioc->ioctl->status |= MPT_IOCTL_STATUS_COMMAND_GOOD;
327                                 ioc->ioctl->reset &= ~MPTCTL_RESET_OK;
328                         }
329
330                         /* We are done, issue wake up
331                          */
332                         ioc->ioctl->wait_done = 1;
333                         wake_up (&mptctl_wait);
334                 } else if (reply && cmd == MPI_FUNCTION_FW_DOWNLOAD) {
335                         /* Two paths to FW DOWNLOAD! */
336                         // NOTE: Expects/requires non-Turbo reply!
337                         dctlprintk((MYIOC_s_INFO_FMT ":Caching MPI_FUNCTION_FW_DOWNLOAD reply!\n",
338                                 ioc->name));
339                         memcpy(fwReplyBuffer, reply, min_t(int, sizeof(fwReplyBuffer), 4*reply->u.reply.MsgLength));
340                         ReplyMsg = (pMPIDefaultReply_t) fwReplyBuffer;
341                 }
342         }
343         return 1;
344 }
345
346 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
347 /* mptctl_timer_expired
348  *
349  * Call back for timer process. Used only for ioctl functionality.
350  *
351  */
352 static void mptctl_timer_expired (unsigned long data)
353 {
354         MPT_IOCTL *ioctl = (MPT_IOCTL *) data;
355         int rc = 1;
356
357         dctlprintk((KERN_NOTICE MYNAM ": Timer Expired! Host %d\n",
358                                 ioctl->ioc->id));
359         if (ioctl == NULL)
360                 return;
361
362         if (ioctl->reset & MPTCTL_RESET_OK)
363                 rc = mptctl_bus_reset(ioctl);
364
365         if (rc) {
366                 /* Issue a reset for this device.
367                  * The IOC is not responding.
368                  */
369                 mpt_HardResetHandler(ioctl->ioc, NO_SLEEP);
370         }
371         return;
372
373 }
374
375 /* mptctl_bus_reset
376  *
377  * Bus reset code.
378  *
379  */
380 static int mptctl_bus_reset(MPT_IOCTL *ioctl)
381 {
382         MPT_FRAME_HDR   *mf;
383         SCSITaskMgmt_t  *pScsiTm;
384         MPT_SCSI_HOST   *hd;
385         int              ii;
386         int              retval;
387
388
389         ioctl->reset &= ~MPTCTL_RESET_OK;
390
391         if (ioctl->ioc->sh == NULL)
392                 return -EPERM;
393         
394         hd = (MPT_SCSI_HOST *) ioctl->ioc->sh->hostdata;
395         if (hd == NULL)
396                 return -EPERM;
397
398         /* Single threading ....
399          */
400         if (mptctl_set_tm_flags(hd) != 0)
401                 return -EPERM;
402
403         /* Send request
404          */
405         if ((mf = mpt_get_msg_frame(mptctl_id, ioctl->ioc->id)) == NULL) {
406                 dctlprintk((MYIOC_s_WARN_FMT "IssueTaskMgmt, no msg frames!!\n",
407                                 ioctl->ioc->name));
408
409                 mptctl_free_tm_flags(ioctl->ioc);
410                 return -ENOMEM;
411         }
412
413         dtmprintk((MYIOC_s_INFO_FMT "IssueTaskMgmt request @ %p\n",
414                         ioctl->ioc->name, mf));
415
416         pScsiTm = (SCSITaskMgmt_t *) mf;
417         pScsiTm->TargetID = ioctl->target;
418         pScsiTm->Bus = hd->port;        /* 0 */
419         pScsiTm->ChainOffset = 0;
420         pScsiTm->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
421         pScsiTm->Reserved = 0;
422         pScsiTm->TaskType = MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS;
423         pScsiTm->Reserved1 = 0;
424         pScsiTm->MsgFlags = MPI_SCSITASKMGMT_MSGFLAGS_LIPRESET_RESET_OPTION;
425
426         for (ii= 0; ii < 8; ii++)
427                 pScsiTm->LUN[ii] = 0;
428
429         for (ii=0; ii < 7; ii++)
430                 pScsiTm->Reserved2[ii] = 0;
431
432         pScsiTm->TaskMsgContext = 0;
433         dtmprintk((MYIOC_s_INFO_FMT "mptctl_bus_reset: issued.\n", ioctl->ioc->name));
434
435         ioctl->tmPtr = mf;
436         ioctl->TMtimer.expires = jiffies + HZ * 20;     /* 20 seconds */
437         ioctl->status |= MPT_IOCTL_STATUS_TMTIMER_ACTIVE;
438         add_timer(&ioctl->TMtimer);
439
440         retval = mpt_send_handshake_request(mptctl_id, ioctl->ioc->id,
441                         sizeof(SCSITaskMgmt_t), (u32*)pScsiTm, NO_SLEEP);
442
443         if (retval != 0) {
444                 dtmprintk((MYIOC_s_WARN_FMT "_send_handshake FAILED!"
445                         " (hd %p, ioc %p, mf %p) \n", ioctl->ioc->name, hd, hd->ioc, mf));
446
447                 mptctl_free_tm_flags(ioctl->ioc);
448                 del_timer(&ioctl->TMtimer);
449                 mpt_free_msg_frame(mptctl_id, ioctl->ioc->id, mf);
450                 ioctl->tmPtr = NULL;
451         }
452
453         return retval;
454 }
455
456 static int
457 mptctl_set_tm_flags(MPT_SCSI_HOST *hd) {
458         unsigned long flags;
459
460         spin_lock_irqsave(&hd->ioc->FreeQlock, flags);
461
462         if (hd->tmState == TM_STATE_NONE) {
463                 hd->tmState = TM_STATE_IN_PROGRESS;
464                 hd->tmPending = 1;
465                 spin_unlock_irqrestore(&hd->ioc->FreeQlock, flags);
466         } else {
467                 spin_unlock_irqrestore(&hd->ioc->FreeQlock, flags);
468                 return -EBUSY;
469         }
470
471         return 0;
472 }
473
474 static void
475 mptctl_free_tm_flags(MPT_ADAPTER *ioc)
476 {
477         MPT_SCSI_HOST * hd;
478         unsigned long flags;
479
480         hd = (MPT_SCSI_HOST *) ioc->sh->hostdata;
481         if (hd == NULL)
482                 return;
483
484         spin_lock_irqsave(&ioc->FreeQlock, flags);
485
486         hd->tmState = TM_STATE_ERROR;
487         hd->tmPending = 0;
488         spin_unlock_irqrestore(&ioc->FreeQlock, flags);
489
490         return;
491 }
492
493
494 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
495 /* mptctl_ioc_reset
496  *
497  * Clean-up functionality. Used only if there has been a
498  * reload of the FW due.
499  *
500  */
501 static int
502 mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase)
503 {
504         MPT_IOCTL *ioctl = ioc->ioctl;
505         dctlprintk((KERN_INFO MYNAM ": IOC %s_reset routed to IOCTL driver!\n",
506                         reset_phase==MPT_IOC_SETUP_RESET ? "setup" : (
507                         reset_phase==MPT_IOC_PRE_RESET ? "pre" : "post")));
508
509         if (reset_phase == MPT_IOC_SETUP_RESET){
510                 ;
511         } else if (reset_phase == MPT_IOC_PRE_RESET){
512
513                 /* Someone has called the reset handler to
514                  * do a hard reset. No more replies from the FW.
515                  * Delete the timer. TM flags cleaned up by SCSI driver.
516                  * Do not need to free msg frame, as re-initialized
517                  */
518                 if (ioctl && (ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE)){
519                         del_timer(&ioctl->timer);
520                 }
521                 if (ioctl && (ioctl->status & MPT_IOCTL_STATUS_TMTIMER_ACTIVE)){
522                         ioctl->status &= ~MPT_IOCTL_STATUS_TMTIMER_ACTIVE;
523                         del_timer(&ioctl->TMtimer);
524                         mpt_free_msg_frame(mptctl_id, ioc->id, ioctl->tmPtr);
525                 }
526
527         } else {
528                 ioctl->tmPtr = NULL;
529
530                 /* Set the status and continue IOCTL
531                  * processing. All memory will be free'd
532                  * by originating thread after wake_up is
533                  * called.
534                  */
535                 if (ioctl && (ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE)){
536                         ioctl->status |= MPT_IOCTL_STATUS_DID_IOCRESET;
537
538                         /* Wake up the calling process
539                          */
540                         ioctl->wait_done = 1;
541                         wake_up(&mptctl_wait);
542                 }
543         }
544
545         return 1;
546 }
547
548 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
549 /*
550  *  struct file_operations functionality.
551  *  Members:
552  *      llseek, write, read, ioctl, open, release
553  */
554 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
555 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,9)
556 static loff_t
557 mptctl_llseek(struct file *file, loff_t offset, int origin)
558 {
559         return -ESPIPE;
560 }
561 #define no_llseek mptctl_llseek
562 #endif
563
564 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
565 static ssize_t
566 mptctl_write(struct file *file, const char *buf, size_t count, loff_t *ppos)
567 {
568         printk(KERN_ERR MYNAM ": ioctl WRITE not yet supported\n");
569         return 0;
570 }
571
572 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
573 static ssize_t
574 mptctl_read(struct file *file, char *buf, size_t count, loff_t *ptr)
575 {
576         printk(KERN_ERR MYNAM ": ioctl READ not yet supported\n");
577         return 0;
578 }
579
580 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
581 /*
582  *  MPT ioctl handler
583  *  cmd - specify the particular IOCTL command to be issued
584  *  arg - data specific to the command. Must not be null.
585  */
586 static int
587 mptctl_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
588 {
589         mpt_ioctl_header        *uhdr = (mpt_ioctl_header *) arg;
590         mpt_ioctl_header         khdr;
591         int iocnum;
592         unsigned iocnumX;
593         int nonblock = (file->f_flags & O_NONBLOCK);
594         int ret;
595         MPT_ADAPTER *iocp = NULL;
596
597         dctlprintk(("mptctl_ioctl() called\n"));
598
599         if (copy_from_user(&khdr, uhdr, sizeof(khdr))) {
600                 printk(KERN_ERR "%s::mptctl_ioctl() @%d - "
601                                 "Unable to copy mpt_ioctl_header data @ %p\n",
602                                 __FILE__, __LINE__, (void*)uhdr);
603                 return -EFAULT;
604         }
605         ret = -ENXIO;                           /* (-6) No such device or address */
606
607         /* Verify intended MPT adapter - set iocnum and the adapter
608          * pointer (iocp)
609          */
610         iocnumX = khdr.iocnum & 0xFF;
611         if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
612             (iocp == NULL)) {
613                 dctlprintk((KERN_ERR "%s::mptctl_ioctl() @%d - ioc%d not found!\n",
614                                 __FILE__, __LINE__, iocnumX));
615                 return -ENODEV;
616         }
617
618         if (!iocp->active) {
619                 printk(KERN_ERR "%s::mptctl_ioctl() @%d - Controller disabled.\n",
620                                 __FILE__, __LINE__);
621                 return -EFAULT;
622         }
623
624         /* Handle those commands that are just returning
625          * information stored in the driver.
626          * These commands should never time out and are unaffected
627          * by TM and FW reloads.
628          */
629         if ((cmd & ~IOCSIZE_MASK) == (MPTIOCINFO & ~IOCSIZE_MASK)) {
630                 return mptctl_getiocinfo(arg, _IOC_SIZE(cmd));
631         } else if (cmd == MPTTARGETINFO) {
632                 return mptctl_gettargetinfo(arg);
633         } else if (cmd == MPTTEST) {
634                 return mptctl_readtest(arg);
635         } else if (cmd == MPTEVENTQUERY) {
636                 return mptctl_eventquery(arg);
637         } else if (cmd == MPTEVENTENABLE) {
638                 return mptctl_eventenable(arg);
639         } else if (cmd == MPTEVENTREPORT) {
640                 return mptctl_eventreport(arg);
641         } else if (cmd == MPTFWREPLACE) {
642                 return mptctl_replace_fw(arg);
643         }
644
645         /* All of these commands require an interrupt or
646          * are unknown/illegal.
647          */
648         if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
649                 return ret;
650
651         dctlprintk((MYIOC_s_INFO_FMT ": mptctl_ioctl()\n", iocp->name));
652
653         if (cmd == MPTFWDOWNLOAD)
654                 ret = mptctl_fw_download(arg);
655         else if (cmd == MPTCOMMAND)
656                 ret = mptctl_mpt_command(arg);
657         else if (cmd == MPTHARDRESET)
658                 ret = mptctl_do_reset(arg);
659         else if ((cmd & ~IOCSIZE_MASK) == (HP_GETHOSTINFO & ~IOCSIZE_MASK))
660                 ret = mptctl_hp_hostinfo(arg, _IOC_SIZE(cmd));
661         else if (cmd == HP_GETTARGETINFO)
662                 ret = mptctl_hp_targetinfo(arg);
663         else
664                 ret = -EINVAL;
665
666
667         up(&mptctl_syscall_sem_ioc[iocp->id]);
668
669         return ret;
670 }
671
672 static int mptctl_do_reset(unsigned long arg)
673 {
674         struct mpt_ioctl_diag_reset *urinfo = (struct mpt_ioctl_diag_reset *) arg;
675         struct mpt_ioctl_diag_reset krinfo;
676         MPT_ADAPTER             *iocp;
677
678         dctlprintk((KERN_INFO "mptctl_do_reset called.\n"));
679
680         if (copy_from_user(&krinfo, urinfo, sizeof(struct mpt_ioctl_diag_reset))) {
681                 printk(KERN_ERR "%s@%d::mptctl_do_reset - "
682                                 "Unable to copy mpt_ioctl_diag_reset struct @ %p\n",
683                                 __FILE__, __LINE__, (void*)urinfo);
684                 return -EFAULT;
685         }
686
687         if (mpt_verify_adapter(krinfo.hdr.iocnum, &iocp) < 0) {
688                 dctlprintk((KERN_ERR "%s@%d::mptctl_do_reset - ioc%d not found!\n",
689                                 __FILE__, __LINE__, krinfo.hdr.iocnum));
690                 return -ENODEV; /* (-6) No such device or address */
691         }
692
693         if (mpt_HardResetHandler(iocp, CAN_SLEEP) != 0) {
694                 printk (KERN_ERR "%s@%d::mptctl_do_reset - reset failed.\n",
695                         __FILE__, __LINE__);
696                 return -1;
697         }
698
699         return 0;
700 }
701
702 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
703 static int mptctl_open(struct inode *inode, struct file *file)
704 {
705         /*
706          * Should support multiple management users
707          */
708         return 0;
709 }
710
711 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
712 static int mptctl_release(struct inode *inode, struct file *file)
713 {
714         return 0;
715 }
716
717 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
718 /*
719  * MPT FW download function.  Cast the arg into the mpt_fw_xfer structure.
720  * This structure contains: iocnum, firmware length (bytes),
721  *      pointer to user space memory where the fw image is stored.
722  *
723  * Outputs:     None.
724  * Return:      0 if successful
725  *              -EFAULT if data unavailable
726  *              -ENXIO  if no such device
727  *              -EAGAIN if resource problem
728  *              -ENOMEM if no memory for SGE
729  *              -EMLINK if too many chain buffers required
730  *              -EBADRQC if adapter does not support FW download
731  *              -EBUSY if adapter is busy
732  *              -ENOMSG if FW upload returned bad status
733  */
734 static int
735 mptctl_fw_download(unsigned long arg)
736 {
737         struct mpt_fw_xfer      *ufwdl = (struct mpt_fw_xfer *) arg;
738         struct mpt_fw_xfer       kfwdl;
739
740         dctlprintk((KERN_INFO "mptctl_fwdl called. mptctl_id = %xh\n", mptctl_id)); //tc
741         if (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {
742                 printk(KERN_ERR "%s@%d::_ioctl_fwdl - "
743                                 "Unable to copy mpt_fw_xfer struct @ %p\n",
744                                 __FILE__, __LINE__, (void*)ufwdl);
745                 return -EFAULT;
746         }
747
748         return mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);
749 }
750
751 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
752 /*
753  * FW Download engine.
754  * Outputs:     None.
755  * Return:      0 if successful
756  *              -EFAULT if data unavailable
757  *              -ENXIO  if no such device
758  *              -EAGAIN if resource problem
759  *              -ENOMEM if no memory for SGE
760  *              -EMLINK if too many chain buffers required
761  *              -EBADRQC if adapter does not support FW download
762  *              -EBUSY if adapter is busy
763  *              -ENOMSG if FW upload returned bad status
764  */
765 static int
766 mptctl_do_fw_download(int ioc, char *ufwbuf, size_t fwlen)
767 {
768         FWDownload_t            *dlmsg;
769         MPT_FRAME_HDR           *mf;
770         MPT_ADAPTER             *iocp;
771         FWDownloadTCSGE_t       *ptsge;
772         MptSge_t                *sgl, *sgIn;
773         char                    *sgOut;
774         struct buflist          *buflist;
775         struct buflist          *bl;
776         dma_addr_t               sgl_dma;
777         int                      ret;
778         int                      numfrags = 0;
779         int                      maxfrags;
780         int                      n = 0;
781         u32                      sgdir;
782         u32                      nib;
783         int                      fw_bytes_copied = 0;
784         int                      i;
785         int                      cntdn;
786         int                      sge_offset = 0;
787         u16                      iocstat;
788
789         dctlprintk((KERN_INFO "mptctl_do_fwdl called. mptctl_id = %xh.\n", mptctl_id));
790
791         dctlprintk((KERN_INFO "DbG: kfwdl.bufp  = %p\n", ufwbuf));
792         dctlprintk((KERN_INFO "DbG: kfwdl.fwlen = %d\n", (int)fwlen));
793         dctlprintk((KERN_INFO "DbG: kfwdl.ioc   = %04xh\n", ioc));
794
795         if ((ioc = mpt_verify_adapter(ioc, &iocp)) < 0) {
796                 dctlprintk(("%s@%d::_ioctl_fwdl - ioc%d not found!\n",
797                                 __FILE__, __LINE__, ioc));
798                 return -ENODEV; /* (-6) No such device or address */
799         }
800
801         /*  Valid device. Get a message frame and construct the FW download message.
802          */
803         if ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL)
804                 return -EAGAIN;
805         dlmsg = (FWDownload_t*) mf;
806         ptsge = (FWDownloadTCSGE_t *) &dlmsg->SGL;
807         sgOut = (char *) (ptsge + 1);
808
809         /*
810          * Construct f/w download request
811          */
812         dlmsg->ImageType = MPI_FW_DOWNLOAD_ITYPE_FW;
813         dlmsg->Reserved = 0;
814         dlmsg->ChainOffset = 0;
815         dlmsg->Function = MPI_FUNCTION_FW_DOWNLOAD;
816         dlmsg->Reserved1[0] = dlmsg->Reserved1[1] = dlmsg->Reserved1[2] = 0;
817         dlmsg->MsgFlags = 0;
818
819         /* Set up the Transaction SGE.
820          */
821         ptsge->Reserved = 0;
822         ptsge->ContextSize = 0;
823         ptsge->DetailsLength = 12;
824         ptsge->Flags = MPI_SGE_FLAGS_TRANSACTION_ELEMENT;
825         ptsge->Reserved_0100_Checksum = 0;
826         ptsge->ImageOffset = 0;
827         ptsge->ImageSize = cpu_to_le32(fwlen);
828
829         /* Add the SGL
830          */
831
832         /*
833          * Need to kmalloc area(s) for holding firmware image bytes.
834          * But we need to do it piece meal, using a proper
835          * scatter gather list (with 128kB MAX hunks).
836          *
837          * A practical limit here might be # of sg hunks that fit into
838          * a single IOC request frame; 12 or 8 (see below), so:
839          * For FC9xx: 12 x 128kB == 1.5 mB (max)
840          * For C1030:  8 x 128kB == 1   mB (max)
841          * We could support chaining, but things get ugly(ier:)
842          *
843          * Set the sge_offset to the start of the sgl (bytes).
844          */
845         sgdir = 0x04000000;             /* IOC will READ from sys mem */
846         sge_offset = sizeof(MPIHeader_t) + sizeof(FWDownloadTCSGE_t);
847         if ((sgl = kbuf_alloc_2_sgl(fwlen, sgdir, sge_offset,
848                                     &numfrags, &buflist, &sgl_dma, iocp)) == NULL)
849                 return -ENOMEM;
850
851         /*
852          * We should only need SGL with 2 simple_32bit entries (up to 256 kB)
853          * for FC9xx f/w image, but calculate max number of sge hunks
854          * we can fit into a request frame, and limit ourselves to that.
855          * (currently no chain support)
856          * maxfrags = (Request Size - FWdownload Size ) / Size of 32 bit SGE
857          *      Request         maxfrags
858          *      128             12
859          *      96              8
860          *      64              4
861          */
862         maxfrags = (iocp->req_sz - sizeof(MPIHeader_t) - sizeof(FWDownloadTCSGE_t))
863                         / (sizeof(dma_addr_t) + sizeof(u32));
864         if (numfrags > maxfrags) {
865                 ret = -EMLINK;
866                 goto fwdl_out;
867         }
868
869         dctlprintk((KERN_INFO "DbG: sgl buffer  = %p, sgfrags = %d\n", sgl, numfrags));
870
871         /*
872          * Parse SG list, copying sgl itself,
873          * plus f/w image hunks from user space as we go...
874          */
875         ret = -EFAULT;
876         sgIn = sgl;
877         bl = buflist;
878         for (i=0; i < numfrags; i++) {
879
880                 /* Get the SGE type: 0 - TCSGE, 3 - Chain, 1 - Simple SGE
881                  * Skip everything but Simple. If simple, copy from
882                  *      user space into kernel space.
883                  * Note: we should not have anything but Simple as
884                  *      Chain SGE are illegal.
885                  */
886                 nib = (sgIn->FlagsLength & 0x30000000) >> 28;
887                 if (nib == 0 || nib == 3) {
888                         ;
889                 } else if (sgIn->Address) {
890                         mpt_add_sge(sgOut, sgIn->FlagsLength, sgIn->Address);
891                         n++;
892                         if (copy_from_user(bl->kptr, ufwbuf+fw_bytes_copied, bl->len)) {
893                                 printk(KERN_ERR "%s@%d::_ioctl_fwdl - "
894                                                 "Unable to copy f/w buffer hunk#%d @ %p\n",
895                                                 __FILE__, __LINE__, n, (void*)ufwbuf);
896                                 goto fwdl_out;
897                         }
898                         fw_bytes_copied += bl->len;
899                 }
900                 sgIn++;
901                 bl++;
902                 sgOut += (sizeof(dma_addr_t) + sizeof(u32));
903         }
904
905 #ifdef MPT_DEBUG
906         {
907                 u32 *m = (u32 *)mf;
908                 printk(KERN_INFO MYNAM ": F/W download request:\n" KERN_INFO " ");
909                 for (i=0; i < 7+numfrags*2; i++)
910                         printk(" %08x", le32_to_cpu(m[i]));
911                 printk("\n");
912         }
913 #endif
914
915         /*
916          * Finally, perform firmware download.
917          */
918         ReplyMsg = NULL;
919         mpt_put_msg_frame(mptctl_id, ioc, mf);
920
921         /*
922          *  Wait until the reply has been received
923          */
924         for (cntdn=HZ*60, i=1; ReplyMsg == NULL; cntdn--, i++) {
925                 if (!cntdn) {
926                         ret = -ETIME;
927                         goto fwdl_out;
928                 }
929
930                 if (!(i%HZ)) {
931                         dctlprintk((KERN_INFO "DbG::_do_fwdl: "
932                                    "In ReplyMsg loop - iteration %d\n",
933                                    i));
934                 }
935
936                 set_current_state(TASK_INTERRUPTIBLE);
937                 schedule_timeout(1);
938         }
939
940         if (sgl)
941                 kfree_sgl(sgl, sgl_dma, buflist, iocp);
942
943         iocstat = le16_to_cpu(ReplyMsg->IOCStatus) & MPI_IOCSTATUS_MASK;
944         if (iocstat == MPI_IOCSTATUS_SUCCESS) {
945                 printk(KERN_INFO MYNAM ": F/W update successfully sent to %s!\n", iocp->name);
946                 return 0;
947         } else if (iocstat == MPI_IOCSTATUS_INVALID_FUNCTION) {
948                 printk(KERN_WARNING MYNAM ": ?Hmmm...  %s says it doesn't support F/W download!?!\n",
949                                 iocp->name);
950                 printk(KERN_WARNING MYNAM ": (time to go bang on somebodies door)\n");
951                 return -EBADRQC;
952         } else if (iocstat == MPI_IOCSTATUS_BUSY) {
953                 printk(KERN_WARNING MYNAM ": Warning!  %s says: IOC_BUSY!\n", iocp->name);
954                 printk(KERN_WARNING MYNAM ": (try again later?)\n");
955                 return -EBUSY;
956         } else {
957                 printk(KERN_WARNING MYNAM "::ioctl_fwdl() ERROR!  %s returned [bad] status = %04xh\n",
958                                     iocp->name, iocstat);
959                 printk(KERN_WARNING MYNAM ": (bad VooDoo)\n");
960                 return -ENOMSG;
961         }
962         return 0;
963
964 fwdl_out:
965         kfree_sgl(sgl, sgl_dma, buflist, iocp);
966         return ret;
967 }
968
969 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
970 /*
971  * SGE Allocation routine
972  *
973  * Inputs:      bytes - number of bytes to be transferred
974  *              sgdir - data direction
975  *              sge_offset - offset (in bytes) from the start of the request
976  *                      frame to the first SGE
977  *              ioc - pointer to the mptadapter
978  * Outputs:     frags - number of scatter gather elements
979  *              blp - point to the buflist pointer
980  *              sglbuf_dma - pointer to the (dma) sgl
981  * Returns:     Null if failes
982  *              pointer to the (virtual) sgl if successful.
983  */
984 static MptSge_t *
985 kbuf_alloc_2_sgl(int bytes, u32 sgdir, int sge_offset, int *frags,
986                  struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc)
987 {
988         MptSge_t        *sglbuf = NULL;         /* pointer to array of SGE */
989                                                 /* and chain buffers */
990         struct buflist  *buflist = NULL;        /* kernel routine */
991         MptSge_t        *sgl;
992         int              numfrags = 0;
993         int              fragcnt = 0;
994         int              alloc_sz = min(bytes,MAX_KMALLOC_SZ);  // avoid kernel warning msg!
995         int              bytes_allocd = 0;
996         int              this_alloc;
997         dma_addr_t       pa;                                    // phys addr
998         int              i, buflist_ent;
999         int              sg_spill = MAX_FRAGS_SPILL1;
1000         int              dir;
1001         /* initialization */
1002         *frags = 0;
1003         *blp = NULL;
1004
1005         /* Allocate and initialize an array of kernel
1006          * structures for the SG elements.
1007          */
1008         i = MAX_SGL_BYTES / 8;
1009         buflist = kmalloc(i, GFP_USER);
1010         if (buflist == NULL)
1011                 return NULL;
1012         memset(buflist, 0, i);
1013         buflist_ent = 0;
1014
1015         /* Allocate a single block of memory to store the sg elements and
1016          * the chain buffers.  The calling routine is responsible for
1017          * copying the data in this array into the correct place in the
1018          * request and chain buffers.
1019          */
1020         sglbuf = pci_alloc_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf_dma);
1021         if (sglbuf == NULL)
1022                 goto free_and_fail;
1023
1024         if (sgdir & 0x04000000)
1025                 dir = PCI_DMA_TODEVICE;
1026         else
1027                 dir = PCI_DMA_FROMDEVICE;
1028
1029         /* At start:
1030          *      sgl = sglbuf = point to beginning of sg buffer
1031          *      buflist_ent = 0 = first kernel structure
1032          *      sg_spill = number of SGE that can be written before the first
1033          *              chain element.
1034          *
1035          */
1036         sgl = sglbuf;
1037         sg_spill = ((ioc->req_sz - sge_offset)/(sizeof(dma_addr_t) + sizeof(u32))) - 1;
1038         while (bytes_allocd < bytes) {
1039                 this_alloc = min(alloc_sz, bytes-bytes_allocd);
1040                 buflist[buflist_ent].len = this_alloc;
1041                 buflist[buflist_ent].kptr = pci_alloc_consistent(ioc->pcidev,
1042                                                                  this_alloc,
1043                                                                  &pa);
1044                 if (buflist[buflist_ent].kptr == NULL) {
1045                         alloc_sz = alloc_sz / 2;
1046                         if (alloc_sz == 0) {
1047                                 printk(KERN_WARNING MYNAM "-SG: No can do - "
1048                                                     "not enough memory!   :-(\n");
1049                                 printk(KERN_WARNING MYNAM "-SG: (freeing %d frags)\n",
1050                                                     numfrags);
1051                                 goto free_and_fail;
1052                         }
1053                         continue;
1054                 } else {
1055                         dma_addr_t dma_addr;
1056
1057                         bytes_allocd += this_alloc;
1058                         sgl->FlagsLength = (0x10000000|MPT_SGE_FLAGS_ADDRESSING|sgdir|this_alloc);
1059                         dma_addr = pci_map_single(ioc->pcidev, buflist[buflist_ent].kptr, this_alloc, dir);
1060                         sgl->Address = dma_addr;
1061
1062                         fragcnt++;
1063                         numfrags++;
1064                         sgl++;
1065                         buflist_ent++;
1066                 }
1067
1068                 if (bytes_allocd >= bytes)
1069                         break;
1070
1071                 /* Need to chain? */
1072                 if (fragcnt == sg_spill) {
1073                         printk(KERN_WARNING MYNAM "-SG: No can do - " "Chain required!   :-(\n");
1074                         printk(KERN_WARNING MYNAM "(freeing %d frags)\n", numfrags);
1075                         goto free_and_fail;
1076                 }
1077
1078                 /* overflow check... */
1079                 if (numfrags*8 > MAX_SGL_BYTES){
1080                         /* GRRRRR... */
1081                         printk(KERN_WARNING MYNAM "-SG: No can do - "
1082                                             "too many SG frags!   :-(\n");
1083                         printk(KERN_WARNING MYNAM "-SG: (freeing %d frags)\n",
1084                                             numfrags);
1085                         goto free_and_fail;
1086                 }
1087         }
1088
1089         /* Last sge fixup: set LE+eol+eob bits */
1090         sgl[-1].FlagsLength |= 0xC1000000;
1091
1092         *frags = numfrags;
1093         *blp = buflist;
1094
1095         dctlprintk((KERN_INFO MYNAM "-SG: kbuf_alloc_2_sgl() - "
1096                            "%d SG frags generated!\n",
1097                            numfrags));
1098
1099         dctlprintk((KERN_INFO MYNAM "-SG: kbuf_alloc_2_sgl() - "
1100                            "last (big) alloc_sz=%d\n",
1101                            alloc_sz));
1102
1103         return sglbuf;
1104
1105 free_and_fail:
1106         if (sglbuf != NULL) {
1107                 int i;
1108
1109                 for (i = 0; i < numfrags; i++) {
1110                         dma_addr_t dma_addr;
1111                         u8 *kptr;
1112                         int len;
1113
1114                         if ((sglbuf[i].FlagsLength >> 24) == 0x30)
1115                                 continue;
1116
1117                         dma_addr = sglbuf[i].Address;
1118                         kptr = buflist[i].kptr;
1119                         len = buflist[i].len;
1120
1121                         pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
1122                 }
1123                 pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf, *sglbuf_dma);
1124         }
1125         kfree(buflist);
1126         return NULL;
1127 }
1128
1129 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1130 /*
1131  * Routine to free the SGL elements.
1132  */
1133 static void
1134 kfree_sgl(MptSge_t *sgl, dma_addr_t sgl_dma, struct buflist *buflist, MPT_ADAPTER *ioc)
1135 {
1136         MptSge_t        *sg = sgl;
1137         struct buflist  *bl = buflist;
1138         u32              nib;
1139         int              dir;
1140         int              n = 0;
1141
1142         if (sg->FlagsLength & 0x04000000)
1143                 dir = PCI_DMA_TODEVICE;
1144         else
1145                 dir = PCI_DMA_FROMDEVICE;
1146
1147         nib = (sg->FlagsLength & 0xF0000000) >> 28;
1148         while (! (nib & 0x4)) { /* eob */
1149                 /* skip ignore/chain. */
1150                 if (nib == 0 || nib == 3) {
1151                         ;
1152                 } else if (sg->Address) {
1153                         dma_addr_t dma_addr;
1154                         void *kptr;
1155                         int len;
1156
1157                         dma_addr = sg->Address;
1158                         kptr = bl->kptr;
1159                         len = bl->len;
1160                         pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
1161                         pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
1162                         n++;
1163                 }
1164                 sg++;
1165                 bl++;
1166                 nib = (le32_to_cpu(sg->FlagsLength) & 0xF0000000) >> 28;
1167         }
1168
1169         /* we're at eob! */
1170         if (sg->Address) {
1171                 dma_addr_t dma_addr;
1172                 void *kptr;
1173                 int len;
1174
1175                 dma_addr = sg->Address;
1176                 kptr = bl->kptr;
1177                 len = bl->len;
1178                 pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
1179                 pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
1180                 n++;
1181         }
1182
1183         pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sgl, sgl_dma);
1184         kfree(buflist);
1185         dctlprintk((KERN_INFO MYNAM "-SG: Free'd 1 SGL buf + %d kbufs!\n", n));
1186 }
1187
1188 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1189 /*
1190  *      mptctl_getiocinfo - Query the host adapter for IOC information.
1191  *      @arg: User space argument
1192  *
1193  * Outputs:     None.
1194  * Return:      0 if successful
1195  *              -EFAULT if data unavailable
1196  *              -ENODEV  if no such device/adapter
1197  */
1198 static int
1199 mptctl_getiocinfo (unsigned long arg, unsigned int data_size)
1200 {
1201         struct mpt_ioctl_iocinfo *uarg = (struct mpt_ioctl_iocinfo *) arg;
1202         struct mpt_ioctl_iocinfo *karg;
1203         MPT_ADAPTER             *ioc;
1204         struct pci_dev          *pdev;
1205         struct Scsi_Host        *sh;
1206         MPT_SCSI_HOST           *hd;
1207         int                     iocnum;
1208         int                     numDevices = 0;
1209         unsigned int            max_id;
1210         int                     ii;
1211         int                     port;
1212         int                     cim_rev;
1213         u8                      revision;
1214
1215         dctlprintk((": mptctl_getiocinfo called.\n"));
1216         /* Add of PCI INFO results in unaligned access for
1217          * IA64 and Sparc. Reset long to int. Return no PCI
1218          * data for obsolete format.
1219          */
1220         if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev0))
1221                 cim_rev = 0;
1222         else if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev1))
1223                 cim_rev = 1;
1224         else if (data_size == sizeof(struct mpt_ioctl_iocinfo))
1225                 cim_rev = 2;
1226         else if (data_size == (sizeof(struct mpt_ioctl_iocinfo_rev0)+12))
1227                 cim_rev = 0;    /* obsolete */
1228         else
1229                 return -EFAULT;
1230         
1231         karg = kmalloc(data_size, GFP_KERNEL);
1232         if (karg == NULL) {
1233                 printk(KERN_ERR "%s::mpt_ioctl_iocinfo() @%d - no memory available!\n",
1234                                 __FILE__, __LINE__);
1235                 return -ENOMEM;
1236         }
1237                 
1238         if (copy_from_user(karg, uarg, data_size)) {
1239                 printk(KERN_ERR "%s@%d::mptctl_getiocinfo - "
1240                         "Unable to read in mpt_ioctl_iocinfo struct @ %p\n",
1241                                 __FILE__, __LINE__, (void*)uarg);
1242                 kfree(karg);
1243                 return -EFAULT;
1244         }
1245
1246         if (((iocnum = mpt_verify_adapter(karg->hdr.iocnum, &ioc)) < 0) ||
1247             (ioc == NULL)) {
1248                 dctlprintk((KERN_ERR "%s::mptctl_getiocinfo() @%d - ioc%d not found!\n",
1249                                 __FILE__, __LINE__, iocnum));
1250                 kfree(karg);
1251                 return -ENODEV;
1252         }
1253
1254         /* Verify the data transfer size is correct.
1255          * Ignore the port setting.
1256          */
1257         if (karg->hdr.maxDataSize != data_size) {
1258                 printk(KERN_ERR "%s@%d::mptctl_getiocinfo - "
1259                         "Structure size mismatch. Command not completed.\n",
1260                                 __FILE__, __LINE__);
1261                 kfree(karg);
1262                 return -EFAULT;
1263         }
1264
1265         /* Fill in the data and return the structure to the calling
1266          * program
1267          */
1268         if ((int)ioc->chip_type <= (int) FC929)
1269                 karg->adapterType = MPT_IOCTL_INTERFACE_FC;
1270         else
1271                 karg->adapterType = MPT_IOCTL_INTERFACE_SCSI;
1272
1273         port = karg->hdr.port;
1274
1275         karg->port = port;
1276         pdev = (struct pci_dev *) ioc->pcidev;
1277
1278         karg->pciId = pdev->device;
1279         pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
1280         karg->hwRev = revision;
1281 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1282         karg->subSystemDevice = pdev->subsystem_device;
1283         karg->subSystemVendor = pdev->subsystem_vendor;
1284 #endif
1285
1286         if (cim_rev == 1) {
1287                 /* Get the PCI bus, device, and function numbers for the IOC
1288                  */
1289                 karg->pciInfo.u.bits.busNumber = pdev->bus->number;
1290                 karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
1291                 karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
1292         } else if (cim_rev == 2) {
1293                 /* Get the PCI bus, device, function and segment ID numbers 
1294                    for the IOC */
1295                 karg->pciInfo.u.bits.busNumber = pdev->bus->number;
1296                 karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
1297                 karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
1298                 karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
1299                 karg->pciInfo.segmentID = pci_domain_nr(pdev->bus);
1300         }
1301
1302         /* Get number of devices
1303          */
1304         if ((sh = ioc->sh) != NULL) {
1305                  /* sh->max_id = maximum target ID + 1
1306                  */
1307                 max_id = sh->max_id - 1;
1308                 hd = (MPT_SCSI_HOST *) sh->hostdata;
1309
1310                 /* Check all of the target structures and
1311                  * keep a counter.
1312                  */
1313                 if (hd && hd->Targets) {
1314                         for (ii = 0; ii <= max_id; ii++) {
1315                                 if (hd->Targets[ii])
1316                                         numDevices++;
1317                         }
1318                 }
1319         }
1320         karg->numDevices = numDevices;
1321
1322         /* Set the BIOS and FW Version
1323          */
1324         karg->FWVersion = ioc->facts.FWVersion.Word;
1325         karg->BIOSVersion = ioc->biosVersion;
1326
1327         /* Set the Version Strings.
1328          */
1329         strncpy (karg->driverVersion, MPT_LINUX_PACKAGE_NAME, MPT_IOCTL_VERSION_LENGTH);
1330         karg->driverVersion[MPT_IOCTL_VERSION_LENGTH-1]='\0';
1331
1332         karg->busChangeEvent = 0;
1333         karg->hostId = ioc->pfacts[port].PortSCSIID;
1334         karg->rsvd[0] = karg->rsvd[1] = 0;
1335
1336         /* Copy the data from kernel memory to user memory
1337          */
1338         if (copy_to_user((char *)arg, karg, data_size)) {
1339                 printk(KERN_ERR "%s@%d::mptctl_getiocinfo - "
1340                         "Unable to write out mpt_ioctl_iocinfo struct @ %p\n",
1341                                 __FILE__, __LINE__, (void*)uarg);
1342                 kfree(karg);
1343                 return -EFAULT;
1344         }
1345
1346         kfree(karg);
1347         return 0;
1348 }
1349
1350 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1351 /*
1352  *      mptctl_gettargetinfo - Query the host adapter for target information.
1353  *      @arg: User space argument
1354  *
1355  * Outputs:     None.
1356  * Return:      0 if successful
1357  *              -EFAULT if data unavailable
1358  *              -ENODEV  if no such device/adapter
1359  */
1360 static int
1361 mptctl_gettargetinfo (unsigned long arg)
1362 {
1363         struct mpt_ioctl_targetinfo *uarg = (struct mpt_ioctl_targetinfo *) arg;
1364         struct mpt_ioctl_targetinfo karg;
1365         MPT_ADAPTER             *ioc;
1366         struct Scsi_Host        *sh;
1367         MPT_SCSI_HOST           *hd;
1368         VirtDevice              *vdev;
1369         char                    *pmem;
1370         int                     *pdata;
1371         IOCPage2_t              *pIoc2;
1372         int                     iocnum;
1373         int                     numDevices = 0;
1374         unsigned int            max_id;
1375         int                     id, jj, indexed_lun, lun_index;
1376         u32                     lun;
1377         int                     maxWordsLeft;
1378         int                     numBytes;
1379         u8                      port, devType, bus_id;
1380
1381         dctlprintk(("mptctl_gettargetinfo called.\n"));
1382         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_targetinfo))) {
1383                 printk(KERN_ERR "%s@%d::mptctl_gettargetinfo - "
1384                         "Unable to read in mpt_ioctl_targetinfo struct @ %p\n",
1385                                 __FILE__, __LINE__, (void*)uarg);
1386                 return -EFAULT;
1387         }
1388
1389         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1390             (ioc == NULL)) {
1391                 dctlprintk((KERN_ERR "%s::mptctl_gettargetinfo() @%d - ioc%d not found!\n",
1392                                 __FILE__, __LINE__, iocnum));
1393                 return -ENODEV;
1394         }
1395
1396         /* Get the port number and set the maximum number of bytes
1397          * in the returned structure.
1398          * Ignore the port setting.
1399          */
1400         numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
1401         maxWordsLeft = numBytes/sizeof(int);
1402         port = karg.hdr.port;
1403
1404         if (maxWordsLeft <= 0) {
1405                 printk(KERN_ERR "%s::mptctl_gettargetinfo() @%d - no memory available!\n",
1406                                 __FILE__, __LINE__);
1407                 return -ENOMEM;
1408         }
1409
1410         /* Fill in the data and return the structure to the calling
1411          * program
1412          */
1413
1414         /* struct mpt_ioctl_targetinfo does not contain sufficient space
1415          * for the target structures so when the IOCTL is called, there is
1416          * not sufficient stack space for the structure. Allocate memory,
1417          * populate the memory, copy back to the user, then free memory.
1418          * targetInfo format:
1419          * bits 31-24: reserved
1420          *      23-16: LUN
1421          *      15- 8: Bus Number
1422          *       7- 0: Target ID
1423          */
1424         pmem = kmalloc(numBytes, GFP_KERNEL);
1425         if (pmem == NULL) {
1426                 printk(KERN_ERR "%s::mptctl_gettargetinfo() @%d - no memory available!\n",
1427                                 __FILE__, __LINE__);
1428                 return -ENOMEM;
1429         }
1430         memset(pmem, 0, numBytes);
1431         pdata =  (int *) pmem;
1432
1433         /* Get number of devices
1434          */
1435         if ((sh = ioc->sh) != NULL) {
1436
1437                 max_id = sh->max_id - 1;
1438                 hd = (MPT_SCSI_HOST *) sh->hostdata;
1439
1440                 /* Check all of the target structures.
1441                  * Save the Id and increment the counter,
1442                  * if ptr non-null.
1443                  * sh->max_id = maximum target ID + 1
1444                  */
1445                 if (hd && hd->Targets) {
1446                         mpt_findImVolumes(ioc);
1447                         pIoc2 = ioc->spi_data.pIocPg2;
1448                         for ( id = 0; id <= max_id; id++ ) {
1449                                 if ( pIoc2 && pIoc2->NumActiveVolumes &&
1450                                         ( id == pIoc2->RaidVolume[0].VolumeID ) ) {
1451                                         if (maxWordsLeft <= 0) {
1452                                                 printk(KERN_ERR "mptctl_gettargetinfo - "
1453                         "buffer is full but volume is available on ioc %d\n, numDevices=%d", iocnum, numDevices);
1454                                                 goto data_space_full;
1455                                         }
1456                                         if ( ( pIoc2->RaidVolume[0].Flags & MPI_IOCPAGE2_FLAG_VOLUME_INACTIVE ) == 0 )
1457                                                 devType = 0x80;
1458                                         else
1459                                                 devType = 0xC0;
1460                                         bus_id = pIoc2->RaidVolume[0].VolumeBus;
1461                                         numDevices++;
1462                                         *pdata = ( (devType << 24) | (bus_id << 8) | id );
1463                                         dctlprintk((KERN_ERR "mptctl_gettargetinfo - "
1464                 "volume ioc=%d target=%x numDevices=%d pdata=%p\n", iocnum, *pdata, numDevices, pdata));
1465                                         pdata++;
1466                                         --maxWordsLeft;
1467                                 } else {
1468                                         vdev = hd->Targets[id];
1469                                         if (vdev) {
1470                                                 for (jj = 0; jj <= MPT_LAST_LUN; jj++) {
1471                                                         lun_index = (jj >> 5);
1472                                                         indexed_lun = (jj % 32);
1473                                                         lun = (1 << indexed_lun);
1474                                                         if (vdev->luns[lun_index] & lun) {
1475                                                                 if (maxWordsLeft <= 0) {
1476                                                                         printk(KERN_ERR
1477                                                                         "mptctl_gettargetinfo - "
1478                                                                         "buffer is full but more targets are available on ioc %d numDevices=%d\n",
1479                                                                         iocnum, numDevices);
1480                                                                         goto data_space_full;
1481                                                                 }
1482                                                                 bus_id = vdev->bus_id;
1483                                                                 numDevices++;
1484                                                                 *pdata = ( (jj << 16) | (bus_id << 8) | id );
1485                                                                 dctlprintk((KERN_ERR
1486                                                                  "mptctl_gettargetinfo - "
1487                                                                  "target ioc=%d target=%x numDevices=%d pdata=%p\n",
1488                                                                  iocnum, *pdata, numDevices, pdata));
1489                                                                 pdata++;
1490                                                                 --maxWordsLeft;
1491                                                         }
1492                                                 }
1493                                         }
1494                                 }
1495                         }
1496                 }
1497         }
1498 data_space_full:
1499         karg.numDevices = numDevices;
1500
1501         /* Copy part of the data from kernel memory to user memory
1502          */
1503         if (copy_to_user((char *)arg, &karg,
1504                                 sizeof(struct mpt_ioctl_targetinfo))) {
1505                 printk(KERN_ERR "%s@%d::mptctl_gettargetinfo - "
1506                         "Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
1507                                 __FILE__, __LINE__, (void*)uarg);
1508                 kfree(pmem);
1509                 return -EFAULT;
1510         }
1511
1512         /* Copy the remaining data from kernel memory to user memory
1513          */
1514         if (copy_to_user((char *) uarg->targetInfo, pmem, numBytes)) {
1515                 printk(KERN_ERR "%s@%d::mptctl_gettargetinfo - "
1516                         "Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
1517                                 __FILE__, __LINE__, (void*)pdata);
1518                 kfree(pmem);
1519                 return -EFAULT;
1520         }
1521
1522         kfree(pmem);
1523
1524         return 0;
1525 }
1526
1527 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1528 /* MPT IOCTL Test function.
1529  *
1530  * Outputs:     None.
1531  * Return:      0 if successful
1532  *              -EFAULT if data unavailable
1533  *              -ENODEV  if no such device/adapter
1534  */
1535 static int
1536 mptctl_readtest (unsigned long arg)
1537 {
1538         struct mpt_ioctl_test   *uarg = (struct mpt_ioctl_test *) arg;
1539         struct mpt_ioctl_test    karg;
1540         MPT_ADAPTER *ioc;
1541         int iocnum;
1542
1543         dctlprintk(("mptctl_readtest called.\n"));
1544         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {
1545                 printk(KERN_ERR "%s@%d::mptctl_readtest - "
1546                         "Unable to read in mpt_ioctl_test struct @ %p\n",
1547                                 __FILE__, __LINE__, (void*)uarg);
1548                 return -EFAULT;
1549         }
1550
1551         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1552             (ioc == NULL)) {
1553                 dctlprintk((KERN_ERR "%s::mptctl_readtest() @%d - ioc%d not found!\n",
1554                                 __FILE__, __LINE__, iocnum));
1555                 return -ENODEV;
1556         }
1557
1558         /* Fill in the data and return the structure to the calling
1559          * program
1560          */
1561
1562 #ifdef MFCNT
1563         karg.chip_type = ioc->mfcnt;
1564 #else
1565         karg.chip_type = ioc->chip_type;
1566 #endif
1567         strncpy (karg.name, ioc->name, MPT_MAX_NAME);
1568         karg.name[MPT_MAX_NAME-1]='\0';
1569         strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);
1570         karg.product[MPT_PRODUCT_LENGTH-1]='\0';
1571
1572         /* Copy the data from kernel memory to user memory
1573          */
1574         if (copy_to_user((char *)arg, &karg, sizeof(struct mpt_ioctl_test))) {
1575                 printk(KERN_ERR "%s@%d::mptctl_readtest - "
1576                         "Unable to write out mpt_ioctl_test struct @ %p\n",
1577                                 __FILE__, __LINE__, (void*)uarg);
1578                 return -EFAULT;
1579         }
1580
1581         return 0;
1582 }
1583
1584 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1585 /*
1586  *      mptctl_eventquery - Query the host adapter for the event types
1587  *      that are being logged.
1588  *      @arg: User space argument
1589  *
1590  * Outputs:     None.
1591  * Return:      0 if successful
1592  *              -EFAULT if data unavailable
1593  *              -ENODEV  if no such device/adapter
1594  */
1595 static int
1596 mptctl_eventquery (unsigned long arg)
1597 {
1598         struct mpt_ioctl_eventquery     *uarg = (struct mpt_ioctl_eventquery *) arg;
1599         struct mpt_ioctl_eventquery      karg;
1600         MPT_ADAPTER *ioc;
1601         int iocnum;
1602
1603         dctlprintk(("mptctl_eventquery called.\n"));
1604         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {
1605                 printk(KERN_ERR "%s@%d::mptctl_eventquery - "
1606                         "Unable to read in mpt_ioctl_eventquery struct @ %p\n",
1607                                 __FILE__, __LINE__, (void*)uarg);
1608                 return -EFAULT;
1609         }
1610
1611         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1612             (ioc == NULL)) {
1613                 dctlprintk((KERN_ERR "%s::mptctl_eventquery() @%d - ioc%d not found!\n",
1614                                 __FILE__, __LINE__, iocnum));
1615                 return -ENODEV;
1616         }
1617
1618         karg.eventEntries = ioc->eventLogSize;
1619         karg.eventTypes = ioc->eventTypes;
1620
1621         /* Copy the data from kernel memory to user memory
1622          */
1623         if (copy_to_user((char *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {
1624                 printk(KERN_ERR "%s@%d::mptctl_eventquery - "
1625                         "Unable to write out mpt_ioctl_eventquery struct @ %p\n",
1626                                 __FILE__, __LINE__, (void*)uarg);
1627                 return -EFAULT;
1628         }
1629         return 0;
1630 }
1631
1632 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1633 static int
1634 mptctl_eventenable (unsigned long arg)
1635 {
1636         struct mpt_ioctl_eventenable    *uarg = (struct mpt_ioctl_eventenable *) arg;
1637         struct mpt_ioctl_eventenable     karg;
1638         MPT_ADAPTER *ioc;
1639         int iocnum;
1640
1641         dctlprintk(("mptctl_eventenable called.\n"));
1642         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) {
1643                 printk(KERN_ERR "%s@%d::mptctl_eventenable - "
1644                         "Unable to read in mpt_ioctl_eventenable struct @ %p\n",
1645                                 __FILE__, __LINE__, (void*)uarg);
1646                 return -EFAULT;
1647         }
1648
1649         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1650             (ioc == NULL)) {
1651                 dctlprintk((KERN_ERR "%s::mptctl_eventenable() @%d - ioc%d not found!\n",
1652                                 __FILE__, __LINE__, iocnum));
1653                 return -ENODEV;
1654         }
1655
1656         if (ioc->events == NULL) {
1657                 /* Have not yet allocated memory - do so now.
1658                  */
1659                 int sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS);
1660                 ioc->events = kmalloc(sz, GFP_KERNEL);
1661                 if (ioc->events == NULL) {
1662                         printk(KERN_ERR MYNAM ": ERROR - Insufficient memory to add adapter!\n");
1663                         return -ENOMEM;
1664                 }
1665                 memset(ioc->events, 0, sz);
1666                 ioc->alloc_total += sz;
1667
1668                 ioc->eventLogSize = MPTCTL_EVENT_LOG_SIZE;
1669                 ioc->eventContext = 0;
1670         }
1671
1672         /* Update the IOC event logging flag.
1673          */
1674         ioc->eventTypes = karg.eventTypes;
1675
1676         return 0;
1677 }
1678
1679 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1680 static int
1681 mptctl_eventreport (unsigned long arg)
1682 {
1683         struct mpt_ioctl_eventreport    *uarg = (struct mpt_ioctl_eventreport *) arg;
1684         struct mpt_ioctl_eventreport     karg;
1685         MPT_ADAPTER              *ioc;
1686         int                      iocnum;
1687         int                      numBytes, maxEvents, max;
1688
1689         dctlprintk(("mptctl_eventreport called.\n"));
1690         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {
1691                 printk(KERN_ERR "%s@%d::mptctl_eventreport - "
1692                         "Unable to read in mpt_ioctl_eventreport struct @ %p\n",
1693                                 __FILE__, __LINE__, (void*)uarg);
1694                 return -EFAULT;
1695         }
1696
1697         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1698             (ioc == NULL)) {
1699                 dctlprintk((KERN_ERR "%s::mptctl_eventreport() @%d - ioc%d not found!\n",
1700                                 __FILE__, __LINE__, iocnum));
1701                 return -ENODEV;
1702         }
1703
1704         numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
1705         maxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);
1706
1707
1708         max = ioc->eventLogSize < maxEvents ? ioc->eventLogSize : maxEvents;
1709
1710         /* If fewer than 1 event is requested, there must have
1711          * been some type of error.
1712          */
1713         if ((max < 1) || !ioc->events)
1714                 return -ENODATA;
1715
1716         /* Copy the data from kernel memory to user memory
1717          */
1718         numBytes = max * sizeof(MPT_IOCTL_EVENTS);
1719         if (copy_to_user((char *) uarg->eventData, ioc->events, numBytes)) {
1720                 printk(KERN_ERR "%s@%d::mptctl_eventreport - "
1721                         "Unable to write out mpt_ioctl_eventreport struct @ %p\n",
1722                                 __FILE__, __LINE__, (void*)ioc->events);
1723                 return -EFAULT;
1724         }
1725
1726         return 0;
1727 }
1728
1729 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1730 static int
1731 mptctl_replace_fw (unsigned long arg)
1732 {
1733         struct mpt_ioctl_replace_fw     *uarg = (struct mpt_ioctl_replace_fw *) arg;
1734         struct mpt_ioctl_replace_fw      karg;
1735         MPT_ADAPTER              *ioc;
1736         fw_image_t               **fwmem = NULL;
1737         int                      iocnum;
1738         int                      newFwSize;
1739         int                      num_frags, alloc_sz;
1740         int                      ii;
1741         u32                      offset;
1742
1743         dctlprintk(("mptctl_replace_fw called.\n"));
1744         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) {
1745                 printk(KERN_ERR "%s@%d::mptctl_replace_fw - "
1746                         "Unable to read in mpt_ioctl_replace_fw struct @ %p\n",
1747                                 __FILE__, __LINE__, (void*)uarg);
1748                 return -EFAULT;
1749         }
1750
1751         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1752             (ioc == NULL)) {
1753                 dctlprintk((KERN_ERR "%s::mptctl_replace_fw() @%d - ioc%d not found!\n",
1754                                 __FILE__, __LINE__, iocnum));
1755                 return -ENODEV;
1756         }
1757
1758         /* If not caching FW, return 0
1759          */
1760         if ((ioc->cached_fw == NULL) && (ioc->alt_ioc) && (ioc->alt_ioc->cached_fw == NULL))
1761                 return 0;
1762
1763         /* Allocate memory for the new FW image
1764          */
1765         newFwSize = karg.newImageSize;
1766         fwmem = mpt_alloc_fw_memory(ioc, newFwSize, &num_frags, &alloc_sz);
1767         if (fwmem == NULL)
1768                 return -ENOMEM;
1769
1770         offset = 0;
1771         for (ii = 0; ii < num_frags; ii++) {
1772                 /* Copy the data from user memory to kernel space
1773                  */
1774                 if (copy_from_user(fwmem[ii]->fw, uarg->newImage + offset, fwmem[ii]->size)) {
1775                         printk(KERN_ERR "%s@%d::mptctl_replace_fw - "
1776                                 "Unable to read in mpt_ioctl_replace_fw image @ %p\n",
1777                                         __FILE__, __LINE__, (void*)uarg);
1778
1779                         mpt_free_fw_memory(ioc, fwmem);
1780                         return -EFAULT;
1781                 }
1782                 offset += fwmem[ii]->size;
1783         }
1784
1785
1786         /* Free the old FW image
1787          */
1788         if (ioc->cached_fw) {
1789                 mpt_free_fw_memory(ioc, 0);
1790                 ioc->cached_fw = fwmem;
1791                 ioc->alloc_total += alloc_sz;
1792         } else if ((ioc->alt_ioc) && (ioc->alt_ioc->cached_fw)) {
1793                 mpt_free_fw_memory(ioc->alt_ioc, 0);
1794                 ioc->alt_ioc->cached_fw = fwmem;
1795                 ioc->alt_ioc->alloc_total += alloc_sz;
1796         }
1797
1798         /* Update IOCFactsReply
1799          */
1800         ioc->facts.FWImageSize = newFwSize;
1801         if (ioc->alt_ioc)
1802                 ioc->alt_ioc->facts.FWImageSize = newFwSize;
1803
1804         return 0;
1805 }
1806
1807 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1808 /* MPT IOCTL MPTCOMMAND function.
1809  * Cast the arg into the mpt_ioctl_mpt_command structure.
1810  *
1811  * Outputs:     None.
1812  * Return:      0 if successful
1813  *              -EBUSY  if previous command timout and IOC reset is not complete.
1814  *              -EFAULT if data unavailable
1815  *              -ENODEV if no such device/adapter
1816  *              -ETIME  if timer expires
1817  *              -ENOMEM if memory allocation error
1818  */
1819 static int
1820 mptctl_mpt_command (unsigned long arg)
1821 {
1822         struct mpt_ioctl_command *uarg = (struct mpt_ioctl_command *) arg;
1823         struct mpt_ioctl_command  karg;
1824         MPT_ADAPTER     *ioc;
1825         int             iocnum;
1826         int             rc;
1827
1828         dctlprintk(("mptctl_command called.\n"));
1829
1830         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {
1831                 printk(KERN_ERR "%s@%d::mptctl_mpt_command - "
1832                         "Unable to read in mpt_ioctl_command struct @ %p\n",
1833                                 __FILE__, __LINE__, (void*)uarg);
1834                 return -EFAULT;
1835         }
1836
1837         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1838             (ioc == NULL)) {
1839                 dctlprintk((KERN_ERR "%s::mptctl_mpt_command() @%d - ioc%d not found!\n",
1840                                 __FILE__, __LINE__, iocnum));
1841                 return -ENODEV;
1842         }
1843
1844         rc = mptctl_do_mpt_command (karg, (char *) &uarg->MF, 0);
1845
1846         return rc;
1847 }
1848
1849 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1850 /* Worker routine for the IOCTL MPTCOMMAND and MPTCOMMAND32 (sparc) commands.
1851  *
1852  * Outputs:     None.
1853  * Return:      0 if successful
1854  *              -EBUSY  if previous command timout and IOC reset is not complete.
1855  *              -EFAULT if data unavailable
1856  *              -ENODEV if no such device/adapter
1857  *              -ETIME  if timer expires
1858  *              -ENOMEM if memory allocation error
1859  *              -EPERM if SCSI I/O and target is untagged
1860  */
1861 static int
1862 mptctl_do_mpt_command (struct mpt_ioctl_command karg, char *mfPtr, int local)
1863 {
1864         MPT_ADAPTER     *ioc;
1865         MPT_FRAME_HDR   *mf = NULL;
1866         MPIHeader_t     *hdr;
1867         char            *psge;
1868         struct buflist  bufIn;  /* data In buffer */
1869         struct buflist  bufOut; /* data Out buffer */
1870         dma_addr_t      dma_addr_in;
1871         dma_addr_t      dma_addr_out;
1872         int             dir;    /* PCI data direction */
1873         int             sgSize = 0;     /* Num SG elements */
1874         int             iocnum, flagsLength;
1875         int             sz, rc = 0;
1876         int             msgContext;
1877         int             tm_flags_set = 0;
1878         u16             req_idx;
1879
1880         dctlprintk(("mptctl_do_mpt_command called.\n"));
1881         bufIn.kptr = bufOut.kptr = NULL;
1882
1883         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1884             (ioc == NULL)) {
1885                 dctlprintk((KERN_ERR "%s::mptctl_do_mpt_command() @%d - ioc%d not found!\n",
1886                                 __FILE__, __LINE__, iocnum));
1887                 return -ENODEV;
1888         }
1889         if (!ioc->ioctl) {
1890                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
1891                         "No memory available during driver init.\n",
1892                                 __FILE__, __LINE__);
1893                 return -ENOMEM;
1894         } else if (ioc->ioctl->status & MPT_IOCTL_STATUS_DID_IOCRESET) {
1895                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
1896                         "Busy with IOC Reset \n", __FILE__, __LINE__);
1897                 return -EBUSY;
1898         }
1899
1900         /* Verify that the final request frame will not be too large.
1901          */
1902         sz = karg.dataSgeOffset * 4;
1903         if (karg.dataInSize > 0)
1904                 sz += sizeof(dma_addr_t) + sizeof(u32);
1905         if (karg.dataOutSize > 0)
1906                 sz += sizeof(dma_addr_t) + sizeof(u32);
1907
1908         if (sz > ioc->req_sz) {
1909                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
1910                         "Request frame too large (%d) maximum (%d)\n",
1911                                 __FILE__, __LINE__, sz, ioc->req_sz);
1912                 return -EFAULT;
1913         }
1914
1915         /* Get a free request frame and save the message context.
1916          */
1917         if ((mf = mpt_get_msg_frame(mptctl_id, ioc->id)) == NULL)
1918                 return -EAGAIN;
1919
1920         hdr = (MPIHeader_t *) mf;
1921         msgContext = le32_to_cpu(hdr->MsgContext);
1922         req_idx = le16_to_cpu(mf->u.frame.hwhdr.msgctxu.fld.req_idx);
1923
1924         /* Copy the request frame
1925          * Reset the saved message context.
1926          */
1927         if (local) {
1928                 /* Request frame in kernel space
1929                  */
1930                 memcpy((char *)mf, (char *) mfPtr, karg.dataSgeOffset * 4);
1931         } else {
1932                 /* Request frame in user space
1933                  */
1934                 if (copy_from_user((char *)mf, (char *) mfPtr,
1935                                         karg.dataSgeOffset * 4)){
1936                         printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
1937                                 "Unable to read MF from mpt_ioctl_command struct @ %p\n",
1938                                 __FILE__, __LINE__, (void*)mfPtr);
1939                         rc = -EFAULT;
1940                         goto done_free_mem;
1941                 }
1942         }
1943         hdr->MsgContext = cpu_to_le32(msgContext);
1944
1945
1946         /* Verify that this request is allowed.
1947          */
1948         switch (hdr->Function) {
1949         case MPI_FUNCTION_IOC_FACTS:
1950         case MPI_FUNCTION_PORT_FACTS:
1951                 karg.dataOutSize  = karg.dataInSize = 0;
1952                 break;
1953
1954         case MPI_FUNCTION_CONFIG:
1955         case MPI_FUNCTION_FC_COMMON_TRANSPORT_SEND:
1956         case MPI_FUNCTION_FC_EX_LINK_SRVC_SEND:
1957         case MPI_FUNCTION_FW_UPLOAD:
1958         case MPI_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
1959         case MPI_FUNCTION_FW_DOWNLOAD:
1960         case MPI_FUNCTION_FC_PRIMITIVE_SEND:
1961                 break;
1962
1963         case MPI_FUNCTION_SCSI_IO_REQUEST:
1964                 if (ioc->sh) {
1965                         SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf;
1966                         VirtDevice      *pTarget = NULL;
1967                         MPT_SCSI_HOST   *hd = NULL;
1968                         int qtag = MPI_SCSIIO_CONTROL_UNTAGGED;
1969                         int scsidir = 0;
1970                         int target = (int) pScsiReq->TargetID;
1971                         int dataSize;
1972
1973                         if ((target < 0) || (target >= ioc->sh->max_id)) {
1974                                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
1975                                         "Target ID out of bounds. \n",
1976                                         __FILE__, __LINE__);
1977                                 rc = -ENODEV;
1978                                 goto done_free_mem;
1979                         }
1980
1981                         pScsiReq->MsgFlags = mpt_msg_flags();
1982
1983                         /* verify that app has not requested
1984                          *      more sense data than driver
1985                          *      can provide, if so, reset this parameter
1986                          * set the sense buffer pointer low address
1987                          * update the control field to specify Q type
1988                          */
1989                         if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE)
1990                                 pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE;
1991                         else
1992                                 pScsiReq->SenseBufferLength = karg.maxSenseBytes;
1993
1994                         pScsiReq->SenseBufferLowAddr =
1995                                 cpu_to_le32(ioc->sense_buf_low_dma
1996                                    + (req_idx * MPT_SENSE_BUFFER_ALLOC));
1997
1998                         if ((hd = (MPT_SCSI_HOST *) ioc->sh->hostdata)) {
1999                                 if (hd->Targets)
2000                                         pTarget = hd->Targets[target];
2001                         }
2002
2003                         if (pTarget &&(pTarget->tflags & MPT_TARGET_FLAGS_Q_YES))
2004                                 qtag = MPI_SCSIIO_CONTROL_SIMPLEQ;
2005
2006                         /* Have the IOCTL driver set the direction based
2007                          * on the dataOutSize (ordering issue with Sparc).
2008                          */
2009                         if (karg.dataOutSize > 0) {
2010                                 scsidir = MPI_SCSIIO_CONTROL_WRITE;
2011                                 dataSize = karg.dataOutSize;
2012                         } else {
2013                                 scsidir = MPI_SCSIIO_CONTROL_READ;
2014                                 dataSize = karg.dataInSize;
2015                         }
2016
2017                         pScsiReq->Control = cpu_to_le32(scsidir | qtag);
2018                         pScsiReq->DataLength = cpu_to_le32(dataSize);
2019
2020                         ioc->ioctl->reset = MPTCTL_RESET_OK;
2021                         ioc->ioctl->target = target;
2022
2023                 } else {
2024                         printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2025                                 "SCSI driver is not loaded. \n",
2026                                         __FILE__, __LINE__);
2027                         rc = -EFAULT;
2028                         goto done_free_mem;
2029                 }
2030                 break;
2031
2032         case MPI_FUNCTION_RAID_ACTION:
2033                 /* Just add a SGE
2034                  */
2035                 break;
2036
2037         case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
2038                 if (ioc->sh) {
2039                         SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf;
2040                         int qtag = MPI_SCSIIO_CONTROL_SIMPLEQ;
2041                         int scsidir = MPI_SCSIIO_CONTROL_READ;
2042                         int dataSize;
2043
2044                         pScsiReq->MsgFlags = mpt_msg_flags();
2045
2046                         /* verify that app has not requested
2047                          *      more sense data than driver
2048                          *      can provide, if so, reset this parameter
2049                          * set the sense buffer pointer low address
2050                          * update the control field to specify Q type
2051                          */
2052                         if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE)
2053                                 pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE;
2054                         else
2055                                 pScsiReq->SenseBufferLength = karg.maxSenseBytes;
2056
2057                         pScsiReq->SenseBufferLowAddr =
2058                                 cpu_to_le32(ioc->sense_buf_low_dma
2059                                    + (req_idx * MPT_SENSE_BUFFER_ALLOC));
2060
2061                         /* All commands to physical devices are tagged
2062                          */
2063
2064                         /* Have the IOCTL driver set the direction based
2065                          * on the dataOutSize (ordering issue with Sparc).
2066                          */
2067                         if (karg.dataOutSize > 0) {
2068                                 scsidir = MPI_SCSIIO_CONTROL_WRITE;
2069                                 dataSize = karg.dataOutSize;
2070                         } else {
2071                                 scsidir = MPI_SCSIIO_CONTROL_READ;
2072                                 dataSize = karg.dataInSize;
2073                         }
2074
2075                         pScsiReq->Control = cpu_to_le32(scsidir | qtag);
2076                         pScsiReq->DataLength = cpu_to_le32(dataSize);
2077
2078                         ioc->ioctl->reset = MPTCTL_RESET_OK;
2079                         ioc->ioctl->target = pScsiReq->TargetID;
2080                 } else {
2081                         printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2082                                 "SCSI driver is not loaded. \n",
2083                                         __FILE__, __LINE__);
2084                         rc = -EFAULT;
2085                         goto done_free_mem;
2086                 }
2087                 break;
2088
2089         case MPI_FUNCTION_SCSI_TASK_MGMT:
2090                 {
2091                         MPT_SCSI_HOST *hd = NULL;
2092                         if ((ioc->sh == NULL) || ((hd = (MPT_SCSI_HOST *)ioc->sh->hostdata) == NULL)) {
2093                                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2094                                         "SCSI driver not loaded or SCSI host not found. \n",
2095                                         __FILE__, __LINE__);
2096                                 rc = -EFAULT;
2097                                 goto done_free_mem;
2098                         } else if (mptctl_set_tm_flags(hd) != 0) {
2099                                 rc = -EPERM;
2100                                 goto done_free_mem;
2101                         }
2102                         tm_flags_set = 1;
2103                 }
2104                 break;
2105
2106         case MPI_FUNCTION_IOC_INIT:
2107                 {
2108                         IOCInit_t       *pInit = (IOCInit_t *) mf;
2109                         u32             high_addr, sense_high;
2110
2111                         /* Verify that all entries in the IOC INIT match
2112                          * existing setup (and in LE format).
2113                          */
2114                         if (sizeof(dma_addr_t) == sizeof(u64)) {
2115                                 high_addr = cpu_to_le32((u32)((u64)ioc->req_frames_dma >> 32));
2116                                 sense_high= cpu_to_le32((u32)((u64)ioc->sense_buf_pool_dma >> 32));
2117                         } else {
2118                                 high_addr = 0;
2119                                 sense_high= 0;
2120                         }
2121
2122                         if ((pInit->Flags != 0) || (pInit->MaxDevices != ioc->facts.MaxDevices) ||
2123                                 (pInit->MaxBuses != ioc->facts.MaxBuses) ||
2124                                 (pInit->ReplyFrameSize != cpu_to_le16(ioc->reply_sz)) ||
2125                                 (pInit->HostMfaHighAddr != high_addr) ||
2126                                 (pInit->SenseBufferHighAddr != sense_high)) {
2127                                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2128                                         "IOC_INIT issued with 1 or more incorrect parameters. Rejected.\n",
2129                                         __FILE__, __LINE__);
2130                                 rc = -EFAULT;
2131                                 goto done_free_mem;
2132                         }
2133                 }
2134                 break;
2135         default:
2136                 /*
2137                  * MPI_FUNCTION_PORT_ENABLE
2138                  * MPI_FUNCTION_TARGET_CMD_BUFFER_POST
2139                  * MPI_FUNCTION_TARGET_ASSIST
2140                  * MPI_FUNCTION_TARGET_STATUS_SEND
2141                  * MPI_FUNCTION_TARGET_MODE_ABORT
2142                  * MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET
2143                  * MPI_FUNCTION_IO_UNIT_RESET
2144                  * MPI_FUNCTION_HANDSHAKE
2145                  * MPI_FUNCTION_REPLY_FRAME_REMOVAL
2146                  * MPI_FUNCTION_EVENT_NOTIFICATION
2147                  *  (driver handles event notification)
2148                  * MPI_FUNCTION_EVENT_ACK
2149                  */
2150
2151                 /*  What to do with these???  CHECK ME!!!
2152                         MPI_FUNCTION_FC_LINK_SRVC_BUF_POST
2153                         MPI_FUNCTION_FC_LINK_SRVC_RSP
2154                         MPI_FUNCTION_FC_ABORT
2155                         MPI_FUNCTION_LAN_SEND
2156                         MPI_FUNCTION_LAN_RECEIVE
2157                         MPI_FUNCTION_LAN_RESET
2158                 */
2159
2160                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2161                         "Illegal request (function 0x%x) \n",
2162                         __FILE__, __LINE__, hdr->Function);
2163                 rc = -EFAULT;
2164                 goto done_free_mem;
2165         }
2166
2167         /* Add the SGL ( at most one data in SGE and one data out SGE )
2168          * In the case of two SGE's - the data out (write) will always
2169          * preceede the data in (read) SGE. psgList is used to free the
2170          * allocated memory.
2171          */
2172         psge = (char *) (((int *) mf) + karg.dataSgeOffset);
2173         flagsLength = 0;
2174
2175         /* bufIn and bufOut are used for user to kernel space transfers
2176          */
2177         bufIn.kptr = bufOut.kptr = NULL;
2178         bufIn.len = bufOut.len = 0;
2179
2180         if (karg.dataOutSize > 0)
2181                 sgSize ++;
2182
2183         if (karg.dataInSize > 0)
2184                 sgSize ++;
2185
2186         if (sgSize > 0) {
2187
2188                 /* Set up the dataOut memory allocation */
2189                 if (karg.dataOutSize > 0) {
2190                         dir = PCI_DMA_TODEVICE;
2191                         if (karg.dataInSize > 0) {
2192                                 flagsLength = ( MPI_SGE_FLAGS_SIMPLE_ELEMENT |
2193                                                 MPI_SGE_FLAGS_DIRECTION |
2194                                                 mpt_addr_size() )
2195                                                 << MPI_SGE_FLAGS_SHIFT;
2196                         } else {
2197                                 flagsLength = MPT_SGE_FLAGS_SSIMPLE_WRITE;
2198                         }
2199                         flagsLength |= karg.dataOutSize;
2200                         bufOut.len = karg.dataOutSize;
2201                         bufOut.kptr = pci_alloc_consistent(
2202                                         ioc->pcidev, bufOut.len, &dma_addr_out);
2203
2204                         if (bufOut.kptr == NULL) {
2205                                 rc = -ENOMEM;
2206                                 goto done_free_mem;
2207                         } else {
2208                                 /* Set up this SGE.
2209                                  * Copy to MF and to sglbuf
2210                                  */
2211                                 mpt_add_sge(psge, flagsLength, dma_addr_out);
2212                                 psge += (sizeof(u32) + sizeof(dma_addr_t));
2213
2214                                 /* Copy user data to kernel space.
2215                                  */
2216                                 if (copy_from_user(bufOut.kptr,
2217                                                 karg.dataOutBufPtr,
2218                                                 bufOut.len)) {
2219                                         printk(KERN_ERR
2220                                                 "%s@%d::mptctl_do_mpt_command - Unable "
2221                                                 "to read user data "
2222                                                 "struct @ %p\n",
2223                                                 __FILE__, __LINE__,(void*)karg.dataOutBufPtr);
2224                                         rc =  -EFAULT;
2225                                         goto done_free_mem;
2226                                 }
2227                         }
2228                 }
2229
2230                 if (karg.dataInSize > 0) {
2231                         dir = PCI_DMA_FROMDEVICE;
2232                         flagsLength = MPT_SGE_FLAGS_SSIMPLE_READ;
2233                         flagsLength |= karg.dataInSize;
2234
2235                         bufIn.len = karg.dataInSize;
2236                         bufIn.kptr = pci_alloc_consistent(ioc->pcidev,
2237                                         bufIn.len, &dma_addr_in);
2238
2239                         if (bufIn.kptr == NULL) {
2240                                 rc = -ENOMEM;
2241                                 goto done_free_mem;
2242                         } else {
2243                                 /* Set up this SGE
2244                                  * Copy to MF and to sglbuf
2245                                  */
2246                                 mpt_add_sge(psge, flagsLength, dma_addr_in);
2247                         }
2248                 }
2249         } else  {
2250                 /* Add a NULL SGE
2251                  */
2252                 mpt_add_sge(psge, flagsLength, (dma_addr_t) -1);
2253         }
2254
2255         /* The request is complete. Set the timer parameters
2256          * and issue the request.
2257          */
2258         if (karg.timeout > 0) {
2259                 ioc->ioctl->timer.expires = jiffies + HZ*karg.timeout;
2260         } else {
2261                 ioc->ioctl->timer.expires = jiffies + HZ*MPT_IOCTL_DEFAULT_TIMEOUT;
2262         }
2263
2264         ioc->ioctl->wait_done = 0;
2265         ioc->ioctl->status |= MPT_IOCTL_STATUS_TIMER_ACTIVE;
2266         add_timer(&ioc->ioctl->timer);
2267
2268         if (hdr->Function == MPI_FUNCTION_SCSI_TASK_MGMT) {
2269                 rc = mpt_send_handshake_request(mptctl_id, ioc->id,
2270                                 sizeof(SCSITaskMgmt_t), (u32*)mf, CAN_SLEEP);
2271                 if (rc == 0) {
2272                         wait_event(mptctl_wait, ioc->ioctl->wait_done);
2273                 } else {
2274                         mptctl_free_tm_flags(ioc);
2275                         tm_flags_set= 0;
2276                         del_timer(&ioc->ioctl->timer);
2277                         ioc->ioctl->status &= ~MPT_IOCTL_STATUS_TIMER_ACTIVE;
2278                         ioc->ioctl->status |= MPT_IOCTL_STATUS_TM_FAILED;
2279                         mpt_free_msg_frame(mptctl_id, ioc->id, mf);
2280                 }
2281         } else {
2282                 mpt_put_msg_frame(mptctl_id, ioc->id, mf);
2283                 wait_event(mptctl_wait, ioc->ioctl->wait_done);
2284         }
2285
2286         mf = NULL;
2287
2288         /* MF Cleanup:
2289          * If command failed and failure triggered a diagnostic reset
2290          * OR a diagnostic reset happens during command processing,
2291          * no data, messaging queues are reset (mf cannot be accessed),
2292          * and status is DID_IOCRESET
2293          *
2294          * If a user-requested bus reset fails to be handshaked, then
2295          * mf is returned to free queue and status is TM_FAILED.
2296          *
2297          * Otherise, the command completed and the mf was freed
2298          # by ISR (mf cannot be touched).
2299          */
2300         if (ioc->ioctl->status & MPT_IOCTL_STATUS_DID_IOCRESET) {
2301                 /* The timer callback deleted the
2302                  * timer and reset the adapter queues.
2303                  */
2304                 printk(KERN_WARNING "%s@%d::mptctl_do_mpt_command - "
2305                         "Timeout Occurred on IOCTL! Reset IOC.\n", __FILE__, __LINE__);
2306                 tm_flags_set= 0;
2307                 rc = -ETIME;
2308         } else if (ioc->ioctl->status & MPT_IOCTL_STATUS_TM_FAILED) {
2309                 /* User TM request failed! mf has not been freed.
2310                  */
2311                 rc = -ENODATA;
2312         } else {
2313                 /* If a valid reply frame, copy to the user.
2314                  * Offset 2: reply length in U32's
2315                  */
2316                 if (ioc->ioctl->status & MPT_IOCTL_STATUS_RF_VALID) {
2317                         if (karg.maxReplyBytes < ioc->reply_sz) {
2318                                  sz = min(karg.maxReplyBytes, 4*ioc->ioctl->ReplyFrame[2]);
2319                         } else {
2320                                  sz = min(ioc->reply_sz, 4*ioc->ioctl->ReplyFrame[2]);
2321                         }
2322
2323                         if (sz > 0) {
2324                                 if (copy_to_user((char *)karg.replyFrameBufPtr,
2325                                          &ioc->ioctl->ReplyFrame, sz)){
2326
2327                                          printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2328                                          "Unable to write out reply frame %p\n",
2329                                          __FILE__, __LINE__, (void*)karg.replyFrameBufPtr);
2330                                          rc =  -ENODATA;
2331                                          goto done_free_mem;
2332                                 }
2333                         }
2334                 }
2335
2336                 /* If valid sense data, copy to user.
2337                  */
2338                 if (ioc->ioctl->status & MPT_IOCTL_STATUS_SENSE_VALID) {
2339                         sz = min(karg.maxSenseBytes, MPT_SENSE_BUFFER_SIZE);
2340                         if (sz > 0) {
2341                                 if (copy_to_user((char *)karg.senseDataPtr, ioc->ioctl->sense, sz)) {
2342                                         printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2343                                         "Unable to write sense data to user %p\n",
2344                                         __FILE__, __LINE__,
2345                                         (void*)karg.senseDataPtr);
2346                                         rc =  -ENODATA;
2347                                         goto done_free_mem;
2348                                 }
2349                         }
2350                 }
2351
2352                 /* If the overall status is _GOOD and data in, copy data
2353                  * to user.
2354                  */
2355                 if ((ioc->ioctl->status & MPT_IOCTL_STATUS_COMMAND_GOOD) &&
2356                                         (karg.dataInSize > 0) && (bufIn.kptr)) {
2357
2358                         if (copy_to_user((char *)karg.dataInBufPtr,
2359                                          bufIn.kptr, karg.dataInSize)) {
2360                                 printk(KERN_ERR "%s@%d::mptctl_do_mpt_command - "
2361                                         "Unable to write data to user %p\n",
2362                                         __FILE__, __LINE__,
2363                                         (void*)karg.dataInBufPtr);
2364                                 rc =  -ENODATA;
2365                         }
2366                 }
2367         }
2368
2369 done_free_mem:
2370         /* Clear all status bits except TMTIMER_ACTIVE, this bit is cleared
2371          * upon completion of the TM command.
2372          * ioc->ioctl->status = 0;
2373          */
2374         ioc->ioctl->status &= ~(MPT_IOCTL_STATUS_TIMER_ACTIVE | MPT_IOCTL_STATUS_TM_FAILED |
2375                         MPT_IOCTL_STATUS_COMMAND_GOOD | MPT_IOCTL_STATUS_SENSE_VALID |
2376                         MPT_IOCTL_STATUS_RF_VALID | MPT_IOCTL_STATUS_DID_IOCRESET);
2377
2378         if (tm_flags_set)
2379                 mptctl_free_tm_flags(ioc);
2380
2381         /* Free the allocated memory.
2382          */
2383          if (bufOut.kptr != NULL) {
2384                 pci_free_consistent(ioc->pcidev,
2385                         bufOut.len, (void *) bufOut.kptr, dma_addr_out);
2386         }
2387
2388         if (bufIn.kptr != NULL) {
2389                 pci_free_consistent(ioc->pcidev,
2390                         bufIn.len, (void *) bufIn.kptr, dma_addr_in);
2391         }
2392
2393         /* mf is null if command issued successfully
2394          * otherwise, failure occured after mf acquired.
2395          */
2396         if (mf)
2397                 mpt_free_msg_frame(mptctl_id, ioc->id, mf);
2398
2399         return rc;
2400 }
2401
2402 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2403 /* Prototype Routine for the HP HOST INFO command.
2404  *
2405  * Outputs:     None.
2406  * Return:      0 if successful
2407  *              -EFAULT if data unavailable
2408  *              -EBUSY  if previous command timout and IOC reset is not complete.
2409  *              -ENODEV if no such device/adapter
2410  *              -ETIME  if timer expires
2411  *              -ENOMEM if memory allocation error
2412  */
2413 static int
2414 mptctl_hp_hostinfo(unsigned long arg, unsigned int data_size)
2415 {
2416         hp_host_info_t  *uarg = (hp_host_info_t *) arg;
2417         MPT_ADAPTER             *ioc;
2418         struct pci_dev          *pdev;
2419         char                    *pbuf;
2420         dma_addr_t              buf_dma;
2421         hp_host_info_t          karg;
2422         CONFIGPARMS             cfg;
2423         ConfigPageHeader_t      hdr;
2424         int                     iocnum;
2425         int                     rc, cim_rev;
2426
2427         dctlprintk((": mptctl_hp_hostinfo called.\n"));
2428         /* Reset long to int. Should affect IA64 and SPARC only
2429          */
2430         if (data_size == sizeof(hp_host_info_t))
2431                 cim_rev = 1;
2432         else if (data_size == sizeof(hp_host_info_rev0_t))
2433                 cim_rev = 0;    /* obsolete */
2434         else
2435                 return -EFAULT;
2436
2437         if (copy_from_user(&karg, uarg, sizeof(hp_host_info_t))) {
2438                 printk(KERN_ERR "%s@%d::mptctl_hp_host_info - "
2439                         "Unable to read in hp_host_info struct @ %p\n",
2440                                 __FILE__, __LINE__, (void*)uarg);
2441                 return -EFAULT;
2442         }
2443
2444         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
2445             (ioc == NULL)) {
2446                 dctlprintk((KERN_ERR "%s::mptctl_hp_hostinfo() @%d - ioc%d not found!\n",
2447                                 __FILE__, __LINE__, iocnum));
2448                 return -ENODEV;
2449         }
2450
2451         /* Fill in the data and return the structure to the calling
2452          * program
2453          */
2454         pdev = (struct pci_dev *) ioc->pcidev;
2455
2456         karg.vendor = pdev->vendor;
2457         karg.device = pdev->device;
2458 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
2459         karg.subsystem_id = pdev->subsystem_device;
2460         karg.subsystem_vendor = pdev->subsystem_vendor;
2461 #endif
2462         karg.devfn = pdev->devfn;
2463         karg.bus = pdev->bus->number;
2464
2465         /* Save the SCSI host no. if
2466          * SCSI driver loaded
2467          */
2468         if (ioc->sh != NULL)
2469                 karg.host_no = ioc->sh->host_no;
2470         else
2471                 karg.host_no =  -1;
2472
2473         /* Reformat the fw_version into a string
2474          */
2475         karg.fw_version[0] = ioc->facts.FWVersion.Struct.Major >= 10 ?
2476                 ((ioc->facts.FWVersion.Struct.Major / 10) + '0') : '0';
2477         karg.fw_version[1] = (ioc->facts.FWVersion.Struct.Major % 10 ) + '0';
2478         karg.fw_version[2] = '.';
2479         karg.fw_version[3] = ioc->facts.FWVersion.Struct.Minor >= 10 ?
2480                 ((ioc->facts.FWVersion.Struct.Minor / 10) + '0') : '0';
2481         karg.fw_version[4] = (ioc->facts.FWVersion.Struct.Minor % 10 ) + '0';
2482         karg.fw_version[5] = '.';
2483         karg.fw_version[6] = ioc->facts.FWVersion.Struct.Unit >= 10 ?
2484                 ((ioc->facts.FWVersion.Struct.Unit / 10) + '0') : '0';
2485         karg.fw_version[7] = (ioc->facts.FWVersion.Struct.Unit % 10 ) + '0';
2486         karg.fw_version[8] = '.';
2487         karg.fw_version[9] = ioc->facts.FWVersion.Struct.Dev >= 10 ?
2488                 ((ioc->facts.FWVersion.Struct.Dev / 10) + '0') : '0';
2489         karg.fw_version[10] = (ioc->facts.FWVersion.Struct.Dev % 10 ) + '0';
2490         karg.fw_version[11] = '\0';
2491
2492         /* Issue a config request to get the device serial number
2493          */
2494         hdr.PageVersion = 0;
2495         hdr.PageLength = 0;
2496         hdr.PageNumber = 0;
2497         hdr.PageType = MPI_CONFIG_PAGETYPE_MANUFACTURING;
2498         cfg.hdr = &hdr;
2499         cfg.physAddr = -1;
2500         cfg.pageAddr = 0;
2501         cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
2502         cfg.dir = 0;    /* read */
2503         cfg.timeout = 10;
2504
2505         strncpy(karg.serial_number, " ", 24);
2506         if (mpt_config(ioc, &cfg) == 0) {
2507                 if (cfg.hdr->PageLength > 0) {
2508                         /* Issue the second config page request */
2509                         cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
2510
2511                         pbuf = pci_alloc_consistent(ioc->pcidev, hdr.PageLength * 4, &buf_dma);
2512                         if (pbuf) {
2513                                 cfg.physAddr = buf_dma;
2514                                 if (mpt_config(ioc, &cfg) == 0) {
2515                                         ManufacturingPage0_t *pdata = (ManufacturingPage0_t *) pbuf;
2516                                         if (strlen(pdata->BoardTracerNumber) > 1) {
2517                                                 strncpy(karg.serial_number,                                                                         pdata->BoardTracerNumber, 24);
2518                                                 karg.serial_number[24-1]='\0';
2519                                         }
2520                                 }
2521                                 pci_free_consistent(ioc->pcidev, hdr.PageLength * 4, pbuf, buf_dma);
2522                                 pbuf = NULL;
2523                         }
2524                 }
2525         }
2526         rc = mpt_GetIocState(ioc, 1);
2527         switch (rc) {
2528         case MPI_IOC_STATE_OPERATIONAL:
2529                 karg.ioc_status =  HP_STATUS_OK;
2530                 break;
2531
2532         case MPI_IOC_STATE_FAULT:
2533                 karg.ioc_status =  HP_STATUS_FAILED;
2534                 break;
2535
2536         case MPI_IOC_STATE_RESET:
2537         case MPI_IOC_STATE_READY:
2538         default:
2539                 karg.ioc_status =  HP_STATUS_OTHER;
2540                 break;
2541         }
2542
2543         karg.base_io_addr = pdev->PCI_BASEADDR_START(0);
2544
2545         if ((int)ioc->chip_type <= (int) FC929)
2546                 karg.bus_phys_width = HP_BUS_WIDTH_UNK;
2547         else
2548                 karg.bus_phys_width = HP_BUS_WIDTH_16;
2549
2550         karg.hard_resets = 0;
2551         karg.soft_resets = 0;
2552         karg.timeouts = 0;
2553         if (ioc->sh != NULL) {
2554                 MPT_SCSI_HOST *hd =  (MPT_SCSI_HOST *)ioc->sh->hostdata;
2555
2556                 if (hd && (cim_rev == 1)) {
2557                         karg.hard_resets = hd->hard_resets;
2558                         karg.soft_resets = hd->soft_resets;
2559                         karg.timeouts = hd->timeouts;
2560                 }
2561         }
2562
2563         cfg.pageAddr = 0;
2564         cfg.action = MPI_TOOLBOX_ISTWI_READ_WRITE_TOOL;
2565         cfg.dir = MPI_TB_ISTWI_FLAGS_READ;
2566         cfg.timeout = 10;
2567         pbuf = pci_alloc_consistent(ioc->pcidev, 4, &buf_dma);
2568         if (pbuf) {
2569                 cfg.physAddr = buf_dma;
2570                 if ((mpt_toolbox(ioc, &cfg)) == 0) {
2571                         karg.rsvd = *(u32 *)pbuf;
2572                 }
2573                 pci_free_consistent(ioc->pcidev, 4, pbuf, buf_dma);
2574                 pbuf = NULL;
2575         }
2576
2577         /* Copy the data from kernel memory to user memory
2578          */
2579         if (copy_to_user((char *)arg, &karg,
2580                                 sizeof(hp_host_info_t))) {
2581                 printk(KERN_ERR "%s@%d::mptctl_hpgethostinfo - "
2582                         "Unable to write out hp_host_info @ %p\n",
2583                                 __FILE__, __LINE__, (void*)uarg);
2584                 return -EFAULT;
2585         }
2586
2587         return 0;
2588
2589 }
2590
2591 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2592 /* Prototype Routine for the HP TARGET INFO command.
2593  *
2594  * Outputs:     None.
2595  * Return:      0 if successful
2596  *              -EFAULT if data unavailable
2597  *              -EBUSY  if previous command timout and IOC reset is not complete.
2598  *              -ENODEV if no such device/adapter
2599  *              -ETIME  if timer expires
2600  *              -ENOMEM if memory allocation error
2601  */
2602 static int
2603 mptctl_hp_targetinfo(unsigned long arg)
2604 {
2605         hp_target_info_t        *uarg = (hp_target_info_t *) arg;
2606         SCSIDevicePage0_t       *pg0_alloc;
2607         SCSIDevicePage3_t       *pg3_alloc;
2608         MPT_ADAPTER             *ioc;
2609         MPT_SCSI_HOST           *hd = NULL;
2610         hp_target_info_t        karg;
2611         int                     iocnum;
2612         int                     data_sz;
2613         dma_addr_t              page_dma;
2614         CONFIGPARMS             cfg;
2615         ConfigPageHeader_t      hdr;
2616         int                     tmp, np, rc = 0;
2617
2618         dctlprintk((": mptctl_hp_targetinfo called.\n"));
2619         if (copy_from_user(&karg, uarg, sizeof(hp_target_info_t))) {
2620                 printk(KERN_ERR "%s@%d::mptctl_hp_targetinfo - "
2621                         "Unable to read in hp_host_targetinfo struct @ %p\n",
2622                                 __FILE__, __LINE__, (void*)uarg);
2623                 return -EFAULT;
2624         }
2625         
2626         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
2627                 (ioc == NULL)) {
2628                 dctlprintk((KERN_ERR "%s::mptctl_hp_targetinfo() @%d - ioc%d not found!\n",
2629                                 __FILE__, __LINE__, iocnum));
2630                 return -ENODEV;
2631         }
2632
2633         /*  There is nothing to do for FCP parts.
2634          */
2635         if ((int) ioc->chip_type <= (int) FC929)
2636                 return 0;
2637
2638         if ((ioc->spi_data.sdp0length == 0) || (ioc->sh == NULL))
2639                 return 0;
2640
2641         if (ioc->sh->host_no != karg.hdr.host)
2642                 return -ENODEV;
2643                 
2644        /* Get the data transfer speeds
2645         */
2646         data_sz = ioc->spi_data.sdp0length * 4;
2647         pg0_alloc = (SCSIDevicePage0_t *) pci_alloc_consistent(ioc->pcidev, data_sz, &page_dma);
2648         if (pg0_alloc) {
2649                 hdr.PageVersion = ioc->spi_data.sdp0version;
2650                 hdr.PageLength = data_sz;
2651                 hdr.PageNumber = 0;
2652                 hdr.PageType = MPI_CONFIG_PAGETYPE_SCSI_DEVICE;
2653
2654                 cfg.hdr = &hdr;
2655                 cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
2656                 cfg.dir = 0;
2657                 cfg.timeout = 0;
2658                 cfg.physAddr = page_dma;
2659
2660                 cfg.pageAddr = (karg.hdr.channel << 8) | karg.hdr.id;
2661
2662                 if ((rc = mpt_config(ioc, &cfg)) == 0) {
2663                         np = le32_to_cpu(pg0_alloc->NegotiatedParameters);
2664                         karg.negotiated_width = np & MPI_SCSIDEVPAGE0_NP_WIDE ?
2665                                         HP_BUS_WIDTH_16 : HP_BUS_WIDTH_8;
2666
2667                         if (np & MPI_SCSIDEVPAGE0_NP_NEG_SYNC_OFFSET_MASK) {
2668                                 tmp = (np & MPI_SCSIDEVPAGE0_NP_NEG_SYNC_PERIOD_MASK) >> 8;
2669                                 if (tmp < 0x09)
2670                                         karg.negotiated_speed = HP_DEV_SPEED_ULTRA320;
2671                                 else if (tmp <= 0x09)
2672                                         karg.negotiated_speed = HP_DEV_SPEED_ULTRA160;
2673                                 else if (tmp <= 0x0A)
2674                                         karg.negotiated_speed = HP_DEV_SPEED_ULTRA2;
2675                                 else if (tmp <= 0x0C)
2676                                         karg.negotiated_speed = HP_DEV_SPEED_ULTRA;
2677                                 else if (tmp <= 0x25)
2678                                         karg.negotiated_speed = HP_DEV_SPEED_FAST;
2679                                 else
2680                                         karg.negotiated_speed = HP_DEV_SPEED_ASYNC;
2681                         } else
2682                                 karg.negotiated_speed = HP_DEV_SPEED_ASYNC;
2683                 }
2684
2685                 pci_free_consistent(ioc->pcidev, data_sz, (u8 *) pg0_alloc, page_dma);
2686         }
2687
2688         /* Set defaults
2689          */
2690         karg.message_rejects = -1;
2691         karg.phase_errors = -1;
2692         karg.parity_errors = -1;
2693         karg.select_timeouts = -1;
2694
2695         /* Get the target error parameters
2696          */
2697         hdr.PageVersion = 0;
2698         hdr.PageLength = 0;
2699         hdr.PageNumber = 3;
2700         hdr.PageType = MPI_CONFIG_PAGETYPE_SCSI_DEVICE;
2701
2702         cfg.hdr = &hdr;
2703         cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
2704         cfg.dir = 0;
2705         cfg.timeout = 0;
2706         cfg.physAddr = -1;
2707         if ((mpt_config(ioc, &cfg) == 0) && (cfg.hdr->PageLength > 0)) {
2708                 /* Issue the second config page request */
2709                 cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
2710                 data_sz = (int) cfg.hdr->PageLength * 4;
2711                 pg3_alloc = (SCSIDevicePage3_t *) pci_alloc_consistent(
2712                                                         ioc->pcidev, data_sz, &page_dma);
2713                 if (pg3_alloc) {
2714                         cfg.physAddr = page_dma;
2715                         cfg.pageAddr = (karg.hdr.channel << 8) | karg.hdr.id;
2716                         if ((rc = mpt_config(ioc, &cfg)) == 0) {
2717                                 karg.message_rejects = (u32) le16_to_cpu(pg3_alloc->MsgRejectCount);
2718                                 karg.phase_errors = (u32) le16_to_cpu(pg3_alloc->PhaseErrorCount);
2719                                 karg.parity_errors = (u32) le16_to_cpu(pg3_alloc->ParityErrorCount);
2720                         }
2721                         pci_free_consistent(ioc->pcidev, data_sz, (u8 *) pg3_alloc, page_dma);
2722                 }
2723         }
2724         hd = (MPT_SCSI_HOST *) ioc->sh->hostdata;
2725         if (hd != NULL)
2726                 karg.select_timeouts = hd->sel_timeout[karg.hdr.id];
2727
2728         /* Copy the data from kernel memory to user memory
2729          */
2730         if (copy_to_user((char *)arg, &karg, sizeof(hp_target_info_t))) {
2731                 printk(KERN_ERR "%s@%d::mptctl_hp_target_info - "
2732                         "Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
2733                                 __FILE__, __LINE__, (void*)uarg);
2734                 return -EFAULT;
2735         }
2736
2737         return 0;
2738 }
2739
2740 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2741
2742 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,51)
2743 #define owner_THIS_MODULE  .owner = THIS_MODULE,
2744 #else
2745 #define owner_THIS_MODULE
2746 #endif
2747
2748 static struct file_operations mptctl_fops = {
2749         owner_THIS_MODULE
2750         .llseek =       no_llseek,
2751         .read =         mptctl_read,
2752         .write =        mptctl_write,
2753         .ioctl =        mptctl_ioctl,
2754         .open =         mptctl_open,
2755         .release =      mptctl_release,
2756 };
2757
2758 static struct miscdevice mptctl_miscdev = {
2759         MPT_MINOR,
2760         MYNAM,
2761         &mptctl_fops
2762 };
2763
2764 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2765
2766 #ifdef CONFIG_COMPAT
2767
2768 #include <linux/ioctl32.h>
2769
2770 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2771 /* compat_XXX functions are used to provide a conversion between
2772  * pointers and u32's. If the arg does not contain any pointers, then
2773  * a specialized function (compat_XXX) is not needed. If the arg
2774  * does contain pointer(s), then the specialized function is used
2775  * to ensure the structure contents is properly processed by mptctl.
2776  */
2777 static int
2778 compat_mptctl_ioctl(unsigned int fd, unsigned int cmd,
2779                         unsigned long arg, struct file *filp)
2780 {
2781         int ret;
2782
2783         lock_kernel();
2784         dctlprintk((KERN_INFO MYNAM "::compat_mptctl_ioctl() called\n"));
2785         ret = mptctl_ioctl(filp->f_dentry->d_inode, filp, cmd, arg);
2786         unlock_kernel();
2787         return ret;
2788 }
2789  
2790 static int
2791 compat_mptfwxfer_ioctl(unsigned int fd, unsigned int cmd,
2792                         unsigned long arg, struct file *filp)
2793 {
2794         struct mpt_fw_xfer32 kfw32;
2795         struct mpt_fw_xfer kfw;
2796         MPT_ADAPTER *iocp = NULL;
2797         int iocnum, iocnumX;
2798         int nonblock = (filp->f_flags & O_NONBLOCK);
2799         int ret;
2800
2801         dctlprintk((KERN_INFO MYNAM "::compat_mptfwxfer_ioctl() called\n"));
2802
2803         if (copy_from_user(&kfw32, (char *)arg, sizeof(kfw32)))
2804                 return -EFAULT;
2805
2806         /* Verify intended MPT adapter */
2807         iocnumX = kfw32.iocnum & 0xFF;
2808         if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
2809             (iocp == NULL)) {
2810                 dctlprintk((KERN_ERR MYNAM "::compat_mptfwxfer_ioctl @%d - ioc%d not found!\n",
2811                                 __LINE__, iocnumX));
2812                 return -ENODEV;
2813         }
2814
2815         if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
2816                 return ret;
2817
2818         kfw.iocnum = iocnum;
2819         kfw.fwlen = kfw32.fwlen;
2820         kfw.bufp = (void *)(unsigned long)kfw32.bufp;
2821
2822         ret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);
2823
2824         up(&mptctl_syscall_sem_ioc[iocp->id]);
2825
2826         return ret;
2827 }
2828
2829 static int
2830 compat_mpt_command(unsigned int fd, unsigned int cmd,
2831                         unsigned long arg, struct file *filp)
2832 {
2833         struct mpt_ioctl_command32 karg32;
2834         struct mpt_ioctl_command32 *uarg = (struct mpt_ioctl_command32 *) arg;
2835         struct mpt_ioctl_command karg;
2836         MPT_ADAPTER *iocp = NULL;
2837         int iocnum, iocnumX;
2838         int nonblock = (filp->f_flags & O_NONBLOCK);
2839         int ret;
2840
2841         dctlprintk((KERN_INFO MYNAM "::compat_mpt_command() called\n"));
2842
2843         if (copy_from_user(&karg32, (char *)arg, sizeof(karg32)))
2844                 return -EFAULT;
2845
2846         /* Verify intended MPT adapter */
2847         iocnumX = karg32.hdr.iocnum & 0xFF;
2848         if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
2849             (iocp == NULL)) {
2850                 dctlprintk((KERN_ERR MYNAM "::compat_mpt_command @%d - ioc%d not found!\n",
2851                                 __LINE__, iocnumX));
2852                 return -ENODEV;
2853         }
2854
2855         if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
2856                 return ret;
2857
2858         /* Copy data to karg */
2859         karg.hdr.iocnum = karg32.hdr.iocnum;
2860         karg.hdr.port = karg32.hdr.port;
2861         karg.timeout = karg32.timeout;
2862         karg.maxReplyBytes = karg32.maxReplyBytes;
2863
2864         karg.dataInSize = karg32.dataInSize;
2865         karg.dataOutSize = karg32.dataOutSize;
2866         karg.maxSenseBytes = karg32.maxSenseBytes;
2867         karg.dataSgeOffset = karg32.dataSgeOffset;
2868
2869         karg.replyFrameBufPtr = (char *)(unsigned long)karg32.replyFrameBufPtr;
2870         karg.dataInBufPtr = (char *)(unsigned long)karg32.dataInBufPtr;
2871         karg.dataOutBufPtr = (char *)(unsigned long)karg32.dataOutBufPtr;
2872         karg.senseDataPtr = (char *)(unsigned long)karg32.senseDataPtr;
2873
2874         /* Pass new structure to do_mpt_command
2875          */
2876         ret = mptctl_do_mpt_command (karg, (char *) &uarg->MF, 0);
2877
2878         up(&mptctl_syscall_sem_ioc[iocp->id]);
2879
2880         return ret;
2881 }
2882
2883 #endif
2884
2885 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2886 int __init mptctl_init(void)
2887 {
2888         int err;
2889         int i;
2890         int where = 1;
2891         int sz;
2892         u8 *mem;
2893         MPT_ADAPTER *ioc = NULL;
2894         int iocnum;
2895
2896         show_mptmod_ver(my_NAME, my_VERSION);
2897
2898         for (i=0; i<MPT_MAX_ADAPTERS; i++) {
2899                 sema_init(&mptctl_syscall_sem_ioc[i], 1);
2900
2901                 ioc = NULL;
2902                 if (((iocnum = mpt_verify_adapter(i, &ioc)) < 0) ||
2903                     (ioc == NULL)) {
2904                         continue;
2905                 }
2906                 else {
2907                         /* This adapter instance is found.
2908                          * Allocate and inite a MPT_IOCTL structure
2909                          */
2910                         sz = sizeof (MPT_IOCTL);
2911                         mem = kmalloc(sz, GFP_KERNEL);
2912                         if (mem == NULL) {
2913                                 err = -ENOMEM;
2914                                 goto out_fail;
2915                         }
2916
2917                         memset(mem, 0, sz);
2918                         ioc->ioctl = (MPT_IOCTL *) mem;
2919                         ioc->ioctl->ioc = ioc;
2920                         init_timer (&ioc->ioctl->timer);
2921                         ioc->ioctl->timer.data = (unsigned long) ioc->ioctl;
2922                         ioc->ioctl->timer.function = mptctl_timer_expired;
2923                         init_timer (&ioc->ioctl->TMtimer);
2924                         ioc->ioctl->TMtimer.data = (unsigned long) ioc->ioctl;
2925                         ioc->ioctl->TMtimer.function = mptctl_timer_expired;
2926                 }
2927         }
2928
2929 #ifdef CONFIG_COMPAT
2930         err = register_ioctl32_conversion(MPTIOCINFO, compat_mptctl_ioctl);
2931         if (++where && err) goto out_fail;
2932         err = register_ioctl32_conversion(MPTIOCINFO1, compat_mptctl_ioctl);
2933         if (++where && err) goto out_fail;
2934         err = register_ioctl32_conversion(MPTIOCINFO2, compat_mptctl_ioctl);
2935         if (++where && err) goto out_fail;
2936         err = register_ioctl32_conversion(MPTTARGETINFO, compat_mptctl_ioctl);
2937         if (++where && err) goto out_fail;
2938         err = register_ioctl32_conversion(MPTTEST, compat_mptctl_ioctl);
2939         if (++where && err) goto out_fail;
2940         err = register_ioctl32_conversion(MPTEVENTQUERY, compat_mptctl_ioctl);
2941         if (++where && err) goto out_fail;
2942         err = register_ioctl32_conversion(MPTEVENTENABLE, compat_mptctl_ioctl);
2943         if (++where && err) goto out_fail;
2944         err = register_ioctl32_conversion(MPTEVENTREPORT, compat_mptctl_ioctl);
2945         if (++where && err) goto out_fail;
2946         err = register_ioctl32_conversion(MPTHARDRESET, compat_mptctl_ioctl);
2947         if (++where && err) goto out_fail;
2948         err = register_ioctl32_conversion(MPTCOMMAND32, compat_mpt_command);
2949         if (++where && err) goto out_fail;
2950         err = register_ioctl32_conversion(MPTFWDOWNLOAD32,
2951                                           compat_mptfwxfer_ioctl);
2952         if (++where && err) goto out_fail;
2953         err = register_ioctl32_conversion(HP_GETHOSTINFO, compat_mptctl_ioctl);
2954         if (++where && err) goto out_fail;
2955         err = register_ioctl32_conversion(HP_GETTARGETINFO, compat_mptctl_ioctl);
2956         if (++where && err) goto out_fail;
2957 #endif
2958
2959         /* Register this device */
2960         err = misc_register(&mptctl_miscdev);
2961         if (err < 0) {
2962                 printk(KERN_ERR MYNAM ": Can't register misc device [minor=%d].\n", MPT_MINOR);
2963                 goto out_fail;
2964         }
2965         printk(KERN_INFO MYNAM ": Registered with Fusion MPT base driver\n");
2966         printk(KERN_INFO MYNAM ": /dev/%s @ (major,minor=%d,%d)\n",
2967                          mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
2968
2969         /*
2970          *  Install our handler
2971          */
2972         ++where;
2973         if ((mptctl_id = mpt_register(mptctl_reply, MPTCTL_DRIVER)) < 0) {
2974                 printk(KERN_ERR MYNAM ": ERROR: Failed to register with Fusion MPT base driver\n");
2975                 misc_deregister(&mptctl_miscdev);
2976                 err = -EBUSY;
2977                 goto out_fail;
2978         }
2979
2980         if (mpt_reset_register(mptctl_id, mptctl_ioc_reset) == 0) {
2981                 dprintk((KERN_INFO MYNAM ": Registered for IOC reset notifications\n"));
2982         } else {
2983                 /* FIXME! */
2984         }
2985
2986         return 0;
2987
2988 out_fail:
2989
2990 #ifdef CONFIG_COMPAT
2991         printk(KERN_ERR MYNAM ": ERROR: Failed to register ioctl32_conversion!"
2992                         " (%d:err=%d)\n", where, err);
2993         unregister_ioctl32_conversion(MPTIOCINFO);
2994         unregister_ioctl32_conversion(MPTIOCINFO1);
2995         unregister_ioctl32_conversion(MPTIOCINFO2);
2996         unregister_ioctl32_conversion(MPTTARGETINFO);
2997         unregister_ioctl32_conversion(MPTTEST);
2998         unregister_ioctl32_conversion(MPTEVENTQUERY);
2999         unregister_ioctl32_conversion(MPTEVENTENABLE);
3000         unregister_ioctl32_conversion(MPTEVENTREPORT);
3001         unregister_ioctl32_conversion(MPTHARDRESET);
3002         unregister_ioctl32_conversion(MPTCOMMAND32);
3003         unregister_ioctl32_conversion(MPTFWDOWNLOAD32);
3004         unregister_ioctl32_conversion(HP_GETHOSTINFO);
3005         unregister_ioctl32_conversion(HP_GETTARGETINFO);
3006 #endif
3007
3008         for (i=0; i<MPT_MAX_ADAPTERS; i++) {
3009                 ioc = NULL;
3010                 if (((iocnum = mpt_verify_adapter(i, &ioc)) < 0) ||
3011                     (ioc == NULL)) {
3012                         continue;
3013                 }
3014                 else {
3015                         if (ioc->ioctl) {
3016                                 kfree ( ioc->ioctl );
3017                                 ioc->ioctl = NULL;
3018                         }
3019                 }
3020         }
3021         return err;
3022 }
3023
3024 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
3025 void mptctl_exit(void)
3026 {
3027         int i;
3028         MPT_ADAPTER *ioc;
3029         int iocnum;
3030
3031         misc_deregister(&mptctl_miscdev);
3032         printk(KERN_INFO MYNAM ": Deregistered /dev/%s @ (major,minor=%d,%d)\n",
3033                          mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
3034
3035         /* De-register reset handler from base module */
3036         mpt_reset_deregister(mptctl_id);
3037         dprintk((KERN_INFO MYNAM ": Deregistered for IOC reset notifications\n"));
3038
3039         /* De-register callback handler from base module */
3040         mpt_deregister(mptctl_id);
3041         printk(KERN_INFO MYNAM ": Deregistered from Fusion MPT base driver\n");
3042
3043 #ifdef CONFIG_COMPAT
3044         unregister_ioctl32_conversion(MPTIOCINFO);
3045         unregister_ioctl32_conversion(MPTIOCINFO1);
3046         unregister_ioctl32_conversion(MPTIOCINFO2);
3047         unregister_ioctl32_conversion(MPTTARGETINFO);
3048         unregister_ioctl32_conversion(MPTTEST);
3049         unregister_ioctl32_conversion(MPTEVENTQUERY);
3050         unregister_ioctl32_conversion(MPTEVENTENABLE);
3051         unregister_ioctl32_conversion(MPTEVENTREPORT);
3052         unregister_ioctl32_conversion(MPTHARDRESET);
3053         unregister_ioctl32_conversion(MPTCOMMAND32);
3054         unregister_ioctl32_conversion(MPTFWDOWNLOAD32);
3055         unregister_ioctl32_conversion(HP_GETHOSTINFO);
3056         unregister_ioctl32_conversion(HP_GETTARGETINFO);
3057 #endif
3058
3059         /* Free allocated memory */
3060         for (i=0; i<MPT_MAX_ADAPTERS; i++) {
3061                 ioc = NULL;
3062                 if (((iocnum = mpt_verify_adapter(i, &ioc)) < 0) ||
3063                     (ioc == NULL)) {
3064                         continue;
3065                 }
3066                 else {
3067                         if (ioc->ioctl) {
3068                                 kfree ( ioc->ioctl );
3069                                 ioc->ioctl = NULL;
3070                         }
3071                 }
3072         }
3073 }
3074
3075 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
3076
3077 module_init(mptctl_init);
3078 module_exit(mptctl_exit);