VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[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 static struct semaphore mptctl_syscall_sem_ioc[MPT_MAX_ADAPTERS];
115
116 static DECLARE_WAIT_QUEUE_HEAD ( mptctl_wait );
117
118 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
119
120 struct buflist {
121         u8      *kptr;
122         int      len;
123 };
124
125 /*
126  * Function prototypes. Called from OS entry point mptctl_ioctl.
127  * arg contents specific to function.
128  */
129 static int mptctl_fw_download(unsigned long arg);
130 static int mptctl_getiocinfo (unsigned long arg, unsigned int cmd);
131 static int mptctl_gettargetinfo (unsigned long arg);
132 static int mptctl_readtest (unsigned long arg);
133 static int mptctl_mpt_command (unsigned long arg);
134 static int mptctl_eventquery (unsigned long arg);
135 static int mptctl_eventenable (unsigned long arg);
136 static int mptctl_eventreport (unsigned long arg);
137 static int mptctl_replace_fw (unsigned long arg);
138
139 static int mptctl_do_reset(unsigned long arg);
140 static int mptctl_hp_hostinfo(unsigned long arg, unsigned int cmd);
141 static int mptctl_hp_targetinfo(unsigned long arg);
142
143 /*
144  * Private function calls.
145  */
146 static int mptctl_do_mpt_command (struct mpt_ioctl_command karg, void __user *mfPtr);
147 static int mptctl_do_fw_download(int ioc, char __user *ufwbuf, size_t fwlen);
148 static MptSge_t *kbuf_alloc_2_sgl( int bytes, u32 dir, int sge_offset, int *frags,
149                 struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc);
150 static void kfree_sgl( MptSge_t *sgl, dma_addr_t sgl_dma,
151                 struct buflist *buflist, MPT_ADAPTER *ioc);
152 static void mptctl_timer_expired (unsigned long data);
153 static int  mptctl_bus_reset(MPT_IOCTL *ioctl);
154 static int mptctl_set_tm_flags(MPT_SCSI_HOST *hd);
155 static void mptctl_free_tm_flags(MPT_ADAPTER *ioc);
156
157 /*
158  * Reset Handler cleanup function
159  */
160 static int  mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase);
161
162 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
163 /*
164  * Scatter gather list (SGL) sizes and limits...
165  */
166 //#define MAX_SCSI_FRAGS        9
167 #define MAX_FRAGS_SPILL1        9
168 #define MAX_FRAGS_SPILL2        15
169 #define FRAGS_PER_BUCKET        (MAX_FRAGS_SPILL2 + 1)
170
171 //#define MAX_CHAIN_FRAGS       64
172 //#define MAX_CHAIN_FRAGS       (15+15+15+16)
173 #define MAX_CHAIN_FRAGS         (4 * MAX_FRAGS_SPILL2 + 1)
174
175 //  Define max sg LIST bytes ( == (#frags + #chains) * 8 bytes each)
176 //  Works out to: 592d bytes!     (9+1)*8 + 4*(15+1)*8
177 //                  ^----------------- 80 + 512
178 #define MAX_SGL_BYTES           ((MAX_FRAGS_SPILL1 + 1 + (4 * FRAGS_PER_BUCKET)) * 8)
179
180 /* linux only seems to ever give 128kB MAX contiguous (GFP_USER) mem bytes */
181 #define MAX_KMALLOC_SZ          (128*1024)
182
183 #define MPT_IOCTL_DEFAULT_TIMEOUT 10    /* Default timeout value (seconds) */
184
185 static u32 fwReplyBuffer[16];
186 static pMPIDefaultReply_t ReplyMsg = NULL;
187
188 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
189 /**
190  *      mptctl_syscall_down - Down the MPT adapter syscall semaphore.
191  *      @ioc: Pointer to MPT adapter
192  *      @nonblock: boolean, non-zero if O_NONBLOCK is set
193  *
194  *      All of the ioctl commands can potentially sleep, which is illegal
195  *      with a spinlock held, thus we perform mutual exclusion here.
196  *
197  *      Returns negative errno on error, or zero for success.
198  */
199 static inline int
200 mptctl_syscall_down(MPT_ADAPTER *ioc, int nonblock)
201 {
202         int rc = 0;
203         dctlprintk((KERN_INFO MYNAM "::mptctl_syscall_down(%p,%d) called\n", ioc, nonblock));
204
205         if (ioc->ioctl->tmPtr != NULL) {
206                 dctlprintk((KERN_INFO MYNAM "::mptctl_syscall_down BUSY\n"));
207                 return -EBUSY;
208         }
209
210         if (nonblock) {
211                 if (down_trylock(&mptctl_syscall_sem_ioc[ioc->id]))
212                         rc = -EAGAIN;
213         } else {
214                 if (down_interruptible(&mptctl_syscall_sem_ioc[ioc->id]))
215                         rc = -ERESTARTSYS;
216         }
217         dctlprintk((KERN_INFO MYNAM "::mptctl_syscall_down return %d\n", rc));
218         return rc;
219 }
220
221 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
222 /*
223  *  This is the callback for any message we have posted. The message itself
224  *  will be returned to the message pool when we return from the IRQ
225  *
226  *  This runs in irq context so be short and sweet.
227  */
228 static int
229 mptctl_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *req, MPT_FRAME_HDR *reply)
230 {
231         char *sense_data;
232         int sz, req_index;
233         u16 iocStatus;
234         u8 cmd;
235
236         dctlprintk((MYIOC_s_INFO_FMT ": mptctl_reply()!\n", ioc->name));
237         if (req)
238                  cmd = req->u.hdr.Function;
239         else
240                 return 1;
241
242         if (ioc->ioctl) {
243                 /* If timer is not running, then an error occurred.
244                  * A timeout will call the reset routine to reload the messaging
245                  * queues.
246                  * Main callback will free message and reply frames.
247                  */
248                 if (reply && (cmd == MPI_FUNCTION_SCSI_TASK_MGMT) &&
249                     (ioc->ioctl->status & MPT_IOCTL_STATUS_TMTIMER_ACTIVE)) {
250                         /* This is internally generated TM
251                          */
252                         del_timer (&ioc->ioctl->TMtimer);
253                         ioc->ioctl->status &= ~MPT_IOCTL_STATUS_TMTIMER_ACTIVE;
254
255                         mptctl_free_tm_flags(ioc);
256
257                         /* If TM failed, reset the timer on the existing command,
258                          * will trigger an adapter reset.
259                          */
260                         iocStatus = reply->u.reply.IOCStatus & MPI_IOCSTATUS_MASK;
261                         if (iocStatus == MPI_IOCSTATUS_SCSI_TASK_MGMT_FAILED) {
262                                 if (ioc->ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE) {
263                                         ioc->ioctl->reset &= ~MPTCTL_RESET_OK;
264                                         del_timer (&ioc->ioctl->timer);
265                                         ioc->ioctl->timer.expires = jiffies + HZ;
266                                         add_timer(&ioc->ioctl->timer);
267                                 }
268                         }
269                         ioc->ioctl->tmPtr = NULL;
270
271                 } else if (ioc->ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE) {
272                         /* Delete this timer
273                          */
274                         del_timer (&ioc->ioctl->timer);
275                         ioc->ioctl->status &= ~MPT_IOCTL_STATUS_TIMER_ACTIVE;
276
277                         /* Set the overall status byte.  Good if:
278                          * IOC status is good OR if no reply and a SCSI IO request
279                          */
280                         if (reply) {
281                                 /* Copy the reply frame (which much exist
282                                  * for non-SCSI I/O) to the IOC structure.
283                                  */
284                                 dctlprintk((MYIOC_s_INFO_FMT ": Copying Reply Frame @%p to IOC!\n",
285                                                 ioc->name, reply));
286                                 memcpy(ioc->ioctl->ReplyFrame, reply,
287                                         min(ioc->reply_sz, 4*reply->u.reply.MsgLength));
288                                 ioc->ioctl->status |= MPT_IOCTL_STATUS_RF_VALID;
289
290                                 /* Set the command status to GOOD if IOC Status is GOOD
291                                  * OR if SCSI I/O cmd and data underrun or recovered error.
292                                  */
293                                 iocStatus = reply->u.reply.IOCStatus & MPI_IOCSTATUS_MASK;
294                                 if (iocStatus  == MPI_IOCSTATUS_SUCCESS)
295                                         ioc->ioctl->status |= MPT_IOCTL_STATUS_COMMAND_GOOD;
296
297                                 if ((cmd == MPI_FUNCTION_SCSI_IO_REQUEST) ||
298                                         (cmd == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
299                                         ioc->ioctl->reset &= ~MPTCTL_RESET_OK;
300
301                                         if ((iocStatus == MPI_IOCSTATUS_SCSI_DATA_UNDERRUN) ||
302                                                 (iocStatus == MPI_IOCSTATUS_SCSI_RECOVERED_ERROR)) {
303                                                 ioc->ioctl->status |= MPT_IOCTL_STATUS_COMMAND_GOOD;
304                                         }
305                                 }
306
307                                 /* Copy the sense data - if present
308                                  */
309                                 if ((cmd == MPI_FUNCTION_SCSI_IO_REQUEST) &&
310                                         (reply->u.sreply.SCSIState & MPI_SCSI_STATE_AUTOSENSE_VALID)){
311
312                                         sz = req->u.scsireq.SenseBufferLength;
313                                         req_index = le16_to_cpu(req->u.frame.hwhdr.msgctxu.fld.req_idx);
314                                         sense_data = ((u8 *)ioc->sense_buf_pool + (req_index * MPT_SENSE_BUFFER_ALLOC));
315                                         memcpy(ioc->ioctl->sense, sense_data, sz);
316                                         ioc->ioctl->status |= MPT_IOCTL_STATUS_SENSE_VALID;
317                                 }
318
319                                 if (cmd == MPI_FUNCTION_SCSI_TASK_MGMT)
320                                         mptctl_free_tm_flags(ioc);
321
322
323                         } else if ((cmd == MPI_FUNCTION_SCSI_IO_REQUEST) ||
324                                         (cmd == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
325                                 ioc->ioctl->status |= MPT_IOCTL_STATUS_COMMAND_GOOD;
326                                 ioc->ioctl->reset &= ~MPTCTL_RESET_OK;
327                         }
328
329                         /* We are done, issue wake up
330                          */
331                         ioc->ioctl->wait_done = 1;
332                         wake_up (&mptctl_wait);
333                 } else if (reply && cmd == MPI_FUNCTION_FW_DOWNLOAD) {
334                         /* Two paths to FW DOWNLOAD! */
335                         // NOTE: Expects/requires non-Turbo reply!
336                         dctlprintk((MYIOC_s_INFO_FMT ":Caching MPI_FUNCTION_FW_DOWNLOAD reply!\n",
337                                 ioc->name));
338                         memcpy(fwReplyBuffer, reply, min_t(int, sizeof(fwReplyBuffer), 4*reply->u.reply.MsgLength));
339                         ReplyMsg = (pMPIDefaultReply_t) fwReplyBuffer;
340                 }
341         }
342         return 1;
343 }
344
345 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
346 /* mptctl_timer_expired
347  *
348  * Call back for timer process. Used only for ioctl functionality.
349  *
350  */
351 static void mptctl_timer_expired (unsigned long data)
352 {
353         MPT_IOCTL *ioctl = (MPT_IOCTL *) data;
354         int rc = 1;
355
356         dctlprintk((KERN_NOTICE MYNAM ": Timer Expired! Host %d\n",
357                                 ioctl->ioc->id));
358         if (ioctl == NULL)
359                 return;
360
361         if (ioctl->reset & MPTCTL_RESET_OK)
362                 rc = mptctl_bus_reset(ioctl);
363
364         if (rc) {
365                 /* Issue a reset for this device.
366                  * The IOC is not responding.
367                  */
368                 mpt_HardResetHandler(ioctl->ioc, NO_SLEEP);
369         }
370         return;
371
372 }
373
374 /* mptctl_bus_reset
375  *
376  * Bus reset code.
377  *
378  */
379 static int mptctl_bus_reset(MPT_IOCTL *ioctl)
380 {
381         MPT_FRAME_HDR   *mf;
382         SCSITaskMgmt_t  *pScsiTm;
383         MPT_SCSI_HOST   *hd;
384         int              ii;
385         int              retval;
386
387
388         ioctl->reset &= ~MPTCTL_RESET_OK;
389
390         if (ioctl->ioc->sh == NULL)
391                 return -EPERM;
392         
393         hd = (MPT_SCSI_HOST *) ioctl->ioc->sh->hostdata;
394         if (hd == NULL)
395                 return -EPERM;
396
397         /* Single threading ....
398          */
399         if (mptctl_set_tm_flags(hd) != 0)
400                 return -EPERM;
401
402         /* Send request
403          */
404         if ((mf = mpt_get_msg_frame(mptctl_id, ioctl->ioc)) == NULL) {
405                 dctlprintk((MYIOC_s_WARN_FMT "IssueTaskMgmt, no msg frames!!\n",
406                                 ioctl->ioc->name));
407
408                 mptctl_free_tm_flags(ioctl->ioc);
409                 return -ENOMEM;
410         }
411
412         dtmprintk((MYIOC_s_INFO_FMT "IssueTaskMgmt request @ %p\n",
413                         ioctl->ioc->name, mf));
414
415         pScsiTm = (SCSITaskMgmt_t *) mf;
416         pScsiTm->TargetID = ioctl->target;
417         pScsiTm->Bus = hd->port;        /* 0 */
418         pScsiTm->ChainOffset = 0;
419         pScsiTm->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
420         pScsiTm->Reserved = 0;
421         pScsiTm->TaskType = MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS;
422         pScsiTm->Reserved1 = 0;
423         pScsiTm->MsgFlags = MPI_SCSITASKMGMT_MSGFLAGS_LIPRESET_RESET_OPTION;
424
425         for (ii= 0; ii < 8; ii++)
426                 pScsiTm->LUN[ii] = 0;
427
428         for (ii=0; ii < 7; ii++)
429                 pScsiTm->Reserved2[ii] = 0;
430
431         pScsiTm->TaskMsgContext = 0;
432         dtmprintk((MYIOC_s_INFO_FMT "mptctl_bus_reset: issued.\n", ioctl->ioc->name));
433
434         ioctl->tmPtr = mf;
435         ioctl->TMtimer.expires = jiffies + HZ * 20;     /* 20 seconds */
436         ioctl->status |= MPT_IOCTL_STATUS_TMTIMER_ACTIVE;
437         add_timer(&ioctl->TMtimer);
438
439         retval = mpt_send_handshake_request(mptctl_id, ioctl->ioc,
440                         sizeof(SCSITaskMgmt_t), (u32*)pScsiTm, NO_SLEEP);
441
442         if (retval != 0) {
443                 dtmprintk((MYIOC_s_WARN_FMT "_send_handshake FAILED!"
444                         " (hd %p, ioc %p, mf %p) \n", ioctl->ioc->name, hd, hd->ioc, mf));
445
446                 mptctl_free_tm_flags(ioctl->ioc);
447                 del_timer(&ioctl->TMtimer);
448                 mpt_free_msg_frame(mptctl_id, ioctl->ioc, mf);
449                 ioctl->tmPtr = NULL;
450         }
451
452         return retval;
453 }
454
455 static int
456 mptctl_set_tm_flags(MPT_SCSI_HOST *hd) {
457         unsigned long flags;
458
459         spin_lock_irqsave(&hd->ioc->FreeQlock, flags);
460
461         if (hd->tmState == TM_STATE_NONE) {
462                 hd->tmState = TM_STATE_IN_PROGRESS;
463                 hd->tmPending = 1;
464                 spin_unlock_irqrestore(&hd->ioc->FreeQlock, flags);
465         } else {
466                 spin_unlock_irqrestore(&hd->ioc->FreeQlock, flags);
467                 return -EBUSY;
468         }
469
470         return 0;
471 }
472
473 static void
474 mptctl_free_tm_flags(MPT_ADAPTER *ioc)
475 {
476         MPT_SCSI_HOST * hd;
477         unsigned long flags;
478
479         hd = (MPT_SCSI_HOST *) ioc->sh->hostdata;
480         if (hd == NULL)
481                 return;
482
483         spin_lock_irqsave(&ioc->FreeQlock, flags);
484
485         hd->tmState = TM_STATE_ERROR;
486         hd->tmPending = 0;
487         spin_unlock_irqrestore(&ioc->FreeQlock, flags);
488
489         return;
490 }
491
492
493 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
494 /* mptctl_ioc_reset
495  *
496  * Clean-up functionality. Used only if there has been a
497  * reload of the FW due.
498  *
499  */
500 static int
501 mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase)
502 {
503         MPT_IOCTL *ioctl = ioc->ioctl;
504         dctlprintk((KERN_INFO MYNAM ": IOC %s_reset routed to IOCTL driver!\n",
505                         reset_phase==MPT_IOC_SETUP_RESET ? "setup" : (
506                         reset_phase==MPT_IOC_PRE_RESET ? "pre" : "post")));
507
508         if (reset_phase == MPT_IOC_SETUP_RESET){
509                 ;
510         } else if (reset_phase == MPT_IOC_PRE_RESET){
511
512                 /* Someone has called the reset handler to
513                  * do a hard reset. No more replies from the FW.
514                  * Delete the timer. TM flags cleaned up by SCSI driver.
515                  * Do not need to free msg frame, as re-initialized
516                  */
517                 if (ioctl && (ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE)){
518                         del_timer(&ioctl->timer);
519                 }
520                 if (ioctl && (ioctl->status & MPT_IOCTL_STATUS_TMTIMER_ACTIVE)){
521                         ioctl->status &= ~MPT_IOCTL_STATUS_TMTIMER_ACTIVE;
522                         del_timer(&ioctl->TMtimer);
523                         mpt_free_msg_frame(mptctl_id, ioc, ioctl->tmPtr);
524                 }
525
526         } else {
527                 ioctl->tmPtr = NULL;
528
529                 /* Set the status and continue IOCTL
530                  * processing. All memory will be free'd
531                  * by originating thread after wake_up is
532                  * called.
533                  */
534                 if (ioctl && (ioctl->status & MPT_IOCTL_STATUS_TIMER_ACTIVE)){
535                         ioctl->status |= MPT_IOCTL_STATUS_DID_IOCRESET;
536
537                         /* Wake up the calling process
538                          */
539                         ioctl->wait_done = 1;
540                         wake_up(&mptctl_wait);
541                 }
542         }
543
544         return 1;
545 }
546
547 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
548 /*
549  *  MPT ioctl handler
550  *  cmd - specify the particular IOCTL command to be issued
551  *  arg - data specific to the command. Must not be null.
552  */
553 static int
554 mptctl_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
555 {
556         mpt_ioctl_header __user *uhdr = (void __user *) arg;
557         mpt_ioctl_header         khdr;
558         int iocnum;
559         unsigned iocnumX;
560         int nonblock = (file->f_flags & O_NONBLOCK);
561         int ret;
562         MPT_ADAPTER *iocp = NULL;
563
564         dctlprintk(("mptctl_ioctl() called\n"));
565
566         if (copy_from_user(&khdr, uhdr, sizeof(khdr))) {
567                 printk(KERN_ERR "%s::mptctl_ioctl() @%d - "
568                                 "Unable to copy mpt_ioctl_header data @ %p\n",
569                                 __FILE__, __LINE__, uhdr);
570                 return -EFAULT;
571         }
572         ret = -ENXIO;                           /* (-6) No such device or address */
573
574         /* Verify intended MPT adapter - set iocnum and the adapter
575          * pointer (iocp)
576          */
577         iocnumX = khdr.iocnum & 0xFF;
578         if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
579             (iocp == NULL)) {
580                 dctlprintk((KERN_ERR "%s::mptctl_ioctl() @%d - ioc%d not found!\n",
581                                 __FILE__, __LINE__, iocnumX));
582                 return -ENODEV;
583         }
584
585         if (!iocp->active) {
586                 printk(KERN_ERR "%s::mptctl_ioctl() @%d - Controller disabled.\n",
587                                 __FILE__, __LINE__);
588                 return -EFAULT;
589         }
590
591         /* Handle those commands that are just returning
592          * information stored in the driver.
593          * These commands should never time out and are unaffected
594          * by TM and FW reloads.
595          */
596         if ((cmd & ~IOCSIZE_MASK) == (MPTIOCINFO & ~IOCSIZE_MASK)) {
597                 return mptctl_getiocinfo(arg, _IOC_SIZE(cmd));
598         } else if (cmd == MPTTARGETINFO) {
599                 return mptctl_gettargetinfo(arg);
600         } else if (cmd == MPTTEST) {
601                 return mptctl_readtest(arg);
602         } else if (cmd == MPTEVENTQUERY) {
603                 return mptctl_eventquery(arg);
604         } else if (cmd == MPTEVENTENABLE) {
605                 return mptctl_eventenable(arg);
606         } else if (cmd == MPTEVENTREPORT) {
607                 return mptctl_eventreport(arg);
608         } else if (cmd == MPTFWREPLACE) {
609                 return mptctl_replace_fw(arg);
610         }
611
612         /* All of these commands require an interrupt or
613          * are unknown/illegal.
614          */
615         if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
616                 return ret;
617
618         dctlprintk((MYIOC_s_INFO_FMT ": mptctl_ioctl()\n", iocp->name));
619
620         if (cmd == MPTFWDOWNLOAD)
621                 ret = mptctl_fw_download(arg);
622         else if (cmd == MPTCOMMAND)
623                 ret = mptctl_mpt_command(arg);
624         else if (cmd == MPTHARDRESET)
625                 ret = mptctl_do_reset(arg);
626         else if ((cmd & ~IOCSIZE_MASK) == (HP_GETHOSTINFO & ~IOCSIZE_MASK))
627                 ret = mptctl_hp_hostinfo(arg, _IOC_SIZE(cmd));
628         else if (cmd == HP_GETTARGETINFO)
629                 ret = mptctl_hp_targetinfo(arg);
630         else
631                 ret = -EINVAL;
632
633
634         up(&mptctl_syscall_sem_ioc[iocp->id]);
635
636         return ret;
637 }
638
639 static int mptctl_do_reset(unsigned long arg)
640 {
641         struct mpt_ioctl_diag_reset __user *urinfo = (void __user *) arg;
642         struct mpt_ioctl_diag_reset krinfo;
643         MPT_ADAPTER             *iocp;
644
645         dctlprintk((KERN_INFO "mptctl_do_reset called.\n"));
646
647         if (copy_from_user(&krinfo, urinfo, sizeof(struct mpt_ioctl_diag_reset))) {
648                 printk(KERN_ERR "%s@%d::mptctl_do_reset - "
649                                 "Unable to copy mpt_ioctl_diag_reset struct @ %p\n",
650                                 __FILE__, __LINE__, urinfo);
651                 return -EFAULT;
652         }
653
654         if (mpt_verify_adapter(krinfo.hdr.iocnum, &iocp) < 0) {
655                 dctlprintk((KERN_ERR "%s@%d::mptctl_do_reset - ioc%d not found!\n",
656                                 __FILE__, __LINE__, krinfo.hdr.iocnum));
657                 return -ENODEV; /* (-6) No such device or address */
658         }
659
660         if (mpt_HardResetHandler(iocp, CAN_SLEEP) != 0) {
661                 printk (KERN_ERR "%s@%d::mptctl_do_reset - reset failed.\n",
662                         __FILE__, __LINE__);
663                 return -1;
664         }
665
666         return 0;
667 }
668
669 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
670 /*
671  * MPT FW download function.  Cast the arg into the mpt_fw_xfer structure.
672  * This structure contains: iocnum, firmware length (bytes),
673  *      pointer to user space memory where the fw image is stored.
674  *
675  * Outputs:     None.
676  * Return:      0 if successful
677  *              -EFAULT if data unavailable
678  *              -ENXIO  if no such device
679  *              -EAGAIN if resource problem
680  *              -ENOMEM if no memory for SGE
681  *              -EMLINK if too many chain buffers required
682  *              -EBADRQC if adapter does not support FW download
683  *              -EBUSY if adapter is busy
684  *              -ENOMSG if FW upload returned bad status
685  */
686 static int
687 mptctl_fw_download(unsigned long arg)
688 {
689         struct mpt_fw_xfer __user *ufwdl = (void __user *) arg;
690         struct mpt_fw_xfer       kfwdl;
691
692         dctlprintk((KERN_INFO "mptctl_fwdl called. mptctl_id = %xh\n", mptctl_id)); //tc
693         if (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {
694                 printk(KERN_ERR "%s@%d::_ioctl_fwdl - "
695                                 "Unable to copy mpt_fw_xfer struct @ %p\n",
696                                 __FILE__, __LINE__, ufwdl);
697                 return -EFAULT;
698         }
699
700         return mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);
701 }
702
703 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
704 /*
705  * FW Download engine.
706  * Outputs:     None.
707  * Return:      0 if successful
708  *              -EFAULT if data unavailable
709  *              -ENXIO  if no such device
710  *              -EAGAIN if resource problem
711  *              -ENOMEM if no memory for SGE
712  *              -EMLINK if too many chain buffers required
713  *              -EBADRQC if adapter does not support FW download
714  *              -EBUSY if adapter is busy
715  *              -ENOMSG if FW upload returned bad status
716  */
717 static int
718 mptctl_do_fw_download(int ioc, char __user *ufwbuf, size_t fwlen)
719 {
720         FWDownload_t            *dlmsg;
721         MPT_FRAME_HDR           *mf;
722         MPT_ADAPTER             *iocp;
723         FWDownloadTCSGE_t       *ptsge;
724         MptSge_t                *sgl, *sgIn;
725         char                    *sgOut;
726         struct buflist          *buflist;
727         struct buflist          *bl;
728         dma_addr_t               sgl_dma;
729         int                      ret;
730         int                      numfrags = 0;
731         int                      maxfrags;
732         int                      n = 0;
733         u32                      sgdir;
734         u32                      nib;
735         int                      fw_bytes_copied = 0;
736         int                      i;
737         int                      cntdn;
738         int                      sge_offset = 0;
739         u16                      iocstat;
740
741         dctlprintk((KERN_INFO "mptctl_do_fwdl called. mptctl_id = %xh.\n", mptctl_id));
742
743         dctlprintk((KERN_INFO "DbG: kfwdl.bufp  = %p\n", ufwbuf));
744         dctlprintk((KERN_INFO "DbG: kfwdl.fwlen = %d\n", (int)fwlen));
745         dctlprintk((KERN_INFO "DbG: kfwdl.ioc   = %04xh\n", ioc));
746
747         if ((ioc = mpt_verify_adapter(ioc, &iocp)) < 0) {
748                 dctlprintk(("%s@%d::_ioctl_fwdl - ioc%d not found!\n",
749                                 __FILE__, __LINE__, ioc));
750                 return -ENODEV; /* (-6) No such device or address */
751         }
752
753         /*  Valid device. Get a message frame and construct the FW download message.
754          */
755         if ((mf = mpt_get_msg_frame(mptctl_id, iocp)) == NULL)
756                 return -EAGAIN;
757         dlmsg = (FWDownload_t*) mf;
758         ptsge = (FWDownloadTCSGE_t *) &dlmsg->SGL;
759         sgOut = (char *) (ptsge + 1);
760
761         /*
762          * Construct f/w download request
763          */
764         dlmsg->ImageType = MPI_FW_DOWNLOAD_ITYPE_FW;
765         dlmsg->Reserved = 0;
766         dlmsg->ChainOffset = 0;
767         dlmsg->Function = MPI_FUNCTION_FW_DOWNLOAD;
768         dlmsg->Reserved1[0] = dlmsg->Reserved1[1] = dlmsg->Reserved1[2] = 0;
769         dlmsg->MsgFlags = 0;
770
771         /* Set up the Transaction SGE.
772          */
773         ptsge->Reserved = 0;
774         ptsge->ContextSize = 0;
775         ptsge->DetailsLength = 12;
776         ptsge->Flags = MPI_SGE_FLAGS_TRANSACTION_ELEMENT;
777         ptsge->Reserved_0100_Checksum = 0;
778         ptsge->ImageOffset = 0;
779         ptsge->ImageSize = cpu_to_le32(fwlen);
780
781         /* Add the SGL
782          */
783
784         /*
785          * Need to kmalloc area(s) for holding firmware image bytes.
786          * But we need to do it piece meal, using a proper
787          * scatter gather list (with 128kB MAX hunks).
788          *
789          * A practical limit here might be # of sg hunks that fit into
790          * a single IOC request frame; 12 or 8 (see below), so:
791          * For FC9xx: 12 x 128kB == 1.5 mB (max)
792          * For C1030:  8 x 128kB == 1   mB (max)
793          * We could support chaining, but things get ugly(ier:)
794          *
795          * Set the sge_offset to the start of the sgl (bytes).
796          */
797         sgdir = 0x04000000;             /* IOC will READ from sys mem */
798         sge_offset = sizeof(MPIHeader_t) + sizeof(FWDownloadTCSGE_t);
799         if ((sgl = kbuf_alloc_2_sgl(fwlen, sgdir, sge_offset,
800                                     &numfrags, &buflist, &sgl_dma, iocp)) == NULL)
801                 return -ENOMEM;
802
803         /*
804          * We should only need SGL with 2 simple_32bit entries (up to 256 kB)
805          * for FC9xx f/w image, but calculate max number of sge hunks
806          * we can fit into a request frame, and limit ourselves to that.
807          * (currently no chain support)
808          * maxfrags = (Request Size - FWdownload Size ) / Size of 32 bit SGE
809          *      Request         maxfrags
810          *      128             12
811          *      96              8
812          *      64              4
813          */
814         maxfrags = (iocp->req_sz - sizeof(MPIHeader_t) - sizeof(FWDownloadTCSGE_t))
815                         / (sizeof(dma_addr_t) + sizeof(u32));
816         if (numfrags > maxfrags) {
817                 ret = -EMLINK;
818                 goto fwdl_out;
819         }
820
821         dctlprintk((KERN_INFO "DbG: sgl buffer  = %p, sgfrags = %d\n", sgl, numfrags));
822
823         /*
824          * Parse SG list, copying sgl itself,
825          * plus f/w image hunks from user space as we go...
826          */
827         ret = -EFAULT;
828         sgIn = sgl;
829         bl = buflist;
830         for (i=0; i < numfrags; i++) {
831
832                 /* Get the SGE type: 0 - TCSGE, 3 - Chain, 1 - Simple SGE
833                  * Skip everything but Simple. If simple, copy from
834                  *      user space into kernel space.
835                  * Note: we should not have anything but Simple as
836                  *      Chain SGE are illegal.
837                  */
838                 nib = (sgIn->FlagsLength & 0x30000000) >> 28;
839                 if (nib == 0 || nib == 3) {
840                         ;
841                 } else if (sgIn->Address) {
842                         mpt_add_sge(sgOut, sgIn->FlagsLength, sgIn->Address);
843                         n++;
844                         if (copy_from_user(bl->kptr, ufwbuf+fw_bytes_copied, bl->len)) {
845                                 printk(KERN_ERR "%s@%d::_ioctl_fwdl - "
846                                                 "Unable to copy f/w buffer hunk#%d @ %p\n",
847                                                 __FILE__, __LINE__, n, ufwbuf);
848                                 goto fwdl_out;
849                         }
850                         fw_bytes_copied += bl->len;
851                 }
852                 sgIn++;
853                 bl++;
854                 sgOut += (sizeof(dma_addr_t) + sizeof(u32));
855         }
856
857 #ifdef MPT_DEBUG
858         {
859                 u32 *m = (u32 *)mf;
860                 printk(KERN_INFO MYNAM ": F/W download request:\n" KERN_INFO " ");
861                 for (i=0; i < 7+numfrags*2; i++)
862                         printk(" %08x", le32_to_cpu(m[i]));
863                 printk("\n");
864         }
865 #endif
866
867         /*
868          * Finally, perform firmware download.
869          */
870         ReplyMsg = NULL;
871         mpt_put_msg_frame(mptctl_id, iocp, mf);
872
873         /*
874          *  Wait until the reply has been received
875          */
876         for (cntdn=HZ*60, i=1; ReplyMsg == NULL; cntdn--, i++) {
877                 if (!cntdn) {
878                         ret = -ETIME;
879                         goto fwdl_out;
880                 }
881
882                 if (!(i%HZ)) {
883                         dctlprintk((KERN_INFO "DbG::_do_fwdl: "
884                                    "In ReplyMsg loop - iteration %d\n",
885                                    i));
886                 }
887
888                 set_current_state(TASK_INTERRUPTIBLE);
889                 schedule_timeout(1);
890         }
891
892         if (sgl)
893                 kfree_sgl(sgl, sgl_dma, buflist, iocp);
894
895         iocstat = le16_to_cpu(ReplyMsg->IOCStatus) & MPI_IOCSTATUS_MASK;
896         if (iocstat == MPI_IOCSTATUS_SUCCESS) {
897                 printk(KERN_INFO MYNAM ": F/W update successfully sent to %s!\n", iocp->name);
898                 return 0;
899         } else if (iocstat == MPI_IOCSTATUS_INVALID_FUNCTION) {
900                 printk(KERN_WARNING MYNAM ": ?Hmmm...  %s says it doesn't support F/W download!?!\n",
901                                 iocp->name);
902                 printk(KERN_WARNING MYNAM ": (time to go bang on somebodies door)\n");
903                 return -EBADRQC;
904         } else if (iocstat == MPI_IOCSTATUS_BUSY) {
905                 printk(KERN_WARNING MYNAM ": Warning!  %s says: IOC_BUSY!\n", iocp->name);
906                 printk(KERN_WARNING MYNAM ": (try again later?)\n");
907                 return -EBUSY;
908         } else {
909                 printk(KERN_WARNING MYNAM "::ioctl_fwdl() ERROR!  %s returned [bad] status = %04xh\n",
910                                     iocp->name, iocstat);
911                 printk(KERN_WARNING MYNAM ": (bad VooDoo)\n");
912                 return -ENOMSG;
913         }
914         return 0;
915
916 fwdl_out:
917         kfree_sgl(sgl, sgl_dma, buflist, iocp);
918         return ret;
919 }
920
921 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
922 /*
923  * SGE Allocation routine
924  *
925  * Inputs:      bytes - number of bytes to be transferred
926  *              sgdir - data direction
927  *              sge_offset - offset (in bytes) from the start of the request
928  *                      frame to the first SGE
929  *              ioc - pointer to the mptadapter
930  * Outputs:     frags - number of scatter gather elements
931  *              blp - point to the buflist pointer
932  *              sglbuf_dma - pointer to the (dma) sgl
933  * Returns:     Null if failes
934  *              pointer to the (virtual) sgl if successful.
935  */
936 static MptSge_t *
937 kbuf_alloc_2_sgl(int bytes, u32 sgdir, int sge_offset, int *frags,
938                  struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc)
939 {
940         MptSge_t        *sglbuf = NULL;         /* pointer to array of SGE */
941                                                 /* and chain buffers */
942         struct buflist  *buflist = NULL;        /* kernel routine */
943         MptSge_t        *sgl;
944         int              numfrags = 0;
945         int              fragcnt = 0;
946         int              alloc_sz = min(bytes,MAX_KMALLOC_SZ);  // avoid kernel warning msg!
947         int              bytes_allocd = 0;
948         int              this_alloc;
949         dma_addr_t       pa;                                    // phys addr
950         int              i, buflist_ent;
951         int              sg_spill = MAX_FRAGS_SPILL1;
952         int              dir;
953         /* initialization */
954         *frags = 0;
955         *blp = NULL;
956
957         /* Allocate and initialize an array of kernel
958          * structures for the SG elements.
959          */
960         i = MAX_SGL_BYTES / 8;
961         buflist = kmalloc(i, GFP_USER);
962         if (buflist == NULL)
963                 return NULL;
964         memset(buflist, 0, i);
965         buflist_ent = 0;
966
967         /* Allocate a single block of memory to store the sg elements and
968          * the chain buffers.  The calling routine is responsible for
969          * copying the data in this array into the correct place in the
970          * request and chain buffers.
971          */
972         sglbuf = pci_alloc_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf_dma);
973         if (sglbuf == NULL)
974                 goto free_and_fail;
975
976         if (sgdir & 0x04000000)
977                 dir = PCI_DMA_TODEVICE;
978         else
979                 dir = PCI_DMA_FROMDEVICE;
980
981         /* At start:
982          *      sgl = sglbuf = point to beginning of sg buffer
983          *      buflist_ent = 0 = first kernel structure
984          *      sg_spill = number of SGE that can be written before the first
985          *              chain element.
986          *
987          */
988         sgl = sglbuf;
989         sg_spill = ((ioc->req_sz - sge_offset)/(sizeof(dma_addr_t) + sizeof(u32))) - 1;
990         while (bytes_allocd < bytes) {
991                 this_alloc = min(alloc_sz, bytes-bytes_allocd);
992                 buflist[buflist_ent].len = this_alloc;
993                 buflist[buflist_ent].kptr = pci_alloc_consistent(ioc->pcidev,
994                                                                  this_alloc,
995                                                                  &pa);
996                 if (buflist[buflist_ent].kptr == NULL) {
997                         alloc_sz = alloc_sz / 2;
998                         if (alloc_sz == 0) {
999                                 printk(KERN_WARNING MYNAM "-SG: No can do - "
1000                                                     "not enough memory!   :-(\n");
1001                                 printk(KERN_WARNING MYNAM "-SG: (freeing %d frags)\n",
1002                                                     numfrags);
1003                                 goto free_and_fail;
1004                         }
1005                         continue;
1006                 } else {
1007                         dma_addr_t dma_addr;
1008
1009                         bytes_allocd += this_alloc;
1010                         sgl->FlagsLength = (0x10000000|MPT_SGE_FLAGS_ADDRESSING|sgdir|this_alloc);
1011                         dma_addr = pci_map_single(ioc->pcidev, buflist[buflist_ent].kptr, this_alloc, dir);
1012                         sgl->Address = dma_addr;
1013
1014                         fragcnt++;
1015                         numfrags++;
1016                         sgl++;
1017                         buflist_ent++;
1018                 }
1019
1020                 if (bytes_allocd >= bytes)
1021                         break;
1022
1023                 /* Need to chain? */
1024                 if (fragcnt == sg_spill) {
1025                         printk(KERN_WARNING MYNAM "-SG: No can do - " "Chain required!   :-(\n");
1026                         printk(KERN_WARNING MYNAM "(freeing %d frags)\n", numfrags);
1027                         goto free_and_fail;
1028                 }
1029
1030                 /* overflow check... */
1031                 if (numfrags*8 > MAX_SGL_BYTES){
1032                         /* GRRRRR... */
1033                         printk(KERN_WARNING MYNAM "-SG: No can do - "
1034                                             "too many SG frags!   :-(\n");
1035                         printk(KERN_WARNING MYNAM "-SG: (freeing %d frags)\n",
1036                                             numfrags);
1037                         goto free_and_fail;
1038                 }
1039         }
1040
1041         /* Last sge fixup: set LE+eol+eob bits */
1042         sgl[-1].FlagsLength |= 0xC1000000;
1043
1044         *frags = numfrags;
1045         *blp = buflist;
1046
1047         dctlprintk((KERN_INFO MYNAM "-SG: kbuf_alloc_2_sgl() - "
1048                            "%d SG frags generated!\n",
1049                            numfrags));
1050
1051         dctlprintk((KERN_INFO MYNAM "-SG: kbuf_alloc_2_sgl() - "
1052                            "last (big) alloc_sz=%d\n",
1053                            alloc_sz));
1054
1055         return sglbuf;
1056
1057 free_and_fail:
1058         if (sglbuf != NULL) {
1059                 int i;
1060
1061                 for (i = 0; i < numfrags; i++) {
1062                         dma_addr_t dma_addr;
1063                         u8 *kptr;
1064                         int len;
1065
1066                         if ((sglbuf[i].FlagsLength >> 24) == 0x30)
1067                                 continue;
1068
1069                         dma_addr = sglbuf[i].Address;
1070                         kptr = buflist[i].kptr;
1071                         len = buflist[i].len;
1072
1073                         pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
1074                 }
1075                 pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf, *sglbuf_dma);
1076         }
1077         kfree(buflist);
1078         return NULL;
1079 }
1080
1081 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1082 /*
1083  * Routine to free the SGL elements.
1084  */
1085 static void
1086 kfree_sgl(MptSge_t *sgl, dma_addr_t sgl_dma, struct buflist *buflist, MPT_ADAPTER *ioc)
1087 {
1088         MptSge_t        *sg = sgl;
1089         struct buflist  *bl = buflist;
1090         u32              nib;
1091         int              dir;
1092         int              n = 0;
1093
1094         if (sg->FlagsLength & 0x04000000)
1095                 dir = PCI_DMA_TODEVICE;
1096         else
1097                 dir = PCI_DMA_FROMDEVICE;
1098
1099         nib = (sg->FlagsLength & 0xF0000000) >> 28;
1100         while (! (nib & 0x4)) { /* eob */
1101                 /* skip ignore/chain. */
1102                 if (nib == 0 || nib == 3) {
1103                         ;
1104                 } else if (sg->Address) {
1105                         dma_addr_t dma_addr;
1106                         void *kptr;
1107                         int len;
1108
1109                         dma_addr = sg->Address;
1110                         kptr = bl->kptr;
1111                         len = bl->len;
1112                         pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
1113                         pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
1114                         n++;
1115                 }
1116                 sg++;
1117                 bl++;
1118                 nib = (le32_to_cpu(sg->FlagsLength) & 0xF0000000) >> 28;
1119         }
1120
1121         /* we're at eob! */
1122         if (sg->Address) {
1123                 dma_addr_t dma_addr;
1124                 void *kptr;
1125                 int len;
1126
1127                 dma_addr = sg->Address;
1128                 kptr = bl->kptr;
1129                 len = bl->len;
1130                 pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
1131                 pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
1132                 n++;
1133         }
1134
1135         pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sgl, sgl_dma);
1136         kfree(buflist);
1137         dctlprintk((KERN_INFO MYNAM "-SG: Free'd 1 SGL buf + %d kbufs!\n", n));
1138 }
1139
1140 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1141 /*
1142  *      mptctl_getiocinfo - Query the host adapter for IOC information.
1143  *      @arg: User space argument
1144  *
1145  * Outputs:     None.
1146  * Return:      0 if successful
1147  *              -EFAULT if data unavailable
1148  *              -ENODEV  if no such device/adapter
1149  */
1150 static int
1151 mptctl_getiocinfo (unsigned long arg, unsigned int data_size)
1152 {
1153         struct mpt_ioctl_iocinfo __user *uarg = (void __user *) arg;
1154         struct mpt_ioctl_iocinfo *karg;
1155         MPT_ADAPTER             *ioc;
1156         struct pci_dev          *pdev;
1157         struct Scsi_Host        *sh;
1158         MPT_SCSI_HOST           *hd;
1159         int                     iocnum;
1160         int                     numDevices = 0;
1161         unsigned int            max_id;
1162         int                     ii;
1163         int                     port;
1164         int                     cim_rev;
1165         u8                      revision;
1166
1167         dctlprintk((": mptctl_getiocinfo called.\n"));
1168         /* Add of PCI INFO results in unaligned access for
1169          * IA64 and Sparc. Reset long to int. Return no PCI
1170          * data for obsolete format.
1171          */
1172         if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev0))
1173                 cim_rev = 0;
1174         else if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev1))
1175                 cim_rev = 1;
1176         else if (data_size == sizeof(struct mpt_ioctl_iocinfo))
1177                 cim_rev = 2;
1178         else if (data_size == (sizeof(struct mpt_ioctl_iocinfo_rev0)+12))
1179                 cim_rev = 0;    /* obsolete */
1180         else
1181                 return -EFAULT;
1182         
1183         karg = kmalloc(data_size, GFP_KERNEL);
1184         if (karg == NULL) {
1185                 printk(KERN_ERR "%s::mpt_ioctl_iocinfo() @%d - no memory available!\n",
1186                                 __FILE__, __LINE__);
1187                 return -ENOMEM;
1188         }
1189                 
1190         if (copy_from_user(karg, uarg, data_size)) {
1191                 printk(KERN_ERR "%s@%d::mptctl_getiocinfo - "
1192                         "Unable to read in mpt_ioctl_iocinfo struct @ %p\n",
1193                                 __FILE__, __LINE__, uarg);
1194                 kfree(karg);
1195                 return -EFAULT;
1196         }
1197
1198         if (((iocnum = mpt_verify_adapter(karg->hdr.iocnum, &ioc)) < 0) ||
1199             (ioc == NULL)) {
1200                 dctlprintk((KERN_ERR "%s::mptctl_getiocinfo() @%d - ioc%d not found!\n",
1201                                 __FILE__, __LINE__, iocnum));
1202                 kfree(karg);
1203                 return -ENODEV;
1204         }
1205
1206         /* Verify the data transfer size is correct.
1207          * Ignore the port setting.
1208          */
1209         if (karg->hdr.maxDataSize != data_size) {
1210                 printk(KERN_ERR "%s@%d::mptctl_getiocinfo - "
1211                         "Structure size mismatch. Command not completed.\n",
1212                                 __FILE__, __LINE__);
1213                 kfree(karg);
1214                 return -EFAULT;
1215         }
1216
1217         /* Fill in the data and return the structure to the calling
1218          * program
1219          */
1220         if ((int)ioc->chip_type <= (int) FC929)
1221                 karg->adapterType = MPT_IOCTL_INTERFACE_FC;
1222         else
1223                 karg->adapterType = MPT_IOCTL_INTERFACE_SCSI;
1224
1225         port = karg->hdr.port;
1226
1227         karg->port = port;
1228         pdev = (struct pci_dev *) ioc->pcidev;
1229
1230         karg->pciId = pdev->device;
1231         pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
1232         karg->hwRev = revision;
1233         karg->subSystemDevice = pdev->subsystem_device;
1234         karg->subSystemVendor = pdev->subsystem_vendor;
1235
1236         if (cim_rev == 1) {
1237                 /* Get the PCI bus, device, and function numbers for the IOC
1238                  */
1239                 karg->pciInfo.u.bits.busNumber = pdev->bus->number;
1240                 karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
1241                 karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
1242         } else if (cim_rev == 2) {
1243                 /* Get the PCI bus, device, function and segment ID numbers 
1244                    for the IOC */
1245                 karg->pciInfo.u.bits.busNumber = pdev->bus->number;
1246                 karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
1247                 karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
1248                 karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
1249                 karg->pciInfo.segmentID = pci_domain_nr(pdev->bus);
1250         }
1251
1252         /* Get number of devices
1253          */
1254         if ((sh = ioc->sh) != NULL) {
1255                  /* sh->max_id = maximum target ID + 1
1256                  */
1257                 max_id = sh->max_id - 1;
1258                 hd = (MPT_SCSI_HOST *) sh->hostdata;
1259
1260                 /* Check all of the target structures and
1261                  * keep a counter.
1262                  */
1263                 if (hd && hd->Targets) {
1264                         for (ii = 0; ii <= max_id; ii++) {
1265                                 if (hd->Targets[ii])
1266                                         numDevices++;
1267                         }
1268                 }
1269         }
1270         karg->numDevices = numDevices;
1271
1272         /* Set the BIOS and FW Version
1273          */
1274         karg->FWVersion = ioc->facts.FWVersion.Word;
1275         karg->BIOSVersion = ioc->biosVersion;
1276
1277         /* Set the Version Strings.
1278          */
1279         strncpy (karg->driverVersion, MPT_LINUX_PACKAGE_NAME, MPT_IOCTL_VERSION_LENGTH);
1280         karg->driverVersion[MPT_IOCTL_VERSION_LENGTH-1]='\0';
1281
1282         karg->busChangeEvent = 0;
1283         karg->hostId = ioc->pfacts[port].PortSCSIID;
1284         karg->rsvd[0] = karg->rsvd[1] = 0;
1285
1286         /* Copy the data from kernel memory to user memory
1287          */
1288         if (copy_to_user((char __user *)arg, karg, data_size)) {
1289                 printk(KERN_ERR "%s@%d::mptctl_getiocinfo - "
1290                         "Unable to write out mpt_ioctl_iocinfo struct @ %p\n",
1291                                 __FILE__, __LINE__, uarg);
1292                 kfree(karg);
1293                 return -EFAULT;
1294         }
1295
1296         kfree(karg);
1297         return 0;
1298 }
1299
1300 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1301 /*
1302  *      mptctl_gettargetinfo - Query the host adapter for target information.
1303  *      @arg: User space argument
1304  *
1305  * Outputs:     None.
1306  * Return:      0 if successful
1307  *              -EFAULT if data unavailable
1308  *              -ENODEV  if no such device/adapter
1309  */
1310 static int
1311 mptctl_gettargetinfo (unsigned long arg)
1312 {
1313         struct mpt_ioctl_targetinfo __user *uarg = (void __user *) arg;
1314         struct mpt_ioctl_targetinfo karg;
1315         MPT_ADAPTER             *ioc;
1316         struct Scsi_Host        *sh;
1317         MPT_SCSI_HOST           *hd;
1318         VirtDevice              *vdev;
1319         char                    *pmem;
1320         int                     *pdata;
1321         IOCPage2_t              *pIoc2;
1322         IOCPage3_t              *pIoc3;
1323         int                     iocnum;
1324         int                     numDevices = 0;
1325         unsigned int            max_id;
1326         int                     id, jj, indexed_lun, lun_index;
1327         u32                     lun;
1328         int                     maxWordsLeft;
1329         int                     numBytes;
1330         u8                      port, devType, bus_id;
1331
1332         dctlprintk(("mptctl_gettargetinfo called.\n"));
1333         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_targetinfo))) {
1334                 printk(KERN_ERR "%s@%d::mptctl_gettargetinfo - "
1335                         "Unable to read in mpt_ioctl_targetinfo struct @ %p\n",
1336                                 __FILE__, __LINE__, uarg);
1337                 return -EFAULT;
1338         }
1339
1340         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1341             (ioc == NULL)) {
1342                 dctlprintk((KERN_ERR "%s::mptctl_gettargetinfo() @%d - ioc%d not found!\n",
1343                                 __FILE__, __LINE__, iocnum));
1344                 return -ENODEV;
1345         }
1346
1347         /* Get the port number and set the maximum number of bytes
1348          * in the returned structure.
1349          * Ignore the port setting.
1350          */
1351         numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
1352         maxWordsLeft = numBytes/sizeof(int);
1353         port = karg.hdr.port;
1354
1355         if (maxWordsLeft <= 0) {
1356                 printk(KERN_ERR "%s::mptctl_gettargetinfo() @%d - no memory available!\n",
1357                                 __FILE__, __LINE__);
1358                 return -ENOMEM;
1359         }
1360
1361         /* Fill in the data and return the structure to the calling
1362          * program
1363          */
1364
1365         /* struct mpt_ioctl_targetinfo does not contain sufficient space
1366          * for the target structures so when the IOCTL is called, there is
1367          * not sufficient stack space for the structure. Allocate memory,
1368          * populate the memory, copy back to the user, then free memory.
1369          * targetInfo format:
1370          * bits 31-24: reserved
1371          *      23-16: LUN
1372          *      15- 8: Bus Number
1373          *       7- 0: Target ID
1374          */
1375         pmem = kmalloc(numBytes, GFP_KERNEL);
1376         if (pmem == NULL) {
1377                 printk(KERN_ERR "%s::mptctl_gettargetinfo() @%d - no memory available!\n",
1378                                 __FILE__, __LINE__);
1379                 return -ENOMEM;
1380         }
1381         memset(pmem, 0, numBytes);
1382         pdata =  (int *) pmem;
1383
1384         /* Get number of devices
1385          */
1386         if ((sh = ioc->sh) != NULL) {
1387
1388                 max_id = sh->max_id - 1;
1389                 hd = (MPT_SCSI_HOST *) sh->hostdata;
1390
1391                 /* Check all of the target structures.
1392                  * Save the Id and increment the counter,
1393                  * if ptr non-null.
1394                  * sh->max_id = maximum target ID + 1
1395                  */
1396                 if (hd && hd->Targets) {
1397                         mpt_findImVolumes(ioc);
1398                         pIoc2 = ioc->spi_data.pIocPg2;
1399                         for ( id = 0; id <= max_id; ) {
1400                                 if ( pIoc2 && pIoc2->NumActiveVolumes ) {
1401                                         if ( id == pIoc2->RaidVolume[0].VolumeID ) {
1402                                                 if (maxWordsLeft <= 0) {
1403                                                         printk(KERN_ERR "mptctl_gettargetinfo - "
1404                         "buffer is full but volume is available on ioc %d\n, numDevices=%d", iocnum, numDevices);
1405                                                         goto data_space_full;
1406                                                 }
1407                                                 if ( ( pIoc2->RaidVolume[0].Flags & MPI_IOCPAGE2_FLAG_VOLUME_INACTIVE ) == 0 )
1408                                                         devType = 0x80;
1409                                                 else
1410                                                         devType = 0xC0;
1411                                                 bus_id = pIoc2->RaidVolume[0].VolumeBus;
1412                                                 numDevices++;
1413                                                 *pdata = ( (devType << 24) | (bus_id << 8) | id );
1414                                                 dctlprintk((KERN_ERR "mptctl_gettargetinfo - "
1415                 "volume ioc=%d target=%x numDevices=%d pdata=%p\n", iocnum, *pdata, numDevices, pdata));
1416                                                 pdata++;
1417                                                 --maxWordsLeft;
1418                                                 goto next_id;
1419                                         } else {
1420                                                 pIoc3 = ioc->spi_data.pIocPg3;
1421                                                 for ( jj = 0; jj < pIoc3->NumPhysDisks; jj++ ) {
1422                                                         if ( pIoc3->PhysDisk[jj].PhysDiskID == id )
1423                                                                 goto next_id;
1424                                                 }
1425                                         }
1426                                 }
1427                                 if ( (vdev = hd->Targets[id]) ) {
1428                                         for (jj = 0; jj <= MPT_LAST_LUN; jj++) {
1429                                                 lun_index = (jj >> 5);
1430                                                 indexed_lun = (jj % 32);
1431                                                 lun = (1 << indexed_lun);
1432                                                 if (vdev->luns[lun_index] & lun) {
1433                                                         if (maxWordsLeft <= 0) {
1434                                                                 printk(KERN_ERR "mptctl_gettargetinfo - "
1435                         "buffer is full but more targets are available on ioc %d numDevices=%d\n", iocnum, numDevices);
1436                                                                 goto data_space_full;
1437                                                         }
1438                                                         bus_id = vdev->bus_id;
1439                                                         numDevices++;
1440                                                         *pdata = ( (jj << 16) | (bus_id << 8) | id );
1441                                                         dctlprintk((KERN_ERR "mptctl_gettargetinfo - "
1442                 "target ioc=%d target=%x numDevices=%d pdata=%p\n", iocnum, *pdata, numDevices, pdata));
1443                                                         pdata++;
1444                                                         --maxWordsLeft;
1445                                                 }
1446                                         }
1447                                 }
1448 next_id:
1449                                 id++;
1450                         }
1451                 }
1452         }
1453 data_space_full:
1454         karg.numDevices = numDevices;
1455
1456         /* Copy part of the data from kernel memory to user memory
1457          */
1458         if (copy_to_user((char __user *)arg, &karg,
1459                                 sizeof(struct mpt_ioctl_targetinfo))) {
1460                 printk(KERN_ERR "%s@%d::mptctl_gettargetinfo - "
1461                         "Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
1462                                 __FILE__, __LINE__, uarg);
1463                 kfree(pmem);
1464                 return -EFAULT;
1465         }
1466
1467         /* Copy the remaining data from kernel memory to user memory
1468          */
1469         if (copy_to_user(uarg->targetInfo, pmem, numBytes)) {
1470                 printk(KERN_ERR "%s@%d::mptctl_gettargetinfo - "
1471                         "Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
1472                                 __FILE__, __LINE__, pdata);
1473                 kfree(pmem);
1474                 return -EFAULT;
1475         }
1476
1477         kfree(pmem);
1478
1479         return 0;
1480 }
1481
1482 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1483 /* MPT IOCTL Test function.
1484  *
1485  * Outputs:     None.
1486  * Return:      0 if successful
1487  *              -EFAULT if data unavailable
1488  *              -ENODEV  if no such device/adapter
1489  */
1490 static int
1491 mptctl_readtest (unsigned long arg)
1492 {
1493         struct mpt_ioctl_test __user *uarg = (void __user *) arg;
1494         struct mpt_ioctl_test    karg;
1495         MPT_ADAPTER *ioc;
1496         int iocnum;
1497
1498         dctlprintk(("mptctl_readtest called.\n"));
1499         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {
1500                 printk(KERN_ERR "%s@%d::mptctl_readtest - "
1501                         "Unable to read in mpt_ioctl_test struct @ %p\n",
1502                                 __FILE__, __LINE__, uarg);
1503                 return -EFAULT;
1504         }
1505
1506         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1507             (ioc == NULL)) {
1508                 dctlprintk((KERN_ERR "%s::mptctl_readtest() @%d - ioc%d not found!\n",
1509                                 __FILE__, __LINE__, iocnum));
1510                 return -ENODEV;
1511         }
1512
1513         /* Fill in the data and return the structure to the calling
1514          * program
1515          */
1516
1517 #ifdef MFCNT
1518         karg.chip_type = ioc->mfcnt;
1519 #else
1520         karg.chip_type = ioc->chip_type;
1521 #endif
1522         strncpy (karg.name, ioc->name, MPT_MAX_NAME);
1523         karg.name[MPT_MAX_NAME-1]='\0';
1524         strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);
1525         karg.product[MPT_PRODUCT_LENGTH-1]='\0';
1526
1527         /* Copy the data from kernel memory to user memory
1528          */
1529         if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) {
1530                 printk(KERN_ERR "%s@%d::mptctl_readtest - "
1531                         "Unable to write out mpt_ioctl_test struct @ %p\n",
1532                                 __FILE__, __LINE__, uarg);
1533                 return -EFAULT;
1534         }
1535
1536         return 0;
1537 }
1538
1539 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1540 /*
1541  *      mptctl_eventquery - Query the host adapter for the event types
1542  *      that are being logged.
1543  *      @arg: User space argument
1544  *
1545  * Outputs:     None.
1546  * Return:      0 if successful
1547  *              -EFAULT if data unavailable
1548  *              -ENODEV  if no such device/adapter
1549  */
1550 static int
1551 mptctl_eventquery (unsigned long arg)
1552 {
1553         struct mpt_ioctl_eventquery __user *uarg = (void __user *) arg;
1554         struct mpt_ioctl_eventquery      karg;
1555         MPT_ADAPTER *ioc;
1556         int iocnum;
1557
1558         dctlprintk(("mptctl_eventquery called.\n"));
1559         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {
1560                 printk(KERN_ERR "%s@%d::mptctl_eventquery - "
1561                         "Unable to read in mpt_ioctl_eventquery struct @ %p\n",
1562                                 __FILE__, __LINE__, uarg);
1563                 return -EFAULT;
1564         }
1565
1566         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1567             (ioc == NULL)) {
1568                 dctlprintk((KERN_ERR "%s::mptctl_eventquery() @%d - ioc%d not found!\n",
1569                                 __FILE__, __LINE__, iocnum));
1570                 return -ENODEV;
1571         }
1572
1573         karg.eventEntries = ioc->eventLogSize;
1574         karg.eventTypes = ioc->eventTypes;
1575
1576         /* Copy the data from kernel memory to user memory
1577          */
1578         if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {
1579                 printk(KERN_ERR "%s@%d::mptctl_eventquery - "
1580                         "Unable to write out mpt_ioctl_eventquery struct @ %p\n",
1581                                 __FILE__, __LINE__, uarg);
1582                 return -EFAULT;
1583         }
1584         return 0;
1585 }
1586
1587 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1588 static int
1589 mptctl_eventenable (unsigned long arg)
1590 {
1591         struct mpt_ioctl_eventenable __user *uarg = (void __user *) arg;
1592         struct mpt_ioctl_eventenable     karg;
1593         MPT_ADAPTER *ioc;
1594         int iocnum;
1595
1596         dctlprintk(("mptctl_eventenable called.\n"));
1597         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) {
1598                 printk(KERN_ERR "%s@%d::mptctl_eventenable - "
1599                         "Unable to read in mpt_ioctl_eventenable struct @ %p\n",
1600                                 __FILE__, __LINE__, uarg);
1601                 return -EFAULT;
1602         }
1603
1604         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1605             (ioc == NULL)) {
1606                 dctlprintk((KERN_ERR "%s::mptctl_eventenable() @%d - ioc%d not found!\n",
1607                                 __FILE__, __LINE__, iocnum));
1608                 return -ENODEV;
1609         }
1610
1611         if (ioc->events == NULL) {
1612                 /* Have not yet allocated memory - do so now.
1613                  */
1614                 int sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS);
1615                 ioc->events = kmalloc(sz, GFP_KERNEL);
1616                 if (ioc->events == NULL) {
1617                         printk(KERN_ERR MYNAM ": ERROR - Insufficient memory to add adapter!\n");
1618                         return -ENOMEM;
1619                 }
1620                 memset(ioc->events, 0, sz);
1621                 ioc->alloc_total += sz;
1622
1623                 ioc->eventLogSize = MPTCTL_EVENT_LOG_SIZE;
1624                 ioc->eventContext = 0;
1625         }
1626
1627         /* Update the IOC event logging flag.
1628          */
1629         ioc->eventTypes = karg.eventTypes;
1630
1631         return 0;
1632 }
1633
1634 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1635 static int
1636 mptctl_eventreport (unsigned long arg)
1637 {
1638         struct mpt_ioctl_eventreport __user *uarg = (void __user *) arg;
1639         struct mpt_ioctl_eventreport     karg;
1640         MPT_ADAPTER              *ioc;
1641         int                      iocnum;
1642         int                      numBytes, maxEvents, max;
1643
1644         dctlprintk(("mptctl_eventreport called.\n"));
1645         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {
1646                 printk(KERN_ERR "%s@%d::mptctl_eventreport - "
1647                         "Unable to read in mpt_ioctl_eventreport struct @ %p\n",
1648                                 __FILE__, __LINE__, uarg);
1649                 return -EFAULT;
1650         }
1651
1652         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1653             (ioc == NULL)) {
1654                 dctlprintk((KERN_ERR "%s::mptctl_eventreport() @%d - ioc%d not found!\n",
1655                                 __FILE__, __LINE__, iocnum));
1656                 return -ENODEV;
1657         }
1658
1659         numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
1660         maxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);
1661
1662
1663         max = ioc->eventLogSize < maxEvents ? ioc->eventLogSize : maxEvents;
1664
1665         /* If fewer than 1 event is requested, there must have
1666          * been some type of error.
1667          */
1668         if ((max < 1) || !ioc->events)
1669                 return -ENODATA;
1670
1671         /* Copy the data from kernel memory to user memory
1672          */
1673         numBytes = max * sizeof(MPT_IOCTL_EVENTS);
1674         if (copy_to_user(uarg->eventData, ioc->events, numBytes)) {
1675                 printk(KERN_ERR "%s@%d::mptctl_eventreport - "
1676                         "Unable to write out mpt_ioctl_eventreport struct @ %p\n",
1677                                 __FILE__, __LINE__, ioc->events);
1678                 return -EFAULT;
1679         }
1680
1681         return 0;
1682 }
1683
1684 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1685 static int
1686 mptctl_replace_fw (unsigned long arg)
1687 {
1688         struct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg;
1689         struct mpt_ioctl_replace_fw      karg;
1690         MPT_ADAPTER              *ioc;
1691         int                      iocnum;
1692         int                      newFwSize;
1693
1694         dctlprintk(("mptctl_replace_fw called.\n"));
1695         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) {
1696                 printk(KERN_ERR "%s@%d::mptctl_replace_fw - "
1697                         "Unable to read in mpt_ioctl_replace_fw struct @ %p\n",
1698                                 __FILE__, __LINE__, uarg);
1699                 return -EFAULT;
1700         }
1701
1702         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1703             (ioc == NULL)) {
1704                 dctlprintk((KERN_ERR "%s::mptctl_replace_fw() @%d - ioc%d not found!\n",
1705                                 __FILE__, __LINE__, iocnum));
1706                 return -ENODEV;
1707         }
1708
1709         /* If caching FW, Free the old FW image
1710          */
1711         if (ioc->cached_fw == NULL)
1712                 return 0;
1713
1714         mpt_free_fw_memory(ioc);
1715
1716         /* Allocate memory for the new FW image
1717          */
1718         newFwSize = karg.newImageSize;
1719
1720         if (newFwSize & 0x01)
1721                 newFwSize += 1;
1722         if (newFwSize & 0x02)
1723                 newFwSize += 2;
1724
1725         mpt_alloc_fw_memory(ioc, newFwSize);
1726         if (ioc->cached_fw == NULL)
1727                 return -ENOMEM;
1728
1729         /* Copy the data from user memory to kernel space
1730          */
1731         if (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) {
1732                 printk(KERN_ERR "%s@%d::mptctl_replace_fw - "
1733                                 "Unable to read in mpt_ioctl_replace_fw image "
1734                                 "@ %p\n", __FILE__, __LINE__, uarg);
1735                 mpt_free_fw_memory(ioc);
1736                 return -EFAULT;
1737         }
1738
1739         /* Update IOCFactsReply
1740          */
1741         ioc->facts.FWImageSize = newFwSize;
1742         return 0;
1743 }
1744
1745 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1746 /* MPT IOCTL MPTCOMMAND function.
1747  * Cast the arg into the mpt_ioctl_mpt_command structure.
1748  *
1749  * Outputs:     None.
1750  * Return:      0 if successful
1751  *              -EBUSY  if previous command timout and IOC reset is not complete.
1752  *              -EFAULT if data unavailable
1753  *              -ENODEV if no such device/adapter
1754  *              -ETIME  if timer expires
1755  *              -ENOMEM if memory allocation error
1756  */
1757 static int
1758 mptctl_mpt_command (unsigned long arg)
1759 {
1760         struct mpt_ioctl_command __user *uarg = (void __user *) arg;
1761         struct mpt_ioctl_command  karg;
1762         MPT_ADAPTER     *ioc;
1763         int             iocnum;
1764         int             rc;
1765
1766         dctlprintk(("mptctl_command called.\n"));
1767
1768         if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {
1769                 printk(KERN_ERR "%s@%d::mptctl_mpt_command - "
1770                         "Unable to read in mpt_ioctl_command struct @ %p\n",
1771                                 __FILE__, __LINE__, uarg);
1772                 return -EFAULT;
1773         }
1774
1775         if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
1776             (ioc == NULL)) {
1777                 dctlprintk((KERN_ERR "%s::mptctl_mpt_command() @%d - ioc%d not found!\n",
1778                                 __FILE__, __LINE__, iocnum));
1779                 return -ENODEV;
1780         }
1781
1782         rc = mptctl_do_mpt_command (karg, &uarg->MF);
1783
1784         return rc;
1785 }
1786
1787 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1788 /* Worker routine for the IOCTL MPTCOMMAND and MPTCOMMAND32 (sparc) commands.
1789  *
1790  * Outputs:     None.
1791  * Return:      0 if successful
1792  *              -EBUSY  if previous command timout and IOC reset is not complete.
1793  *              -EFAULT if data unavailable
1794  *              -ENODEV if no such device/adapter
1795  *              -ETIME  if timer expires
1796  *              -ENOMEM if memory allocation error
1797  *              -EPERM if SCSI I/O and target is untagged
1798  */
1799 static int
1800 mptctl_do_mpt_command (struct mpt_ioctl_command karg, void __user *mfPtr)
1801 {
1802         MPT_ADAPTER     *ioc;
1803         MPT_FRAME_HDR   *mf = NULL;
1804         MPIHeader_t     *hdr;
1805         char            *psge;
1806         struct buflist  bufIn;  /* data In buffer */
1807         struct buflist  bufOut; /* data Out buffer */
1808         dma_addr_t      dma_addr_in;
1809         dma_addr_t      dma_addr_out;
1810         int             dir;    /* PCI data direction */
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                         dir = PCI_DMA_TODEVICE;
2121                         if (karg.dataInSize > 0) {
2122                                 flagsLength = ( MPI_SGE_FLAGS_SIMPLE_ELEMENT |
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                         dir = PCI_DMA_FROMDEVICE;
2162                         flagsLength = MPT_SGE_FLAGS_SSIMPLE_READ;
2163                         flagsLength |= karg.dataInSize;
2164
2165                         bufIn.len = karg.dataInSize;
2166                         bufIn.kptr = pci_alloc_consistent(ioc->pcidev,
2167                                         bufIn.len, &dma_addr_in);
2168
2169                         if (bufIn.kptr == NULL) {
2170                                 rc = -ENOMEM;
2171                                 goto done_free_mem;
2172                         } else {
2173                                 /* Set up this SGE
2174                                  * Copy to MF and to sglbuf
2175                                  */
2176                                 mpt_add_sge(psge, flagsLength, dma_addr_in);
2177                         }
2178                 }
2179         } else  {
2180                 /* Add a NULL SGE
2181                  */
2182                 mpt_add_sge(psge, flagsLength, (dma_addr_t) -1);
2183         }
2184
2185         /* The request is complete. Set the timer parameters
2186          * and issue the request.
2187          */
2188         if (karg.timeout > 0) {
2189                 ioc->ioctl->timer.expires = jiffies + HZ*karg.timeout;
2190         } else {
2191                 ioc->ioctl->timer.expires = jiffies + HZ*MPT_IOCTL_DEFAULT_TIMEOUT;
2192         }
2193
2194         ioc->ioctl->wait_done = 0;
2195         ioc->ioctl->status |= MPT_IOCTL_STATUS_TIMER_ACTIVE;
2196         add_timer(&ioc->ioctl->timer);
2197
2198         if (hdr->Function == MPI_FUNCTION_SCSI_TASK_MGMT) {
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(mptctl_id, 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(mptctl_id, 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(&mptctl_syscall_sem_ioc[iocp->id]);
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(&mptctl_syscall_sem_ioc[iocp->id]);
2796
2797         return ret;
2798 }
2799
2800 #endif
2801
2802 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2803 int __init mptctl_init(void)
2804 {
2805         int err;
2806         int i;
2807         int where = 1;
2808         int sz;
2809         u8 *mem;
2810         MPT_ADAPTER *ioc = NULL;
2811         int iocnum;
2812
2813         show_mptmod_ver(my_NAME, my_VERSION);
2814
2815         for (i=0; i<MPT_MAX_ADAPTERS; i++) {
2816                 sema_init(&mptctl_syscall_sem_ioc[i], 1);
2817
2818                 ioc = NULL;
2819                 if (((iocnum = mpt_verify_adapter(i, &ioc)) < 0) ||
2820                     (ioc == NULL)) {
2821                         continue;
2822                 }
2823                 else {
2824                         /* This adapter instance is found.
2825                          * Allocate and inite a MPT_IOCTL structure
2826                          */
2827                         sz = sizeof (MPT_IOCTL);
2828                         mem = kmalloc(sz, GFP_KERNEL);
2829                         if (mem == NULL) {
2830                                 err = -ENOMEM;
2831                                 goto out_fail;
2832                         }
2833
2834                         memset(mem, 0, sz);
2835                         ioc->ioctl = (MPT_IOCTL *) mem;
2836                         ioc->ioctl->ioc = ioc;
2837                         init_timer (&ioc->ioctl->timer);
2838                         ioc->ioctl->timer.data = (unsigned long) ioc->ioctl;
2839                         ioc->ioctl->timer.function = mptctl_timer_expired;
2840                         init_timer (&ioc->ioctl->TMtimer);
2841                         ioc->ioctl->TMtimer.data = (unsigned long) ioc->ioctl;
2842                         ioc->ioctl->TMtimer.function = mptctl_timer_expired;
2843                 }
2844         }
2845
2846 #ifdef CONFIG_COMPAT
2847         err = register_ioctl32_conversion(MPTIOCINFO, compat_mptctl_ioctl);
2848         if (++where && err) goto out_fail;
2849         err = register_ioctl32_conversion(MPTIOCINFO1, compat_mptctl_ioctl);
2850         if (++where && err) goto out_fail;
2851         err = register_ioctl32_conversion(MPTIOCINFO2, compat_mptctl_ioctl);
2852         if (++where && err) goto out_fail;
2853         err = register_ioctl32_conversion(MPTTARGETINFO, compat_mptctl_ioctl);
2854         if (++where && err) goto out_fail;
2855         err = register_ioctl32_conversion(MPTTEST, compat_mptctl_ioctl);
2856         if (++where && err) goto out_fail;
2857         err = register_ioctl32_conversion(MPTEVENTQUERY, compat_mptctl_ioctl);
2858         if (++where && err) goto out_fail;
2859         err = register_ioctl32_conversion(MPTEVENTENABLE, compat_mptctl_ioctl);
2860         if (++where && err) goto out_fail;
2861         err = register_ioctl32_conversion(MPTEVENTREPORT, compat_mptctl_ioctl);
2862         if (++where && err) goto out_fail;
2863         err = register_ioctl32_conversion(MPTHARDRESET, compat_mptctl_ioctl);
2864         if (++where && err) goto out_fail;
2865         err = register_ioctl32_conversion(MPTCOMMAND32, compat_mpt_command);
2866         if (++where && err) goto out_fail;
2867         err = register_ioctl32_conversion(MPTFWDOWNLOAD32,
2868                                           compat_mptfwxfer_ioctl);
2869         if (++where && err) goto out_fail;
2870         err = register_ioctl32_conversion(HP_GETHOSTINFO, compat_mptctl_ioctl);
2871         if (++where && err) goto out_fail;
2872         err = register_ioctl32_conversion(HP_GETTARGETINFO, compat_mptctl_ioctl);
2873         if (++where && err) goto out_fail;
2874 #endif
2875
2876         /* Register this device */
2877         err = misc_register(&mptctl_miscdev);
2878         if (err < 0) {
2879                 printk(KERN_ERR MYNAM ": Can't register misc device [minor=%d].\n", MPT_MINOR);
2880                 goto out_fail;
2881         }
2882         printk(KERN_INFO MYNAM ": Registered with Fusion MPT base driver\n");
2883         printk(KERN_INFO MYNAM ": /dev/%s @ (major,minor=%d,%d)\n",
2884                          mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
2885
2886         /*
2887          *  Install our handler
2888          */
2889         ++where;
2890         if ((mptctl_id = mpt_register(mptctl_reply, MPTCTL_DRIVER)) < 0) {
2891                 printk(KERN_ERR MYNAM ": ERROR: Failed to register with Fusion MPT base driver\n");
2892                 misc_deregister(&mptctl_miscdev);
2893                 err = -EBUSY;
2894                 goto out_fail;
2895         }
2896
2897         if (mpt_reset_register(mptctl_id, mptctl_ioc_reset) == 0) {
2898                 dprintk((KERN_INFO MYNAM ": Registered for IOC reset notifications\n"));
2899         } else {
2900                 /* FIXME! */
2901         }
2902
2903         return 0;
2904
2905 out_fail:
2906
2907 #ifdef CONFIG_COMPAT
2908         printk(KERN_ERR MYNAM ": ERROR: Failed to register ioctl32_conversion!"
2909                         " (%d:err=%d)\n", where, err);
2910         unregister_ioctl32_conversion(MPTIOCINFO);
2911         unregister_ioctl32_conversion(MPTIOCINFO1);
2912         unregister_ioctl32_conversion(MPTIOCINFO2);
2913         unregister_ioctl32_conversion(MPTTARGETINFO);
2914         unregister_ioctl32_conversion(MPTTEST);
2915         unregister_ioctl32_conversion(MPTEVENTQUERY);
2916         unregister_ioctl32_conversion(MPTEVENTENABLE);
2917         unregister_ioctl32_conversion(MPTEVENTREPORT);
2918         unregister_ioctl32_conversion(MPTHARDRESET);
2919         unregister_ioctl32_conversion(MPTCOMMAND32);
2920         unregister_ioctl32_conversion(MPTFWDOWNLOAD32);
2921         unregister_ioctl32_conversion(HP_GETHOSTINFO);
2922         unregister_ioctl32_conversion(HP_GETTARGETINFO);
2923 #endif
2924
2925         for (i=0; i<MPT_MAX_ADAPTERS; i++) {
2926                 ioc = NULL;
2927                 if (((iocnum = mpt_verify_adapter(i, &ioc)) < 0) ||
2928                     (ioc == NULL)) {
2929                         continue;
2930                 }
2931                 else {
2932                         if (ioc->ioctl) {
2933                                 kfree ( ioc->ioctl );
2934                                 ioc->ioctl = NULL;
2935                         }
2936                 }
2937         }
2938         return err;
2939 }
2940
2941 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2942 void mptctl_exit(void)
2943 {
2944         int i;
2945         MPT_ADAPTER *ioc;
2946         int iocnum;
2947
2948         misc_deregister(&mptctl_miscdev);
2949         printk(KERN_INFO MYNAM ": Deregistered /dev/%s @ (major,minor=%d,%d)\n",
2950                          mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
2951
2952         /* De-register reset handler from base module */
2953         mpt_reset_deregister(mptctl_id);
2954         dprintk((KERN_INFO MYNAM ": Deregistered for IOC reset notifications\n"));
2955
2956         /* De-register callback handler from base module */
2957         mpt_deregister(mptctl_id);
2958         printk(KERN_INFO MYNAM ": Deregistered from Fusion MPT base driver\n");
2959
2960 #ifdef CONFIG_COMPAT
2961         unregister_ioctl32_conversion(MPTIOCINFO);
2962         unregister_ioctl32_conversion(MPTIOCINFO1);
2963         unregister_ioctl32_conversion(MPTIOCINFO2);
2964         unregister_ioctl32_conversion(MPTTARGETINFO);
2965         unregister_ioctl32_conversion(MPTTEST);
2966         unregister_ioctl32_conversion(MPTEVENTQUERY);
2967         unregister_ioctl32_conversion(MPTEVENTENABLE);
2968         unregister_ioctl32_conversion(MPTEVENTREPORT);
2969         unregister_ioctl32_conversion(MPTHARDRESET);
2970         unregister_ioctl32_conversion(MPTCOMMAND32);
2971         unregister_ioctl32_conversion(MPTFWDOWNLOAD32);
2972         unregister_ioctl32_conversion(HP_GETHOSTINFO);
2973         unregister_ioctl32_conversion(HP_GETTARGETINFO);
2974 #endif
2975
2976         /* Free allocated memory */
2977         for (i=0; i<MPT_MAX_ADAPTERS; i++) {
2978                 ioc = NULL;
2979                 if (((iocnum = mpt_verify_adapter(i, &ioc)) < 0) ||
2980                     (ioc == NULL)) {
2981                         continue;
2982                 }
2983                 else {
2984                         if (ioc->ioctl) {
2985                                 kfree ( ioc->ioctl );
2986                                 ioc->ioctl = NULL;
2987                         }
2988                 }
2989         }
2990 }
2991
2992 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2993
2994 module_init(mptctl_init);
2995 module_exit(mptctl_exit);