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