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