Merge branch 'intx' of master.kernel.org:/pub/scm/linux/kernel/git/jgarzik/misc-2.6
[pandora-kernel.git] / drivers / scsi / megaraid / megaraid_sas.c
1 /*
2  *
3  *              Linux MegaRAID driver for SAS based RAID controllers
4  *
5  * Copyright (c) 2003-2005  LSI Logic Corporation.
6  *
7  *         This program is free software; you can redistribute it and/or
8  *         modify it under the terms of the GNU General Public License
9  *         as published by the Free Software Foundation; either version
10  *         2 of the License, or (at your option) any later version.
11  *
12  * FILE         : megaraid_sas.c
13  * Version      : v00.00.03.05
14  *
15  * Authors:
16  *      Sreenivas Bagalkote     <Sreenivas.Bagalkote@lsil.com>
17  *      Sumant Patro            <Sumant.Patro@lsil.com>
18  *
19  * List of supported controllers
20  *
21  * OEM  Product Name                    VID     DID     SSVID   SSID
22  * ---  ------------                    ---     ---     ----    ----
23  */
24
25 #include <linux/kernel.h>
26 #include <linux/types.h>
27 #include <linux/pci.h>
28 #include <linux/list.h>
29 #include <linux/moduleparam.h>
30 #include <linux/module.h>
31 #include <linux/spinlock.h>
32 #include <linux/interrupt.h>
33 #include <linux/delay.h>
34 #include <linux/uio.h>
35 #include <asm/uaccess.h>
36 #include <linux/fs.h>
37 #include <linux/compat.h>
38 #include <linux/mutex.h>
39
40 #include <scsi/scsi.h>
41 #include <scsi/scsi_cmnd.h>
42 #include <scsi/scsi_device.h>
43 #include <scsi/scsi_host.h>
44 #include "megaraid_sas.h"
45
46 MODULE_LICENSE("GPL");
47 MODULE_VERSION(MEGASAS_VERSION);
48 MODULE_AUTHOR("sreenivas.bagalkote@lsil.com");
49 MODULE_DESCRIPTION("LSI Logic MegaRAID SAS Driver");
50
51 /*
52  * PCI ID table for all supported controllers
53  */
54 static struct pci_device_id megasas_pci_table[] = {
55
56         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
57         /* xscale IOP */
58         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
59         /* ppc IOP */
60         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
61         /* xscale IOP, vega */
62         {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
63         /* xscale IOP */
64         {}
65 };
66
67 MODULE_DEVICE_TABLE(pci, megasas_pci_table);
68
69 static int megasas_mgmt_majorno;
70 static struct megasas_mgmt_info megasas_mgmt_info;
71 static struct fasync_struct *megasas_async_queue;
72 static DEFINE_MUTEX(megasas_async_queue_mutex);
73
74 static u32 megasas_dbg_lvl;
75
76 /**
77  * megasas_get_cmd -    Get a command from the free pool
78  * @instance:           Adapter soft state
79  *
80  * Returns a free command from the pool
81  */
82 static struct megasas_cmd *megasas_get_cmd(struct megasas_instance
83                                                   *instance)
84 {
85         unsigned long flags;
86         struct megasas_cmd *cmd = NULL;
87
88         spin_lock_irqsave(&instance->cmd_pool_lock, flags);
89
90         if (!list_empty(&instance->cmd_pool)) {
91                 cmd = list_entry((&instance->cmd_pool)->next,
92                                  struct megasas_cmd, list);
93                 list_del_init(&cmd->list);
94         } else {
95                 printk(KERN_ERR "megasas: Command pool empty!\n");
96         }
97
98         spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
99         return cmd;
100 }
101
102 /**
103  * megasas_return_cmd - Return a cmd to free command pool
104  * @instance:           Adapter soft state
105  * @cmd:                Command packet to be returned to free command pool
106  */
107 static inline void
108 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
109 {
110         unsigned long flags;
111
112         spin_lock_irqsave(&instance->cmd_pool_lock, flags);
113
114         cmd->scmd = NULL;
115         list_add_tail(&cmd->list, &instance->cmd_pool);
116
117         spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
118 }
119
120
121 /**
122 *       The following functions are defined for xscale 
123 *       (deviceid : 1064R, PERC5) controllers
124 */
125
126 /**
127  * megasas_enable_intr_xscale - Enables interrupts
128  * @regs:                       MFI register set
129  */
130 static inline void
131 megasas_enable_intr_xscale(struct megasas_register_set __iomem * regs)
132 {
133         writel(1, &(regs)->outbound_intr_mask);
134
135         /* Dummy readl to force pci flush */
136         readl(&regs->outbound_intr_mask);
137 }
138
139 /**
140  * megasas_disable_intr_xscale -Disables interrupt
141  * @regs:                       MFI register set
142  */
143 static inline void
144 megasas_disable_intr_xscale(struct megasas_register_set __iomem * regs)
145 {
146         u32 mask = 0x1f;
147         writel(mask, &regs->outbound_intr_mask);
148         /* Dummy readl to force pci flush */
149         readl(&regs->outbound_intr_mask);
150 }
151
152 /**
153  * megasas_read_fw_status_reg_xscale - returns the current FW status value
154  * @regs:                       MFI register set
155  */
156 static u32
157 megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs)
158 {
159         return readl(&(regs)->outbound_msg_0);
160 }
161 /**
162  * megasas_clear_interrupt_xscale -     Check & clear interrupt
163  * @regs:                               MFI register set
164  */
165 static int 
166 megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs)
167 {
168         u32 status;
169         /*
170          * Check if it is our interrupt
171          */
172         status = readl(&regs->outbound_intr_status);
173
174         if (!(status & MFI_OB_INTR_STATUS_MASK)) {
175                 return 1;
176         }
177
178         /*
179          * Clear the interrupt by writing back the same value
180          */
181         writel(status, &regs->outbound_intr_status);
182
183         return 0;
184 }
185
186 /**
187  * megasas_fire_cmd_xscale -    Sends command to the FW
188  * @frame_phys_addr :           Physical address of cmd
189  * @frame_count :               Number of frames for the command
190  * @regs :                      MFI register set
191  */
192 static inline void 
193 megasas_fire_cmd_xscale(dma_addr_t frame_phys_addr,u32 frame_count, struct megasas_register_set __iomem *regs)
194 {
195         writel((frame_phys_addr >> 3)|(frame_count),
196                &(regs)->inbound_queue_port);
197 }
198
199 static struct megasas_instance_template megasas_instance_template_xscale = {
200
201         .fire_cmd = megasas_fire_cmd_xscale,
202         .enable_intr = megasas_enable_intr_xscale,
203         .disable_intr = megasas_disable_intr_xscale,
204         .clear_intr = megasas_clear_intr_xscale,
205         .read_fw_status_reg = megasas_read_fw_status_reg_xscale,
206 };
207
208 /**
209 *       This is the end of set of functions & definitions specific 
210 *       to xscale (deviceid : 1064R, PERC5) controllers
211 */
212
213 /**
214 *       The following functions are defined for ppc (deviceid : 0x60) 
215 *       controllers
216 */
217
218 /**
219  * megasas_enable_intr_ppc -    Enables interrupts
220  * @regs:                       MFI register set
221  */
222 static inline void
223 megasas_enable_intr_ppc(struct megasas_register_set __iomem * regs)
224 {
225         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
226     
227         writel(~0x80000004, &(regs)->outbound_intr_mask);
228
229         /* Dummy readl to force pci flush */
230         readl(&regs->outbound_intr_mask);
231 }
232
233 /**
234  * megasas_disable_intr_ppc -   Disable interrupt
235  * @regs:                       MFI register set
236  */
237 static inline void
238 megasas_disable_intr_ppc(struct megasas_register_set __iomem * regs)
239 {
240         u32 mask = 0xFFFFFFFF;
241         writel(mask, &regs->outbound_intr_mask);
242         /* Dummy readl to force pci flush */
243         readl(&regs->outbound_intr_mask);
244 }
245
246 /**
247  * megasas_read_fw_status_reg_ppc - returns the current FW status value
248  * @regs:                       MFI register set
249  */
250 static u32
251 megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs)
252 {
253         return readl(&(regs)->outbound_scratch_pad);
254 }
255
256 /**
257  * megasas_clear_interrupt_ppc -        Check & clear interrupt
258  * @regs:                               MFI register set
259  */
260 static int 
261 megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs)
262 {
263         u32 status;
264         /*
265          * Check if it is our interrupt
266          */
267         status = readl(&regs->outbound_intr_status);
268
269         if (!(status & MFI_REPLY_1078_MESSAGE_INTERRUPT)) {
270                 return 1;
271         }
272
273         /*
274          * Clear the interrupt by writing back the same value
275          */
276         writel(status, &regs->outbound_doorbell_clear);
277
278         return 0;
279 }
280 /**
281  * megasas_fire_cmd_ppc -       Sends command to the FW
282  * @frame_phys_addr :           Physical address of cmd
283  * @frame_count :               Number of frames for the command
284  * @regs :                      MFI register set
285  */
286 static inline void 
287 megasas_fire_cmd_ppc(dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs)
288 {
289         writel((frame_phys_addr | (frame_count<<1))|1, 
290                         &(regs)->inbound_queue_port);
291 }
292
293 static struct megasas_instance_template megasas_instance_template_ppc = {
294         
295         .fire_cmd = megasas_fire_cmd_ppc,
296         .enable_intr = megasas_enable_intr_ppc,
297         .disable_intr = megasas_disable_intr_ppc,
298         .clear_intr = megasas_clear_intr_ppc,
299         .read_fw_status_reg = megasas_read_fw_status_reg_ppc,
300 };
301
302 /**
303 *       This is the end of set of functions & definitions
304 *       specific to ppc (deviceid : 0x60) controllers
305 */
306
307 /**
308  * megasas_issue_polled -       Issues a polling command
309  * @instance:                   Adapter soft state
310  * @cmd:                        Command packet to be issued 
311  *
312  * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
313  */
314 static int
315 megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
316 {
317         int i;
318         u32 msecs = MFI_POLL_TIMEOUT_SECS * 1000;
319
320         struct megasas_header *frame_hdr = &cmd->frame->hdr;
321
322         frame_hdr->cmd_status = 0xFF;
323         frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;
324
325         /*
326          * Issue the frame using inbound queue port
327          */
328         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
329
330         /*
331          * Wait for cmd_status to change
332          */
333         for (i = 0; (i < msecs) && (frame_hdr->cmd_status == 0xff); i++) {
334                 rmb();
335                 msleep(1);
336         }
337
338         if (frame_hdr->cmd_status == 0xff)
339                 return -ETIME;
340
341         return 0;
342 }
343
344 /**
345  * megasas_issue_blocked_cmd -  Synchronous wrapper around regular FW cmds
346  * @instance:                   Adapter soft state
347  * @cmd:                        Command to be issued
348  *
349  * This function waits on an event for the command to be returned from ISR.
350  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
351  * Used to issue ioctl commands.
352  */
353 static int
354 megasas_issue_blocked_cmd(struct megasas_instance *instance,
355                           struct megasas_cmd *cmd)
356 {
357         cmd->cmd_status = ENODATA;
358
359         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
360
361         wait_event_timeout(instance->int_cmd_wait_q, (cmd->cmd_status != ENODATA),
362                 MEGASAS_INTERNAL_CMD_WAIT_TIME*HZ);
363
364         return 0;
365 }
366
367 /**
368  * megasas_issue_blocked_abort_cmd -    Aborts previously issued cmd
369  * @instance:                           Adapter soft state
370  * @cmd_to_abort:                       Previously issued cmd to be aborted
371  *
372  * MFI firmware can abort previously issued AEN comamnd (automatic event
373  * notification). The megasas_issue_blocked_abort_cmd() issues such abort
374  * cmd and waits for return status.
375  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
376  */
377 static int
378 megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
379                                 struct megasas_cmd *cmd_to_abort)
380 {
381         struct megasas_cmd *cmd;
382         struct megasas_abort_frame *abort_fr;
383
384         cmd = megasas_get_cmd(instance);
385
386         if (!cmd)
387                 return -1;
388
389         abort_fr = &cmd->frame->abort;
390
391         /*
392          * Prepare and issue the abort frame
393          */
394         abort_fr->cmd = MFI_CMD_ABORT;
395         abort_fr->cmd_status = 0xFF;
396         abort_fr->flags = 0;
397         abort_fr->abort_context = cmd_to_abort->index;
398         abort_fr->abort_mfi_phys_addr_lo = cmd_to_abort->frame_phys_addr;
399         abort_fr->abort_mfi_phys_addr_hi = 0;
400
401         cmd->sync_cmd = 1;
402         cmd->cmd_status = 0xFF;
403
404         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
405
406         /*
407          * Wait for this cmd to complete
408          */
409         wait_event_timeout(instance->abort_cmd_wait_q, (cmd->cmd_status != 0xFF),
410                 MEGASAS_INTERNAL_CMD_WAIT_TIME*HZ);
411
412         megasas_return_cmd(instance, cmd);
413         return 0;
414 }
415
416 /**
417  * megasas_make_sgl32 - Prepares 32-bit SGL
418  * @instance:           Adapter soft state
419  * @scp:                SCSI command from the mid-layer
420  * @mfi_sgl:            SGL to be filled in
421  *
422  * If successful, this function returns the number of SG elements. Otherwise,
423  * it returnes -1.
424  */
425 static int
426 megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
427                    union megasas_sgl *mfi_sgl)
428 {
429         int i;
430         int sge_count;
431         struct scatterlist *os_sgl;
432
433         /*
434          * Return 0 if there is no data transfer
435          */
436         if (!scp->request_buffer || !scp->request_bufflen)
437                 return 0;
438
439         if (!scp->use_sg) {
440                 mfi_sgl->sge32[0].phys_addr = pci_map_single(instance->pdev,
441                                                              scp->
442                                                              request_buffer,
443                                                              scp->
444                                                              request_bufflen,
445                                                              scp->
446                                                              sc_data_direction);
447                 mfi_sgl->sge32[0].length = scp->request_bufflen;
448
449                 return 1;
450         }
451
452         os_sgl = (struct scatterlist *)scp->request_buffer;
453         sge_count = pci_map_sg(instance->pdev, os_sgl, scp->use_sg,
454                                scp->sc_data_direction);
455
456         for (i = 0; i < sge_count; i++, os_sgl++) {
457                 mfi_sgl->sge32[i].length = sg_dma_len(os_sgl);
458                 mfi_sgl->sge32[i].phys_addr = sg_dma_address(os_sgl);
459         }
460
461         return sge_count;
462 }
463
464 /**
465  * megasas_make_sgl64 - Prepares 64-bit SGL
466  * @instance:           Adapter soft state
467  * @scp:                SCSI command from the mid-layer
468  * @mfi_sgl:            SGL to be filled in
469  *
470  * If successful, this function returns the number of SG elements. Otherwise,
471  * it returnes -1.
472  */
473 static int
474 megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
475                    union megasas_sgl *mfi_sgl)
476 {
477         int i;
478         int sge_count;
479         struct scatterlist *os_sgl;
480
481         /*
482          * Return 0 if there is no data transfer
483          */
484         if (!scp->request_buffer || !scp->request_bufflen)
485                 return 0;
486
487         if (!scp->use_sg) {
488                 mfi_sgl->sge64[0].phys_addr = pci_map_single(instance->pdev,
489                                                              scp->
490                                                              request_buffer,
491                                                              scp->
492                                                              request_bufflen,
493                                                              scp->
494                                                              sc_data_direction);
495
496                 mfi_sgl->sge64[0].length = scp->request_bufflen;
497
498                 return 1;
499         }
500
501         os_sgl = (struct scatterlist *)scp->request_buffer;
502         sge_count = pci_map_sg(instance->pdev, os_sgl, scp->use_sg,
503                                scp->sc_data_direction);
504
505         for (i = 0; i < sge_count; i++, os_sgl++) {
506                 mfi_sgl->sge64[i].length = sg_dma_len(os_sgl);
507                 mfi_sgl->sge64[i].phys_addr = sg_dma_address(os_sgl);
508         }
509
510         return sge_count;
511 }
512
513  /**
514  * megasas_get_frame_count - Computes the number of frames
515  * @sge_count           : number of sg elements
516  *
517  * Returns the number of frames required for numnber of sge's (sge_count)
518  */
519
520 static u32 megasas_get_frame_count(u8 sge_count)
521 {
522         int num_cnt;
523         int sge_bytes;
524         u32 sge_sz;
525         u32 frame_count=0;
526
527         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
528             sizeof(struct megasas_sge32);
529
530         /*
531         * Main frame can contain 2 SGEs for 64-bit SGLs and
532         * 3 SGEs for 32-bit SGLs
533         */
534         if (IS_DMA64)
535                 num_cnt = sge_count - 2;
536         else
537                 num_cnt = sge_count - 3;
538
539         if(num_cnt>0){
540                 sge_bytes = sge_sz * num_cnt;
541
542                 frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
543                     ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
544         }
545         /* Main frame */
546         frame_count +=1;
547
548         if (frame_count > 7)
549                 frame_count = 8;
550         return frame_count;
551 }
552
553 /**
554  * megasas_build_dcdb - Prepares a direct cdb (DCDB) command
555  * @instance:           Adapter soft state
556  * @scp:                SCSI command
557  * @cmd:                Command to be prepared in
558  *
559  * This function prepares CDB commands. These are typcially pass-through
560  * commands to the devices.
561  */
562 static int
563 megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
564                    struct megasas_cmd *cmd)
565 {
566         u32 is_logical;
567         u32 device_id;
568         u16 flags = 0;
569         struct megasas_pthru_frame *pthru;
570
571         is_logical = MEGASAS_IS_LOGICAL(scp);
572         device_id = MEGASAS_DEV_INDEX(instance, scp);
573         pthru = (struct megasas_pthru_frame *)cmd->frame;
574
575         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
576                 flags = MFI_FRAME_DIR_WRITE;
577         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
578                 flags = MFI_FRAME_DIR_READ;
579         else if (scp->sc_data_direction == PCI_DMA_NONE)
580                 flags = MFI_FRAME_DIR_NONE;
581
582         /*
583          * Prepare the DCDB frame
584          */
585         pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
586         pthru->cmd_status = 0x0;
587         pthru->scsi_status = 0x0;
588         pthru->target_id = device_id;
589         pthru->lun = scp->device->lun;
590         pthru->cdb_len = scp->cmd_len;
591         pthru->timeout = 0;
592         pthru->flags = flags;
593         pthru->data_xfer_len = scp->request_bufflen;
594
595         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
596
597         /*
598          * Construct SGL
599          */
600         if (IS_DMA64) {
601                 pthru->flags |= MFI_FRAME_SGL64;
602                 pthru->sge_count = megasas_make_sgl64(instance, scp,
603                                                       &pthru->sgl);
604         } else
605                 pthru->sge_count = megasas_make_sgl32(instance, scp,
606                                                       &pthru->sgl);
607
608         /*
609          * Sense info specific
610          */
611         pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
612         pthru->sense_buf_phys_addr_hi = 0;
613         pthru->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
614
615         /*
616          * Compute the total number of frames this command consumes. FW uses
617          * this number to pull sufficient number of frames from host memory.
618          */
619         cmd->frame_count = megasas_get_frame_count(pthru->sge_count);
620
621         return cmd->frame_count;
622 }
623
624 /**
625  * megasas_build_ldio - Prepares IOs to logical devices
626  * @instance:           Adapter soft state
627  * @scp:                SCSI command
628  * @cmd:                Command to to be prepared
629  *
630  * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
631  */
632 static int
633 megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
634                    struct megasas_cmd *cmd)
635 {
636         u32 device_id;
637         u8 sc = scp->cmnd[0];
638         u16 flags = 0;
639         struct megasas_io_frame *ldio;
640
641         device_id = MEGASAS_DEV_INDEX(instance, scp);
642         ldio = (struct megasas_io_frame *)cmd->frame;
643
644         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
645                 flags = MFI_FRAME_DIR_WRITE;
646         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
647                 flags = MFI_FRAME_DIR_READ;
648
649         /*
650          * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
651          */
652         ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
653         ldio->cmd_status = 0x0;
654         ldio->scsi_status = 0x0;
655         ldio->target_id = device_id;
656         ldio->timeout = 0;
657         ldio->reserved_0 = 0;
658         ldio->pad_0 = 0;
659         ldio->flags = flags;
660         ldio->start_lba_hi = 0;
661         ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
662
663         /*
664          * 6-byte READ(0x08) or WRITE(0x0A) cdb
665          */
666         if (scp->cmd_len == 6) {
667                 ldio->lba_count = (u32) scp->cmnd[4];
668                 ldio->start_lba_lo = ((u32) scp->cmnd[1] << 16) |
669                     ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
670
671                 ldio->start_lba_lo &= 0x1FFFFF;
672         }
673
674         /*
675          * 10-byte READ(0x28) or WRITE(0x2A) cdb
676          */
677         else if (scp->cmd_len == 10) {
678                 ldio->lba_count = (u32) scp->cmnd[8] |
679                     ((u32) scp->cmnd[7] << 8);
680                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
681                     ((u32) scp->cmnd[3] << 16) |
682                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
683         }
684
685         /*
686          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
687          */
688         else if (scp->cmd_len == 12) {
689                 ldio->lba_count = ((u32) scp->cmnd[6] << 24) |
690                     ((u32) scp->cmnd[7] << 16) |
691                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
692
693                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
694                     ((u32) scp->cmnd[3] << 16) |
695                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
696         }
697
698         /*
699          * 16-byte READ(0x88) or WRITE(0x8A) cdb
700          */
701         else if (scp->cmd_len == 16) {
702                 ldio->lba_count = ((u32) scp->cmnd[10] << 24) |
703                     ((u32) scp->cmnd[11] << 16) |
704                     ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
705
706                 ldio->start_lba_lo = ((u32) scp->cmnd[6] << 24) |
707                     ((u32) scp->cmnd[7] << 16) |
708                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
709
710                 ldio->start_lba_hi = ((u32) scp->cmnd[2] << 24) |
711                     ((u32) scp->cmnd[3] << 16) |
712                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
713
714         }
715
716         /*
717          * Construct SGL
718          */
719         if (IS_DMA64) {
720                 ldio->flags |= MFI_FRAME_SGL64;
721                 ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
722         } else
723                 ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
724
725         /*
726          * Sense info specific
727          */
728         ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
729         ldio->sense_buf_phys_addr_hi = 0;
730         ldio->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
731
732         /*
733          * Compute the total number of frames this command consumes. FW uses
734          * this number to pull sufficient number of frames from host memory.
735          */
736         cmd->frame_count = megasas_get_frame_count(ldio->sge_count);
737
738         return cmd->frame_count;
739 }
740
741 /**
742  * megasas_is_ldio -            Checks if the cmd is for logical drive
743  * @scmd:                       SCSI command
744  *      
745  * Called by megasas_queue_command to find out if the command to be queued
746  * is a logical drive command   
747  */
748 static inline int megasas_is_ldio(struct scsi_cmnd *cmd)
749 {
750         if (!MEGASAS_IS_LOGICAL(cmd))
751                 return 0;
752         switch (cmd->cmnd[0]) {
753         case READ_10:
754         case WRITE_10:
755         case READ_12:
756         case WRITE_12:
757         case READ_6:
758         case WRITE_6:
759         case READ_16:
760         case WRITE_16:
761                 return 1;
762         default:
763                 return 0;
764         }
765 }
766
767  /**
768  * megasas_dump_pending_frames -        Dumps the frame address of all pending cmds
769  *                                      in FW
770  * @instance:                           Adapter soft state
771  */
772 static inline void
773 megasas_dump_pending_frames(struct megasas_instance *instance)
774 {
775         struct megasas_cmd *cmd;
776         int i,n;
777         union megasas_sgl *mfi_sgl;
778         struct megasas_io_frame *ldio;
779         struct megasas_pthru_frame *pthru;
780         u32 sgcount;
781         u32 max_cmd = instance->max_fw_cmds;
782
783         printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
784         printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
785         if (IS_DMA64)
786                 printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
787         else
788                 printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
789
790         printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
791         for (i = 0; i < max_cmd; i++) {
792                 cmd = instance->cmd_list[i];
793                 if(!cmd->scmd)
794                         continue;
795                 printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
796                 if (megasas_is_ldio(cmd->scmd)){
797                         ldio = (struct megasas_io_frame *)cmd->frame;
798                         mfi_sgl = &ldio->sgl;
799                         sgcount = ldio->sge_count;
800                         printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no, cmd->frame_count,ldio->cmd,ldio->target_id, ldio->start_lba_lo,ldio->start_lba_hi,ldio->sense_buf_phys_addr_lo,sgcount);
801                 }
802                 else {
803                         pthru = (struct megasas_pthru_frame *) cmd->frame;
804                         mfi_sgl = &pthru->sgl;
805                         sgcount = pthru->sge_count;
806                         printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no,cmd->frame_count,pthru->cmd,pthru->target_id,pthru->lun,pthru->cdb_len , pthru->data_xfer_len,pthru->sense_buf_phys_addr_lo,sgcount);
807                 }
808         if(megasas_dbg_lvl & MEGASAS_DBG_LVL){
809                 for (n = 0; n < sgcount; n++){
810                         if (IS_DMA64)
811                                 printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%08lx ",mfi_sgl->sge64[n].length , (unsigned long)mfi_sgl->sge64[n].phys_addr) ;
812                         else
813                                 printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",mfi_sgl->sge32[n].length , mfi_sgl->sge32[n].phys_addr) ;
814                         }
815                 }
816                 printk(KERN_ERR "\n");
817         } /*for max_cmd*/
818         printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
819         for (i = 0; i < max_cmd; i++) {
820
821                 cmd = instance->cmd_list[i];
822
823                 if(cmd->sync_cmd == 1){
824                         printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
825                 }
826         }
827         printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no);
828 }
829
830 /**
831  * megasas_queue_command -      Queue entry point
832  * @scmd:                       SCSI command to be queued
833  * @done:                       Callback entry point
834  */
835 static int
836 megasas_queue_command(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *))
837 {
838         u32 frame_count;
839         struct megasas_cmd *cmd;
840         struct megasas_instance *instance;
841
842         instance = (struct megasas_instance *)
843             scmd->device->host->hostdata;
844         scmd->scsi_done = done;
845         scmd->result = 0;
846
847         if (MEGASAS_IS_LOGICAL(scmd) &&
848             (scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) {
849                 scmd->result = DID_BAD_TARGET << 16;
850                 goto out_done;
851         }
852
853         cmd = megasas_get_cmd(instance);
854         if (!cmd)
855                 return SCSI_MLQUEUE_HOST_BUSY;
856
857         /*
858          * Logical drive command
859          */
860         if (megasas_is_ldio(scmd))
861                 frame_count = megasas_build_ldio(instance, scmd, cmd);
862         else
863                 frame_count = megasas_build_dcdb(instance, scmd, cmd);
864
865         if (!frame_count)
866                 goto out_return_cmd;
867
868         cmd->scmd = scmd;
869
870         /*
871          * Issue the command to the FW
872          */
873         atomic_inc(&instance->fw_outstanding);
874
875         instance->instancet->fire_cmd(cmd->frame_phys_addr ,cmd->frame_count-1,instance->reg_set);
876
877         return 0;
878
879  out_return_cmd:
880         megasas_return_cmd(instance, cmd);
881  out_done:
882         done(scmd);
883         return 0;
884 }
885
886 static int megasas_slave_configure(struct scsi_device *sdev)
887 {
888         /*
889          * Don't export physical disk devices to the disk driver.
890          *
891          * FIXME: Currently we don't export them to the midlayer at all.
892          *        That will be fixed once LSI engineers have audited the
893          *        firmware for possible issues.
894          */
895         if (sdev->channel < MEGASAS_MAX_PD_CHANNELS && sdev->type == TYPE_DISK)
896                 return -ENXIO;
897
898         /*
899          * The RAID firmware may require extended timeouts.
900          */
901         if (sdev->channel >= MEGASAS_MAX_PD_CHANNELS)
902                 sdev->timeout = 90 * HZ;
903         return 0;
904 }
905
906 /**
907  * megasas_wait_for_outstanding -       Wait for all outstanding cmds
908  * @instance:                           Adapter soft state
909  *
910  * This function waits for upto MEGASAS_RESET_WAIT_TIME seconds for FW to
911  * complete all its outstanding commands. Returns error if one or more IOs
912  * are pending after this time period. It also marks the controller dead.
913  */
914 static int megasas_wait_for_outstanding(struct megasas_instance *instance)
915 {
916         int i;
917         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
918
919         for (i = 0; i < wait_time; i++) {
920
921                 int outstanding = atomic_read(&instance->fw_outstanding);
922
923                 if (!outstanding)
924                         break;
925
926                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
927                         printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
928                                "commands to complete\n",i,outstanding);
929                 }
930
931                 msleep(1000);
932         }
933
934         if (atomic_read(&instance->fw_outstanding)) {
935                 /*
936                 * Send signal to FW to stop processing any pending cmds.
937                 * The controller will be taken offline by the OS now.
938                 */
939                 writel(MFI_STOP_ADP,
940                                 &instance->reg_set->inbound_doorbell);
941                 megasas_dump_pending_frames(instance);
942                 instance->hw_crit_error = 1;
943                 return FAILED;
944         }
945
946         return SUCCESS;
947 }
948
949 /**
950  * megasas_generic_reset -      Generic reset routine
951  * @scmd:                       Mid-layer SCSI command
952  *
953  * This routine implements a generic reset handler for device, bus and host
954  * reset requests. Device, bus and host specific reset handlers can use this
955  * function after they do their specific tasks.
956  */
957 static int megasas_generic_reset(struct scsi_cmnd *scmd)
958 {
959         int ret_val;
960         struct megasas_instance *instance;
961
962         instance = (struct megasas_instance *)scmd->device->host->hostdata;
963
964         scmd_printk(KERN_NOTICE, scmd, "megasas: RESET -%ld cmd=%x\n",
965                scmd->serial_number, scmd->cmnd[0]);
966
967         if (instance->hw_crit_error) {
968                 printk(KERN_ERR "megasas: cannot recover from previous reset "
969                        "failures\n");
970                 return FAILED;
971         }
972
973         ret_val = megasas_wait_for_outstanding(instance);
974         if (ret_val == SUCCESS)
975                 printk(KERN_NOTICE "megasas: reset successful \n");
976         else
977                 printk(KERN_ERR "megasas: failed to do reset\n");
978
979         return ret_val;
980 }
981
982 /**
983  * megasas_reset_device -       Device reset handler entry point
984  */
985 static int megasas_reset_device(struct scsi_cmnd *scmd)
986 {
987         int ret;
988
989         /*
990          * First wait for all commands to complete
991          */
992         ret = megasas_generic_reset(scmd);
993
994         return ret;
995 }
996
997 /**
998  * megasas_reset_bus_host -     Bus & host reset handler entry point
999  */
1000 static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
1001 {
1002         int ret;
1003
1004         /*
1005          * First wait for all commands to complete
1006          */
1007         ret = megasas_generic_reset(scmd);
1008
1009         return ret;
1010 }
1011
1012 /**
1013  * megasas_service_aen -        Processes an event notification
1014  * @instance:                   Adapter soft state
1015  * @cmd:                        AEN command completed by the ISR
1016  *
1017  * For AEN, driver sends a command down to FW that is held by the FW till an
1018  * event occurs. When an event of interest occurs, FW completes the command
1019  * that it was previously holding.
1020  *
1021  * This routines sends SIGIO signal to processes that have registered with the
1022  * driver for AEN.
1023  */
1024 static void
1025 megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
1026 {
1027         /*
1028          * Don't signal app if it is just an aborted previously registered aen
1029          */
1030         if (!cmd->abort_aen)
1031                 kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
1032         else
1033                 cmd->abort_aen = 0;
1034
1035         instance->aen_cmd = NULL;
1036         megasas_return_cmd(instance, cmd);
1037 }
1038
1039 /*
1040  * Scsi host template for megaraid_sas driver
1041  */
1042 static struct scsi_host_template megasas_template = {
1043
1044         .module = THIS_MODULE,
1045         .name = "LSI Logic SAS based MegaRAID driver",
1046         .proc_name = "megaraid_sas",
1047         .slave_configure = megasas_slave_configure,
1048         .queuecommand = megasas_queue_command,
1049         .eh_device_reset_handler = megasas_reset_device,
1050         .eh_bus_reset_handler = megasas_reset_bus_host,
1051         .eh_host_reset_handler = megasas_reset_bus_host,
1052         .use_clustering = ENABLE_CLUSTERING,
1053 };
1054
1055 /**
1056  * megasas_complete_int_cmd -   Completes an internal command
1057  * @instance:                   Adapter soft state
1058  * @cmd:                        Command to be completed
1059  *
1060  * The megasas_issue_blocked_cmd() function waits for a command to complete
1061  * after it issues a command. This function wakes up that waiting routine by
1062  * calling wake_up() on the wait queue.
1063  */
1064 static void
1065 megasas_complete_int_cmd(struct megasas_instance *instance,
1066                          struct megasas_cmd *cmd)
1067 {
1068         cmd->cmd_status = cmd->frame->io.cmd_status;
1069
1070         if (cmd->cmd_status == ENODATA) {
1071                 cmd->cmd_status = 0;
1072         }
1073         wake_up(&instance->int_cmd_wait_q);
1074 }
1075
1076 /**
1077  * megasas_complete_abort -     Completes aborting a command
1078  * @instance:                   Adapter soft state
1079  * @cmd:                        Cmd that was issued to abort another cmd
1080  *
1081  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q 
1082  * after it issues an abort on a previously issued command. This function 
1083  * wakes up all functions waiting on the same wait queue.
1084  */
1085 static void
1086 megasas_complete_abort(struct megasas_instance *instance,
1087                        struct megasas_cmd *cmd)
1088 {
1089         if (cmd->sync_cmd) {
1090                 cmd->sync_cmd = 0;
1091                 cmd->cmd_status = 0;
1092                 wake_up(&instance->abort_cmd_wait_q);
1093         }
1094
1095         return;
1096 }
1097
1098 /**
1099  * megasas_unmap_sgbuf -        Unmap SG buffers
1100  * @instance:                   Adapter soft state
1101  * @cmd:                        Completed command
1102  */
1103 static void
1104 megasas_unmap_sgbuf(struct megasas_instance *instance, struct megasas_cmd *cmd)
1105 {
1106         dma_addr_t buf_h;
1107         u8 opcode;
1108
1109         if (cmd->scmd->use_sg) {
1110                 pci_unmap_sg(instance->pdev, cmd->scmd->request_buffer,
1111                              cmd->scmd->use_sg, cmd->scmd->sc_data_direction);
1112                 return;
1113         }
1114
1115         if (!cmd->scmd->request_bufflen)
1116                 return;
1117
1118         opcode = cmd->frame->hdr.cmd;
1119
1120         if ((opcode == MFI_CMD_LD_READ) || (opcode == MFI_CMD_LD_WRITE)) {
1121                 if (IS_DMA64)
1122                         buf_h = cmd->frame->io.sgl.sge64[0].phys_addr;
1123                 else
1124                         buf_h = cmd->frame->io.sgl.sge32[0].phys_addr;
1125         } else {
1126                 if (IS_DMA64)
1127                         buf_h = cmd->frame->pthru.sgl.sge64[0].phys_addr;
1128                 else
1129                         buf_h = cmd->frame->pthru.sgl.sge32[0].phys_addr;
1130         }
1131
1132         pci_unmap_single(instance->pdev, buf_h, cmd->scmd->request_bufflen,
1133                          cmd->scmd->sc_data_direction);
1134         return;
1135 }
1136
1137 /**
1138  * megasas_complete_cmd -       Completes a command
1139  * @instance:                   Adapter soft state
1140  * @cmd:                        Command to be completed
1141  * @alt_status:                 If non-zero, use this value as status to 
1142  *                              SCSI mid-layer instead of the value returned
1143  *                              by the FW. This should be used if caller wants
1144  *                              an alternate status (as in the case of aborted
1145  *                              commands)
1146  */
1147 static void
1148 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
1149                      u8 alt_status)
1150 {
1151         int exception = 0;
1152         struct megasas_header *hdr = &cmd->frame->hdr;
1153
1154         if (cmd->scmd) {
1155                 cmd->scmd->SCp.ptr = (char *)0;
1156         }
1157
1158         switch (hdr->cmd) {
1159
1160         case MFI_CMD_PD_SCSI_IO:
1161         case MFI_CMD_LD_SCSI_IO:
1162
1163                 /*
1164                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
1165                  * issued either through an IO path or an IOCTL path. If it
1166                  * was via IOCTL, we will send it to internal completion.
1167                  */
1168                 if (cmd->sync_cmd) {
1169                         cmd->sync_cmd = 0;
1170                         megasas_complete_int_cmd(instance, cmd);
1171                         break;
1172                 }
1173
1174         case MFI_CMD_LD_READ:
1175         case MFI_CMD_LD_WRITE:
1176
1177                 if (alt_status) {
1178                         cmd->scmd->result = alt_status << 16;
1179                         exception = 1;
1180                 }
1181
1182                 if (exception) {
1183
1184                         atomic_dec(&instance->fw_outstanding);
1185
1186                         megasas_unmap_sgbuf(instance, cmd);
1187                         cmd->scmd->scsi_done(cmd->scmd);
1188                         megasas_return_cmd(instance, cmd);
1189
1190                         break;
1191                 }
1192
1193                 switch (hdr->cmd_status) {
1194
1195                 case MFI_STAT_OK:
1196                         cmd->scmd->result = DID_OK << 16;
1197                         break;
1198
1199                 case MFI_STAT_SCSI_IO_FAILED:
1200                 case MFI_STAT_LD_INIT_IN_PROGRESS:
1201                         cmd->scmd->result =
1202                             (DID_ERROR << 16) | hdr->scsi_status;
1203                         break;
1204
1205                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
1206
1207                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
1208
1209                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
1210                                 memset(cmd->scmd->sense_buffer, 0,
1211                                        SCSI_SENSE_BUFFERSIZE);
1212                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
1213                                        hdr->sense_len);
1214
1215                                 cmd->scmd->result |= DRIVER_SENSE << 24;
1216                         }
1217
1218                         break;
1219
1220                 case MFI_STAT_LD_OFFLINE:
1221                 case MFI_STAT_DEVICE_NOT_FOUND:
1222                         cmd->scmd->result = DID_BAD_TARGET << 16;
1223                         break;
1224
1225                 default:
1226                         printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
1227                                hdr->cmd_status);
1228                         cmd->scmd->result = DID_ERROR << 16;
1229                         break;
1230                 }
1231
1232                 atomic_dec(&instance->fw_outstanding);
1233
1234                 megasas_unmap_sgbuf(instance, cmd);
1235                 cmd->scmd->scsi_done(cmd->scmd);
1236                 megasas_return_cmd(instance, cmd);
1237
1238                 break;
1239
1240         case MFI_CMD_SMP:
1241         case MFI_CMD_STP:
1242         case MFI_CMD_DCMD:
1243
1244                 /*
1245                  * See if got an event notification
1246                  */
1247                 if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT)
1248                         megasas_service_aen(instance, cmd);
1249                 else
1250                         megasas_complete_int_cmd(instance, cmd);
1251
1252                 break;
1253
1254         case MFI_CMD_ABORT:
1255                 /*
1256                  * Cmd issued to abort another cmd returned
1257                  */
1258                 megasas_complete_abort(instance, cmd);
1259                 break;
1260
1261         default:
1262                 printk("megasas: Unknown command completed! [0x%X]\n",
1263                        hdr->cmd);
1264                 break;
1265         }
1266 }
1267
1268 /**
1269  * megasas_deplete_reply_queue -        Processes all completed commands
1270  * @instance:                           Adapter soft state
1271  * @alt_status:                         Alternate status to be returned to
1272  *                                      SCSI mid-layer instead of the status
1273  *                                      returned by the FW
1274  */
1275 static int
1276 megasas_deplete_reply_queue(struct megasas_instance *instance, u8 alt_status)
1277 {
1278         /*
1279          * Check if it is our interrupt
1280          * Clear the interrupt 
1281          */
1282         if(instance->instancet->clear_intr(instance->reg_set))
1283                 return IRQ_NONE;
1284
1285         /*
1286          * Schedule the tasklet for cmd completion
1287          */
1288         tasklet_schedule(&instance->isr_tasklet);
1289
1290         return IRQ_HANDLED;
1291 }
1292
1293 /**
1294  * megasas_isr - isr entry point
1295  */
1296 static irqreturn_t megasas_isr(int irq, void *devp)
1297 {
1298         return megasas_deplete_reply_queue((struct megasas_instance *)devp,
1299                                            DID_OK);
1300 }
1301
1302 /**
1303  * megasas_transition_to_ready -        Move the FW to READY state
1304  * @instance:                           Adapter soft state
1305  *
1306  * During the initialization, FW passes can potentially be in any one of
1307  * several possible states. If the FW in operational, waiting-for-handshake
1308  * states, driver must take steps to bring it to ready state. Otherwise, it
1309  * has to wait for the ready state.
1310  */
1311 static int
1312 megasas_transition_to_ready(struct megasas_instance* instance)
1313 {
1314         int i;
1315         u8 max_wait;
1316         u32 fw_state;
1317         u32 cur_state;
1318
1319         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
1320
1321         if (fw_state != MFI_STATE_READY)
1322                 printk(KERN_INFO "megasas: Waiting for FW to come to ready"
1323                        " state\n");
1324
1325         while (fw_state != MFI_STATE_READY) {
1326
1327                 switch (fw_state) {
1328
1329                 case MFI_STATE_FAULT:
1330
1331                         printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
1332                         return -ENODEV;
1333
1334                 case MFI_STATE_WAIT_HANDSHAKE:
1335                         /*
1336                          * Set the CLR bit in inbound doorbell
1337                          */
1338                         writel(MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
1339                                 &instance->reg_set->inbound_doorbell);
1340
1341                         max_wait = 2;
1342                         cur_state = MFI_STATE_WAIT_HANDSHAKE;
1343                         break;
1344
1345                 case MFI_STATE_BOOT_MESSAGE_PENDING:
1346                         writel(MFI_INIT_HOTPLUG,
1347                                 &instance->reg_set->inbound_doorbell);
1348
1349                         max_wait = 10;
1350                         cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
1351                         break;
1352
1353                 case MFI_STATE_OPERATIONAL:
1354                         /*
1355                          * Bring it to READY state; assuming max wait 10 secs
1356                          */
1357                         instance->instancet->disable_intr(instance->reg_set);
1358                         writel(MFI_RESET_FLAGS, &instance->reg_set->inbound_doorbell);
1359
1360                         max_wait = 10;
1361                         cur_state = MFI_STATE_OPERATIONAL;
1362                         break;
1363
1364                 case MFI_STATE_UNDEFINED:
1365                         /*
1366                          * This state should not last for more than 2 seconds
1367                          */
1368                         max_wait = 2;
1369                         cur_state = MFI_STATE_UNDEFINED;
1370                         break;
1371
1372                 case MFI_STATE_BB_INIT:
1373                         max_wait = 2;
1374                         cur_state = MFI_STATE_BB_INIT;
1375                         break;
1376
1377                 case MFI_STATE_FW_INIT:
1378                         max_wait = 20;
1379                         cur_state = MFI_STATE_FW_INIT;
1380                         break;
1381
1382                 case MFI_STATE_FW_INIT_2:
1383                         max_wait = 20;
1384                         cur_state = MFI_STATE_FW_INIT_2;
1385                         break;
1386
1387                 case MFI_STATE_DEVICE_SCAN:
1388                         max_wait = 20;
1389                         cur_state = MFI_STATE_DEVICE_SCAN;
1390                         break;
1391
1392                 case MFI_STATE_FLUSH_CACHE:
1393                         max_wait = 20;
1394                         cur_state = MFI_STATE_FLUSH_CACHE;
1395                         break;
1396
1397                 default:
1398                         printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
1399                                fw_state);
1400                         return -ENODEV;
1401                 }
1402
1403                 /*
1404                  * The cur_state should not last for more than max_wait secs
1405                  */
1406                 for (i = 0; i < (max_wait * 1000); i++) {
1407                         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &  
1408                                         MFI_STATE_MASK ;
1409
1410                         if (fw_state == cur_state) {
1411                                 msleep(1);
1412                         } else
1413                                 break;
1414                 }
1415
1416                 /*
1417                  * Return error if fw_state hasn't changed after max_wait
1418                  */
1419                 if (fw_state == cur_state) {
1420                         printk(KERN_DEBUG "FW state [%d] hasn't changed "
1421                                "in %d secs\n", fw_state, max_wait);
1422                         return -ENODEV;
1423                 }
1424         };
1425         printk(KERN_INFO "megasas: FW now in Ready state\n");
1426
1427         return 0;
1428 }
1429
1430 /**
1431  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
1432  * @instance:                           Adapter soft state
1433  */
1434 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
1435 {
1436         int i;
1437         u32 max_cmd = instance->max_fw_cmds;
1438         struct megasas_cmd *cmd;
1439
1440         if (!instance->frame_dma_pool)
1441                 return;
1442
1443         /*
1444          * Return all frames to pool
1445          */
1446         for (i = 0; i < max_cmd; i++) {
1447
1448                 cmd = instance->cmd_list[i];
1449
1450                 if (cmd->frame)
1451                         pci_pool_free(instance->frame_dma_pool, cmd->frame,
1452                                       cmd->frame_phys_addr);
1453
1454                 if (cmd->sense)
1455                         pci_pool_free(instance->sense_dma_pool, cmd->sense,
1456                                       cmd->sense_phys_addr);
1457         }
1458
1459         /*
1460          * Now destroy the pool itself
1461          */
1462         pci_pool_destroy(instance->frame_dma_pool);
1463         pci_pool_destroy(instance->sense_dma_pool);
1464
1465         instance->frame_dma_pool = NULL;
1466         instance->sense_dma_pool = NULL;
1467 }
1468
1469 /**
1470  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
1471  * @instance:                   Adapter soft state
1472  *
1473  * Each command packet has an embedded DMA memory buffer that is used for
1474  * filling MFI frame and the SG list that immediately follows the frame. This
1475  * function creates those DMA memory buffers for each command packet by using
1476  * PCI pool facility.
1477  */
1478 static int megasas_create_frame_pool(struct megasas_instance *instance)
1479 {
1480         int i;
1481         u32 max_cmd;
1482         u32 sge_sz;
1483         u32 sgl_sz;
1484         u32 total_sz;
1485         u32 frame_count;
1486         struct megasas_cmd *cmd;
1487
1488         max_cmd = instance->max_fw_cmds;
1489
1490         /*
1491          * Size of our frame is 64 bytes for MFI frame, followed by max SG
1492          * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
1493          */
1494         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1495             sizeof(struct megasas_sge32);
1496
1497         /*
1498          * Calculated the number of 64byte frames required for SGL
1499          */
1500         sgl_sz = sge_sz * instance->max_num_sge;
1501         frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
1502
1503         /*
1504          * We need one extra frame for the MFI command
1505          */
1506         frame_count++;
1507
1508         total_sz = MEGAMFI_FRAME_SIZE * frame_count;
1509         /*
1510          * Use DMA pool facility provided by PCI layer
1511          */
1512         instance->frame_dma_pool = pci_pool_create("megasas frame pool",
1513                                                    instance->pdev, total_sz, 64,
1514                                                    0);
1515
1516         if (!instance->frame_dma_pool) {
1517                 printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
1518                 return -ENOMEM;
1519         }
1520
1521         instance->sense_dma_pool = pci_pool_create("megasas sense pool",
1522                                                    instance->pdev, 128, 4, 0);
1523
1524         if (!instance->sense_dma_pool) {
1525                 printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
1526
1527                 pci_pool_destroy(instance->frame_dma_pool);
1528                 instance->frame_dma_pool = NULL;
1529
1530                 return -ENOMEM;
1531         }
1532
1533         /*
1534          * Allocate and attach a frame to each of the commands in cmd_list.
1535          * By making cmd->index as the context instead of the &cmd, we can
1536          * always use 32bit context regardless of the architecture
1537          */
1538         for (i = 0; i < max_cmd; i++) {
1539
1540                 cmd = instance->cmd_list[i];
1541
1542                 cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
1543                                             GFP_KERNEL, &cmd->frame_phys_addr);
1544
1545                 cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
1546                                             GFP_KERNEL, &cmd->sense_phys_addr);
1547
1548                 /*
1549                  * megasas_teardown_frame_pool() takes care of freeing
1550                  * whatever has been allocated
1551                  */
1552                 if (!cmd->frame || !cmd->sense) {
1553                         printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
1554                         megasas_teardown_frame_pool(instance);
1555                         return -ENOMEM;
1556                 }
1557
1558                 cmd->frame->io.context = cmd->index;
1559         }
1560
1561         return 0;
1562 }
1563
1564 /**
1565  * megasas_free_cmds -  Free all the cmds in the free cmd pool
1566  * @instance:           Adapter soft state
1567  */
1568 static void megasas_free_cmds(struct megasas_instance *instance)
1569 {
1570         int i;
1571         /* First free the MFI frame pool */
1572         megasas_teardown_frame_pool(instance);
1573
1574         /* Free all the commands in the cmd_list */
1575         for (i = 0; i < instance->max_fw_cmds; i++)
1576                 kfree(instance->cmd_list[i]);
1577
1578         /* Free the cmd_list buffer itself */
1579         kfree(instance->cmd_list);
1580         instance->cmd_list = NULL;
1581
1582         INIT_LIST_HEAD(&instance->cmd_pool);
1583 }
1584
1585 /**
1586  * megasas_alloc_cmds - Allocates the command packets
1587  * @instance:           Adapter soft state
1588  *
1589  * Each command that is issued to the FW, whether IO commands from the OS or
1590  * internal commands like IOCTLs, are wrapped in local data structure called
1591  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
1592  * the FW.
1593  *
1594  * Each frame has a 32-bit field called context (tag). This context is used
1595  * to get back the megasas_cmd from the frame when a frame gets completed in
1596  * the ISR. Typically the address of the megasas_cmd itself would be used as
1597  * the context. But we wanted to keep the differences between 32 and 64 bit
1598  * systems to the mininum. We always use 32 bit integers for the context. In
1599  * this driver, the 32 bit values are the indices into an array cmd_list.
1600  * This array is used only to look up the megasas_cmd given the context. The
1601  * free commands themselves are maintained in a linked list called cmd_pool.
1602  */
1603 static int megasas_alloc_cmds(struct megasas_instance *instance)
1604 {
1605         int i;
1606         int j;
1607         u32 max_cmd;
1608         struct megasas_cmd *cmd;
1609
1610         max_cmd = instance->max_fw_cmds;
1611
1612         /*
1613          * instance->cmd_list is an array of struct megasas_cmd pointers.
1614          * Allocate the dynamic array first and then allocate individual
1615          * commands.
1616          */
1617         instance->cmd_list = kmalloc(sizeof(struct megasas_cmd *) * max_cmd,
1618                                      GFP_KERNEL);
1619
1620         if (!instance->cmd_list) {
1621                 printk(KERN_DEBUG "megasas: out of memory\n");
1622                 return -ENOMEM;
1623         }
1624
1625         memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) * max_cmd);
1626
1627         for (i = 0; i < max_cmd; i++) {
1628                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
1629                                                 GFP_KERNEL);
1630
1631                 if (!instance->cmd_list[i]) {
1632
1633                         for (j = 0; j < i; j++)
1634                                 kfree(instance->cmd_list[j]);
1635
1636                         kfree(instance->cmd_list);
1637                         instance->cmd_list = NULL;
1638
1639                         return -ENOMEM;
1640                 }
1641         }
1642
1643         /*
1644          * Add all the commands to command pool (instance->cmd_pool)
1645          */
1646         for (i = 0; i < max_cmd; i++) {
1647                 cmd = instance->cmd_list[i];
1648                 memset(cmd, 0, sizeof(struct megasas_cmd));
1649                 cmd->index = i;
1650                 cmd->instance = instance;
1651
1652                 list_add_tail(&cmd->list, &instance->cmd_pool);
1653         }
1654
1655         /*
1656          * Create a frame pool and assign one frame to each cmd
1657          */
1658         if (megasas_create_frame_pool(instance)) {
1659                 printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
1660                 megasas_free_cmds(instance);
1661         }
1662
1663         return 0;
1664 }
1665
1666 /**
1667  * megasas_get_controller_info -        Returns FW's controller structure
1668  * @instance:                           Adapter soft state
1669  * @ctrl_info:                          Controller information structure
1670  *
1671  * Issues an internal command (DCMD) to get the FW's controller structure.
1672  * This information is mainly used to find out the maximum IO transfer per
1673  * command supported by the FW.
1674  */
1675 static int
1676 megasas_get_ctrl_info(struct megasas_instance *instance,
1677                       struct megasas_ctrl_info *ctrl_info)
1678 {
1679         int ret = 0;
1680         struct megasas_cmd *cmd;
1681         struct megasas_dcmd_frame *dcmd;
1682         struct megasas_ctrl_info *ci;
1683         dma_addr_t ci_h = 0;
1684
1685         cmd = megasas_get_cmd(instance);
1686
1687         if (!cmd) {
1688                 printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
1689                 return -ENOMEM;
1690         }
1691
1692         dcmd = &cmd->frame->dcmd;
1693
1694         ci = pci_alloc_consistent(instance->pdev,
1695                                   sizeof(struct megasas_ctrl_info), &ci_h);
1696
1697         if (!ci) {
1698                 printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
1699                 megasas_return_cmd(instance, cmd);
1700                 return -ENOMEM;
1701         }
1702
1703         memset(ci, 0, sizeof(*ci));
1704         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1705
1706         dcmd->cmd = MFI_CMD_DCMD;
1707         dcmd->cmd_status = 0xFF;
1708         dcmd->sge_count = 1;
1709         dcmd->flags = MFI_FRAME_DIR_READ;
1710         dcmd->timeout = 0;
1711         dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info);
1712         dcmd->opcode = MR_DCMD_CTRL_GET_INFO;
1713         dcmd->sgl.sge32[0].phys_addr = ci_h;
1714         dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info);
1715
1716         if (!megasas_issue_polled(instance, cmd)) {
1717                 ret = 0;
1718                 memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
1719         } else {
1720                 ret = -1;
1721         }
1722
1723         pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
1724                             ci, ci_h);
1725
1726         megasas_return_cmd(instance, cmd);
1727         return ret;
1728 }
1729
1730 /**
1731  * megasas_complete_cmd_dpc      -      Returns FW's controller structure
1732  * @instance_addr:                      Address of adapter soft state
1733  *
1734  * Tasklet to complete cmds
1735  */
1736 static void megasas_complete_cmd_dpc(unsigned long instance_addr)
1737 {
1738         u32 producer;
1739         u32 consumer;
1740         u32 context;
1741         struct megasas_cmd *cmd;
1742         struct megasas_instance *instance = (struct megasas_instance *)instance_addr;
1743
1744         producer = *instance->producer;
1745         consumer = *instance->consumer;
1746
1747         while (consumer != producer) {
1748                 context = instance->reply_queue[consumer];
1749
1750                 cmd = instance->cmd_list[context];
1751
1752                 megasas_complete_cmd(instance, cmd, DID_OK);
1753
1754                 consumer++;
1755                 if (consumer == (instance->max_fw_cmds + 1)) {
1756                         consumer = 0;
1757                 }
1758         }
1759
1760         *instance->consumer = producer;
1761 }
1762
1763 /**
1764  * megasas_init_mfi -   Initializes the FW
1765  * @instance:           Adapter soft state
1766  *
1767  * This is the main function for initializing MFI firmware.
1768  */
1769 static int megasas_init_mfi(struct megasas_instance *instance)
1770 {
1771         u32 context_sz;
1772         u32 reply_q_sz;
1773         u32 max_sectors_1;
1774         u32 max_sectors_2;
1775         struct megasas_register_set __iomem *reg_set;
1776
1777         struct megasas_cmd *cmd;
1778         struct megasas_ctrl_info *ctrl_info;
1779
1780         struct megasas_init_frame *init_frame;
1781         struct megasas_init_queue_info *initq_info;
1782         dma_addr_t init_frame_h;
1783         dma_addr_t initq_info_h;
1784
1785         /*
1786          * Map the message registers
1787          */
1788         instance->base_addr = pci_resource_start(instance->pdev, 0);
1789
1790         if (pci_request_regions(instance->pdev, "megasas: LSI Logic")) {
1791                 printk(KERN_DEBUG "megasas: IO memory region busy!\n");
1792                 return -EBUSY;
1793         }
1794
1795         instance->reg_set = ioremap_nocache(instance->base_addr, 8192);
1796
1797         if (!instance->reg_set) {
1798                 printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
1799                 goto fail_ioremap;
1800         }
1801
1802         reg_set = instance->reg_set;
1803
1804         switch(instance->pdev->device)
1805         {
1806                 case PCI_DEVICE_ID_LSI_SAS1078R:        
1807                         instance->instancet = &megasas_instance_template_ppc;
1808                         break;
1809                 case PCI_DEVICE_ID_LSI_SAS1064R:
1810                 case PCI_DEVICE_ID_DELL_PERC5:
1811                 default:
1812                         instance->instancet = &megasas_instance_template_xscale;
1813                         break;
1814         }
1815
1816         /*
1817          * We expect the FW state to be READY
1818          */
1819         if (megasas_transition_to_ready(instance))
1820                 goto fail_ready_state;
1821
1822         /*
1823          * Get various operational parameters from status register
1824          */
1825         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
1826         /*
1827          * Reduce the max supported cmds by 1. This is to ensure that the
1828          * reply_q_sz (1 more than the max cmd that driver may send)
1829          * does not exceed max cmds that the FW can support
1830          */
1831         instance->max_fw_cmds = instance->max_fw_cmds-1;
1832         instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >> 
1833                                         0x10;
1834         /*
1835          * Create a pool of commands
1836          */
1837         if (megasas_alloc_cmds(instance))
1838                 goto fail_alloc_cmds;
1839
1840         /*
1841          * Allocate memory for reply queue. Length of reply queue should
1842          * be _one_ more than the maximum commands handled by the firmware.
1843          *
1844          * Note: When FW completes commands, it places corresponding contex
1845          * values in this circular reply queue. This circular queue is a fairly
1846          * typical producer-consumer queue. FW is the producer (of completed
1847          * commands) and the driver is the consumer.
1848          */
1849         context_sz = sizeof(u32);
1850         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
1851
1852         instance->reply_queue = pci_alloc_consistent(instance->pdev,
1853                                                      reply_q_sz,
1854                                                      &instance->reply_queue_h);
1855
1856         if (!instance->reply_queue) {
1857                 printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
1858                 goto fail_reply_queue;
1859         }
1860
1861         /*
1862          * Prepare a init frame. Note the init frame points to queue info
1863          * structure. Each frame has SGL allocated after first 64 bytes. For
1864          * this frame - since we don't need any SGL - we use SGL's space as
1865          * queue info structure
1866          *
1867          * We will not get a NULL command below. We just created the pool.
1868          */
1869         cmd = megasas_get_cmd(instance);
1870
1871         init_frame = (struct megasas_init_frame *)cmd->frame;
1872         initq_info = (struct megasas_init_queue_info *)
1873             ((unsigned long)init_frame + 64);
1874
1875         init_frame_h = cmd->frame_phys_addr;
1876         initq_info_h = init_frame_h + 64;
1877
1878         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
1879         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
1880
1881         initq_info->reply_queue_entries = instance->max_fw_cmds + 1;
1882         initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h;
1883
1884         initq_info->producer_index_phys_addr_lo = instance->producer_h;
1885         initq_info->consumer_index_phys_addr_lo = instance->consumer_h;
1886
1887         init_frame->cmd = MFI_CMD_INIT;
1888         init_frame->cmd_status = 0xFF;
1889         init_frame->queue_info_new_phys_addr_lo = initq_info_h;
1890
1891         init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info);
1892
1893         /*
1894          * disable the intr before firing the init frame to FW
1895          */
1896         instance->instancet->disable_intr(instance->reg_set);
1897
1898         /*
1899          * Issue the init frame in polled mode
1900          */
1901         if (megasas_issue_polled(instance, cmd)) {
1902                 printk(KERN_DEBUG "megasas: Failed to init firmware\n");
1903                 goto fail_fw_init;
1904         }
1905
1906         megasas_return_cmd(instance, cmd);
1907
1908         ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
1909
1910         /*
1911          * Compute the max allowed sectors per IO: The controller info has two
1912          * limits on max sectors. Driver should use the minimum of these two.
1913          *
1914          * 1 << stripe_sz_ops.min = max sectors per strip
1915          *
1916          * Note that older firmwares ( < FW ver 30) didn't report information
1917          * to calculate max_sectors_1. So the number ended up as zero always.
1918          */
1919         if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
1920
1921                 max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
1922                     ctrl_info->max_strips_per_io;
1923                 max_sectors_2 = ctrl_info->max_request_size;
1924
1925                 instance->max_sectors_per_req = (max_sectors_1 < max_sectors_2)
1926                     ? max_sectors_1 : max_sectors_2;
1927         } else
1928                 instance->max_sectors_per_req = instance->max_num_sge *
1929                     PAGE_SIZE / 512;
1930
1931         kfree(ctrl_info);
1932
1933         /*
1934         * Setup tasklet for cmd completion
1935         */
1936
1937         tasklet_init(&instance->isr_tasklet, megasas_complete_cmd_dpc,
1938                         (unsigned long)instance);
1939         return 0;
1940
1941       fail_fw_init:
1942         megasas_return_cmd(instance, cmd);
1943
1944         pci_free_consistent(instance->pdev, reply_q_sz,
1945                             instance->reply_queue, instance->reply_queue_h);
1946       fail_reply_queue:
1947         megasas_free_cmds(instance);
1948
1949       fail_alloc_cmds:
1950       fail_ready_state:
1951         iounmap(instance->reg_set);
1952
1953       fail_ioremap:
1954         pci_release_regions(instance->pdev);
1955
1956         return -EINVAL;
1957 }
1958
1959 /**
1960  * megasas_release_mfi -        Reverses the FW initialization
1961  * @intance:                    Adapter soft state
1962  */
1963 static void megasas_release_mfi(struct megasas_instance *instance)
1964 {
1965         u32 reply_q_sz = sizeof(u32) * (instance->max_fw_cmds + 1);
1966
1967         pci_free_consistent(instance->pdev, reply_q_sz,
1968                             instance->reply_queue, instance->reply_queue_h);
1969
1970         megasas_free_cmds(instance);
1971
1972         iounmap(instance->reg_set);
1973
1974         pci_release_regions(instance->pdev);
1975 }
1976
1977 /**
1978  * megasas_get_seq_num -        Gets latest event sequence numbers
1979  * @instance:                   Adapter soft state
1980  * @eli:                        FW event log sequence numbers information
1981  *
1982  * FW maintains a log of all events in a non-volatile area. Upper layers would
1983  * usually find out the latest sequence number of the events, the seq number at
1984  * the boot etc. They would "read" all the events below the latest seq number
1985  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
1986  * number), they would subsribe to AEN (asynchronous event notification) and
1987  * wait for the events to happen.
1988  */
1989 static int
1990 megasas_get_seq_num(struct megasas_instance *instance,
1991                     struct megasas_evt_log_info *eli)
1992 {
1993         struct megasas_cmd *cmd;
1994         struct megasas_dcmd_frame *dcmd;
1995         struct megasas_evt_log_info *el_info;
1996         dma_addr_t el_info_h = 0;
1997
1998         cmd = megasas_get_cmd(instance);
1999
2000         if (!cmd) {
2001                 return -ENOMEM;
2002         }
2003
2004         dcmd = &cmd->frame->dcmd;
2005         el_info = pci_alloc_consistent(instance->pdev,
2006                                        sizeof(struct megasas_evt_log_info),
2007                                        &el_info_h);
2008
2009         if (!el_info) {
2010                 megasas_return_cmd(instance, cmd);
2011                 return -ENOMEM;
2012         }
2013
2014         memset(el_info, 0, sizeof(*el_info));
2015         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2016
2017         dcmd->cmd = MFI_CMD_DCMD;
2018         dcmd->cmd_status = 0x0;
2019         dcmd->sge_count = 1;
2020         dcmd->flags = MFI_FRAME_DIR_READ;
2021         dcmd->timeout = 0;
2022         dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info);
2023         dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO;
2024         dcmd->sgl.sge32[0].phys_addr = el_info_h;
2025         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info);
2026
2027         megasas_issue_blocked_cmd(instance, cmd);
2028
2029         /*
2030          * Copy the data back into callers buffer
2031          */
2032         memcpy(eli, el_info, sizeof(struct megasas_evt_log_info));
2033
2034         pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
2035                             el_info, el_info_h);
2036
2037         megasas_return_cmd(instance, cmd);
2038
2039         return 0;
2040 }
2041
2042 /**
2043  * megasas_register_aen -       Registers for asynchronous event notification
2044  * @instance:                   Adapter soft state
2045  * @seq_num:                    The starting sequence number
2046  * @class_locale:               Class of the event
2047  *
2048  * This function subscribes for AEN for events beyond the @seq_num. It requests
2049  * to be notified if and only if the event is of type @class_locale
2050  */
2051 static int
2052 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
2053                      u32 class_locale_word)
2054 {
2055         int ret_val;
2056         struct megasas_cmd *cmd;
2057         struct megasas_dcmd_frame *dcmd;
2058         union megasas_evt_class_locale curr_aen;
2059         union megasas_evt_class_locale prev_aen;
2060
2061         /*
2062          * If there an AEN pending already (aen_cmd), check if the
2063          * class_locale of that pending AEN is inclusive of the new
2064          * AEN request we currently have. If it is, then we don't have
2065          * to do anything. In other words, whichever events the current
2066          * AEN request is subscribing to, have already been subscribed
2067          * to.
2068          *
2069          * If the old_cmd is _not_ inclusive, then we have to abort
2070          * that command, form a class_locale that is superset of both
2071          * old and current and re-issue to the FW
2072          */
2073
2074         curr_aen.word = class_locale_word;
2075
2076         if (instance->aen_cmd) {
2077
2078                 prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
2079
2080                 /*
2081                  * A class whose enum value is smaller is inclusive of all
2082                  * higher values. If a PROGRESS (= -1) was previously
2083                  * registered, then a new registration requests for higher
2084                  * classes need not be sent to FW. They are automatically
2085                  * included.
2086                  *
2087                  * Locale numbers don't have such hierarchy. They are bitmap
2088                  * values
2089                  */
2090                 if ((prev_aen.members.class <= curr_aen.members.class) &&
2091                     !((prev_aen.members.locale & curr_aen.members.locale) ^
2092                       curr_aen.members.locale)) {
2093                         /*
2094                          * Previously issued event registration includes
2095                          * current request. Nothing to do.
2096                          */
2097                         return 0;
2098                 } else {
2099                         curr_aen.members.locale |= prev_aen.members.locale;
2100
2101                         if (prev_aen.members.class < curr_aen.members.class)
2102                                 curr_aen.members.class = prev_aen.members.class;
2103
2104                         instance->aen_cmd->abort_aen = 1;
2105                         ret_val = megasas_issue_blocked_abort_cmd(instance,
2106                                                                   instance->
2107                                                                   aen_cmd);
2108
2109                         if (ret_val) {
2110                                 printk(KERN_DEBUG "megasas: Failed to abort "
2111                                        "previous AEN command\n");
2112                                 return ret_val;
2113                         }
2114                 }
2115         }
2116
2117         cmd = megasas_get_cmd(instance);
2118
2119         if (!cmd)
2120                 return -ENOMEM;
2121
2122         dcmd = &cmd->frame->dcmd;
2123
2124         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
2125
2126         /*
2127          * Prepare DCMD for aen registration
2128          */
2129         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2130
2131         dcmd->cmd = MFI_CMD_DCMD;
2132         dcmd->cmd_status = 0x0;
2133         dcmd->sge_count = 1;
2134         dcmd->flags = MFI_FRAME_DIR_READ;
2135         dcmd->timeout = 0;
2136         dcmd->data_xfer_len = sizeof(struct megasas_evt_detail);
2137         dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT;
2138         dcmd->mbox.w[0] = seq_num;
2139         dcmd->mbox.w[1] = curr_aen.word;
2140         dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h;
2141         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail);
2142
2143         /*
2144          * Store reference to the cmd used to register for AEN. When an
2145          * application wants us to register for AEN, we have to abort this
2146          * cmd and re-register with a new EVENT LOCALE supplied by that app
2147          */
2148         instance->aen_cmd = cmd;
2149
2150         /*
2151          * Issue the aen registration frame
2152          */
2153         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
2154
2155         return 0;
2156 }
2157
2158 /**
2159  * megasas_start_aen -  Subscribes to AEN during driver load time
2160  * @instance:           Adapter soft state
2161  */
2162 static int megasas_start_aen(struct megasas_instance *instance)
2163 {
2164         struct megasas_evt_log_info eli;
2165         union megasas_evt_class_locale class_locale;
2166
2167         /*
2168          * Get the latest sequence number from FW
2169          */
2170         memset(&eli, 0, sizeof(eli));
2171
2172         if (megasas_get_seq_num(instance, &eli))
2173                 return -1;
2174
2175         /*
2176          * Register AEN with FW for latest sequence number plus 1
2177          */
2178         class_locale.members.reserved = 0;
2179         class_locale.members.locale = MR_EVT_LOCALE_ALL;
2180         class_locale.members.class = MR_EVT_CLASS_DEBUG;
2181
2182         return megasas_register_aen(instance, eli.newest_seq_num + 1,
2183                                     class_locale.word);
2184 }
2185
2186 /**
2187  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
2188  * @instance:           Adapter soft state
2189  */
2190 static int megasas_io_attach(struct megasas_instance *instance)
2191 {
2192         struct Scsi_Host *host = instance->host;
2193
2194         /*
2195          * Export parameters required by SCSI mid-layer
2196          */
2197         host->irq = instance->pdev->irq;
2198         host->unique_id = instance->unique_id;
2199         host->can_queue = instance->max_fw_cmds - MEGASAS_INT_CMDS;
2200         host->this_id = instance->init_id;
2201         host->sg_tablesize = instance->max_num_sge;
2202         host->max_sectors = instance->max_sectors_per_req;
2203         host->cmd_per_lun = 128;
2204         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
2205         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
2206         host->max_lun = MEGASAS_MAX_LUN;
2207         host->max_cmd_len = 16;
2208
2209         /*
2210          * Notify the mid-layer about the new controller
2211          */
2212         if (scsi_add_host(host, &instance->pdev->dev)) {
2213                 printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
2214                 return -ENODEV;
2215         }
2216
2217         /*
2218          * Trigger SCSI to scan our drives
2219          */
2220         scsi_scan_host(host);
2221         return 0;
2222 }
2223
2224 /**
2225  * megasas_probe_one -  PCI hotplug entry point
2226  * @pdev:               PCI device structure
2227  * @id:                 PCI ids of supported hotplugged adapter 
2228  */
2229 static int __devinit
2230 megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
2231 {
2232         int rval;
2233         struct Scsi_Host *host;
2234         struct megasas_instance *instance;
2235
2236         /*
2237          * Announce PCI information
2238          */
2239         printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
2240                pdev->vendor, pdev->device, pdev->subsystem_vendor,
2241                pdev->subsystem_device);
2242
2243         printk("bus %d:slot %d:func %d\n",
2244                pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
2245
2246         /*
2247          * PCI prepping: enable device set bus mastering and dma mask
2248          */
2249         rval = pci_enable_device(pdev);
2250
2251         if (rval) {
2252                 return rval;
2253         }
2254
2255         pci_set_master(pdev);
2256
2257         /*
2258          * All our contollers are capable of performing 64-bit DMA
2259          */
2260         if (IS_DMA64) {
2261                 if (pci_set_dma_mask(pdev, DMA_64BIT_MASK) != 0) {
2262
2263                         if (pci_set_dma_mask(pdev, DMA_32BIT_MASK) != 0)
2264                                 goto fail_set_dma_mask;
2265                 }
2266         } else {
2267                 if (pci_set_dma_mask(pdev, DMA_32BIT_MASK) != 0)
2268                         goto fail_set_dma_mask;
2269         }
2270
2271         host = scsi_host_alloc(&megasas_template,
2272                                sizeof(struct megasas_instance));
2273
2274         if (!host) {
2275                 printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
2276                 goto fail_alloc_instance;
2277         }
2278
2279         instance = (struct megasas_instance *)host->hostdata;
2280         memset(instance, 0, sizeof(*instance));
2281
2282         instance->producer = pci_alloc_consistent(pdev, sizeof(u32),
2283                                                   &instance->producer_h);
2284         instance->consumer = pci_alloc_consistent(pdev, sizeof(u32),
2285                                                   &instance->consumer_h);
2286
2287         if (!instance->producer || !instance->consumer) {
2288                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
2289                        "producer, consumer\n");
2290                 goto fail_alloc_dma_buf;
2291         }
2292
2293         *instance->producer = 0;
2294         *instance->consumer = 0;
2295
2296         instance->evt_detail = pci_alloc_consistent(pdev,
2297                                                     sizeof(struct
2298                                                            megasas_evt_detail),
2299                                                     &instance->evt_detail_h);
2300
2301         if (!instance->evt_detail) {
2302                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
2303                        "event detail structure\n");
2304                 goto fail_alloc_dma_buf;
2305         }
2306
2307         /*
2308          * Initialize locks and queues
2309          */
2310         INIT_LIST_HEAD(&instance->cmd_pool);
2311
2312         atomic_set(&instance->fw_outstanding,0);
2313
2314         init_waitqueue_head(&instance->int_cmd_wait_q);
2315         init_waitqueue_head(&instance->abort_cmd_wait_q);
2316
2317         spin_lock_init(&instance->cmd_pool_lock);
2318
2319         sema_init(&instance->aen_mutex, 1);
2320         sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
2321
2322         /*
2323          * Initialize PCI related and misc parameters
2324          */
2325         instance->pdev = pdev;
2326         instance->host = host;
2327         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
2328         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
2329
2330         megasas_dbg_lvl = 0;
2331
2332         /*
2333          * Initialize MFI Firmware
2334          */
2335         if (megasas_init_mfi(instance))
2336                 goto fail_init_mfi;
2337
2338         /*
2339          * Register IRQ
2340          */
2341         if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED, "megasas", instance)) {
2342                 printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
2343                 goto fail_irq;
2344         }
2345
2346         instance->instancet->enable_intr(instance->reg_set);
2347
2348         /*
2349          * Store instance in PCI softstate
2350          */
2351         pci_set_drvdata(pdev, instance);
2352
2353         /*
2354          * Add this controller to megasas_mgmt_info structure so that it
2355          * can be exported to management applications
2356          */
2357         megasas_mgmt_info.count++;
2358         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
2359         megasas_mgmt_info.max_index++;
2360
2361         /*
2362          * Initiate AEN (Asynchronous Event Notification)
2363          */
2364         if (megasas_start_aen(instance)) {
2365                 printk(KERN_DEBUG "megasas: start aen failed\n");
2366                 goto fail_start_aen;
2367         }
2368
2369         /*
2370          * Register with SCSI mid-layer
2371          */
2372         if (megasas_io_attach(instance))
2373                 goto fail_io_attach;
2374
2375         return 0;
2376
2377       fail_start_aen:
2378       fail_io_attach:
2379         megasas_mgmt_info.count--;
2380         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
2381         megasas_mgmt_info.max_index--;
2382
2383         pci_set_drvdata(pdev, NULL);
2384         instance->instancet->disable_intr(instance->reg_set);
2385         free_irq(instance->pdev->irq, instance);
2386
2387         megasas_release_mfi(instance);
2388
2389       fail_irq:
2390       fail_init_mfi:
2391       fail_alloc_dma_buf:
2392         if (instance->evt_detail)
2393                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
2394                                     instance->evt_detail,
2395                                     instance->evt_detail_h);
2396
2397         if (instance->producer)
2398                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
2399                                     instance->producer_h);
2400         if (instance->consumer)
2401                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
2402                                     instance->consumer_h);
2403         scsi_host_put(host);
2404
2405       fail_alloc_instance:
2406       fail_set_dma_mask:
2407         pci_disable_device(pdev);
2408
2409         return -ENODEV;
2410 }
2411
2412 /**
2413  * megasas_flush_cache -        Requests FW to flush all its caches
2414  * @instance:                   Adapter soft state
2415  */
2416 static void megasas_flush_cache(struct megasas_instance *instance)
2417 {
2418         struct megasas_cmd *cmd;
2419         struct megasas_dcmd_frame *dcmd;
2420
2421         cmd = megasas_get_cmd(instance);
2422
2423         if (!cmd)
2424                 return;
2425
2426         dcmd = &cmd->frame->dcmd;
2427
2428         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2429
2430         dcmd->cmd = MFI_CMD_DCMD;
2431         dcmd->cmd_status = 0x0;
2432         dcmd->sge_count = 0;
2433         dcmd->flags = MFI_FRAME_DIR_NONE;
2434         dcmd->timeout = 0;
2435         dcmd->data_xfer_len = 0;
2436         dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH;
2437         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
2438
2439         megasas_issue_blocked_cmd(instance, cmd);
2440
2441         megasas_return_cmd(instance, cmd);
2442
2443         return;
2444 }
2445
2446 /**
2447  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
2448  * @instance:                           Adapter soft state
2449  */
2450 static void megasas_shutdown_controller(struct megasas_instance *instance)
2451 {
2452         struct megasas_cmd *cmd;
2453         struct megasas_dcmd_frame *dcmd;
2454
2455         cmd = megasas_get_cmd(instance);
2456
2457         if (!cmd)
2458                 return;
2459
2460         if (instance->aen_cmd)
2461                 megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd);
2462
2463         dcmd = &cmd->frame->dcmd;
2464
2465         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2466
2467         dcmd->cmd = MFI_CMD_DCMD;
2468         dcmd->cmd_status = 0x0;
2469         dcmd->sge_count = 0;
2470         dcmd->flags = MFI_FRAME_DIR_NONE;
2471         dcmd->timeout = 0;
2472         dcmd->data_xfer_len = 0;
2473         dcmd->opcode = MR_DCMD_CTRL_SHUTDOWN;
2474
2475         megasas_issue_blocked_cmd(instance, cmd);
2476
2477         megasas_return_cmd(instance, cmd);
2478
2479         return;
2480 }
2481
2482 /**
2483  * megasas_detach_one - PCI hot"un"plug entry point
2484  * @pdev:               PCI device structure
2485  */
2486 static void megasas_detach_one(struct pci_dev *pdev)
2487 {
2488         int i;
2489         struct Scsi_Host *host;
2490         struct megasas_instance *instance;
2491
2492         instance = pci_get_drvdata(pdev);
2493         host = instance->host;
2494
2495         scsi_remove_host(instance->host);
2496         megasas_flush_cache(instance);
2497         megasas_shutdown_controller(instance);
2498         tasklet_kill(&instance->isr_tasklet);
2499
2500         /*
2501          * Take the instance off the instance array. Note that we will not
2502          * decrement the max_index. We let this array be sparse array
2503          */
2504         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
2505                 if (megasas_mgmt_info.instance[i] == instance) {
2506                         megasas_mgmt_info.count--;
2507                         megasas_mgmt_info.instance[i] = NULL;
2508
2509                         break;
2510                 }
2511         }
2512
2513         pci_set_drvdata(instance->pdev, NULL);
2514
2515         instance->instancet->disable_intr(instance->reg_set);
2516
2517         free_irq(instance->pdev->irq, instance);
2518
2519         megasas_release_mfi(instance);
2520
2521         pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
2522                             instance->evt_detail, instance->evt_detail_h);
2523
2524         pci_free_consistent(pdev, sizeof(u32), instance->producer,
2525                             instance->producer_h);
2526
2527         pci_free_consistent(pdev, sizeof(u32), instance->consumer,
2528                             instance->consumer_h);
2529
2530         scsi_host_put(host);
2531
2532         pci_set_drvdata(pdev, NULL);
2533
2534         pci_disable_device(pdev);
2535
2536         return;
2537 }
2538
2539 /**
2540  * megasas_shutdown -   Shutdown entry point
2541  * @device:             Generic device structure
2542  */
2543 static void megasas_shutdown(struct pci_dev *pdev)
2544 {
2545         struct megasas_instance *instance = pci_get_drvdata(pdev);
2546         megasas_flush_cache(instance);
2547 }
2548
2549 /**
2550  * megasas_mgmt_open -  char node "open" entry point
2551  */
2552 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
2553 {
2554         /*
2555          * Allow only those users with admin rights
2556          */
2557         if (!capable(CAP_SYS_ADMIN))
2558                 return -EACCES;
2559
2560         return 0;
2561 }
2562
2563 /**
2564  * megasas_mgmt_release - char node "release" entry point
2565  */
2566 static int megasas_mgmt_release(struct inode *inode, struct file *filep)
2567 {
2568         filep->private_data = NULL;
2569         fasync_helper(-1, filep, 0, &megasas_async_queue);
2570
2571         return 0;
2572 }
2573
2574 /**
2575  * megasas_mgmt_fasync -        Async notifier registration from applications
2576  *
2577  * This function adds the calling process to a driver global queue. When an
2578  * event occurs, SIGIO will be sent to all processes in this queue.
2579  */
2580 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
2581 {
2582         int rc;
2583
2584         mutex_lock(&megasas_async_queue_mutex);
2585
2586         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
2587
2588         mutex_unlock(&megasas_async_queue_mutex);
2589
2590         if (rc >= 0) {
2591                 /* For sanity check when we get ioctl */
2592                 filep->private_data = filep;
2593                 return 0;
2594         }
2595
2596         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
2597
2598         return rc;
2599 }
2600
2601 /**
2602  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
2603  * @instance:                   Adapter soft state
2604  * @argp:                       User's ioctl packet
2605  */
2606 static int
2607 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
2608                       struct megasas_iocpacket __user * user_ioc,
2609                       struct megasas_iocpacket *ioc)
2610 {
2611         struct megasas_sge32 *kern_sge32;
2612         struct megasas_cmd *cmd;
2613         void *kbuff_arr[MAX_IOCTL_SGE];
2614         dma_addr_t buf_handle = 0;
2615         int error = 0, i;
2616         void *sense = NULL;
2617         dma_addr_t sense_handle;
2618         u32 *sense_ptr;
2619
2620         memset(kbuff_arr, 0, sizeof(kbuff_arr));
2621
2622         if (ioc->sge_count > MAX_IOCTL_SGE) {
2623                 printk(KERN_DEBUG "megasas: SGE count [%d] >  max limit [%d]\n",
2624                        ioc->sge_count, MAX_IOCTL_SGE);
2625                 return -EINVAL;
2626         }
2627
2628         cmd = megasas_get_cmd(instance);
2629         if (!cmd) {
2630                 printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
2631                 return -ENOMEM;
2632         }
2633
2634         /*
2635          * User's IOCTL packet has 2 frames (maximum). Copy those two
2636          * frames into our cmd's frames. cmd->frame's context will get
2637          * overwritten when we copy from user's frames. So set that value
2638          * alone separately
2639          */
2640         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
2641         cmd->frame->hdr.context = cmd->index;
2642
2643         /*
2644          * The management interface between applications and the fw uses
2645          * MFI frames. E.g, RAID configuration changes, LD property changes
2646          * etc are accomplishes through different kinds of MFI frames. The
2647          * driver needs to care only about substituting user buffers with
2648          * kernel buffers in SGLs. The location of SGL is embedded in the
2649          * struct iocpacket itself.
2650          */
2651         kern_sge32 = (struct megasas_sge32 *)
2652             ((unsigned long)cmd->frame + ioc->sgl_off);
2653
2654         /*
2655          * For each user buffer, create a mirror buffer and copy in
2656          */
2657         for (i = 0; i < ioc->sge_count; i++) {
2658                 kbuff_arr[i] = pci_alloc_consistent(instance->pdev,
2659                                                     ioc->sgl[i].iov_len,
2660                                                     &buf_handle);
2661                 if (!kbuff_arr[i]) {
2662                         printk(KERN_DEBUG "megasas: Failed to alloc "
2663                                "kernel SGL buffer for IOCTL \n");
2664                         error = -ENOMEM;
2665                         goto out;
2666                 }
2667
2668                 /*
2669                  * We don't change the dma_coherent_mask, so
2670                  * pci_alloc_consistent only returns 32bit addresses
2671                  */
2672                 kern_sge32[i].phys_addr = (u32) buf_handle;
2673                 kern_sge32[i].length = ioc->sgl[i].iov_len;
2674
2675                 /*
2676                  * We created a kernel buffer corresponding to the
2677                  * user buffer. Now copy in from the user buffer
2678                  */
2679                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
2680                                    (u32) (ioc->sgl[i].iov_len))) {
2681                         error = -EFAULT;
2682                         goto out;
2683                 }
2684         }
2685
2686         if (ioc->sense_len) {
2687                 sense = pci_alloc_consistent(instance->pdev, ioc->sense_len,
2688                                              &sense_handle);
2689                 if (!sense) {
2690                         error = -ENOMEM;
2691                         goto out;
2692                 }
2693
2694                 sense_ptr =
2695                     (u32 *) ((unsigned long)cmd->frame + ioc->sense_off);
2696                 *sense_ptr = sense_handle;
2697         }
2698
2699         /*
2700          * Set the sync_cmd flag so that the ISR knows not to complete this
2701          * cmd to the SCSI mid-layer
2702          */
2703         cmd->sync_cmd = 1;
2704         megasas_issue_blocked_cmd(instance, cmd);
2705         cmd->sync_cmd = 0;
2706
2707         /*
2708          * copy out the kernel buffers to user buffers
2709          */
2710         for (i = 0; i < ioc->sge_count; i++) {
2711                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
2712                                  ioc->sgl[i].iov_len)) {
2713                         error = -EFAULT;
2714                         goto out;
2715                 }
2716         }
2717
2718         /*
2719          * copy out the sense
2720          */
2721         if (ioc->sense_len) {
2722                 /*
2723                  * sense_ptr points to the location that has the user
2724                  * sense buffer address
2725                  */
2726                 sense_ptr = (u32 *) ((unsigned long)ioc->frame.raw +
2727                                      ioc->sense_off);
2728
2729                 if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
2730                                  sense, ioc->sense_len)) {
2731                         error = -EFAULT;
2732                         goto out;
2733                 }
2734         }
2735
2736         /*
2737          * copy the status codes returned by the fw
2738          */
2739         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
2740                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
2741                 printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
2742                 error = -EFAULT;
2743         }
2744
2745       out:
2746         if (sense) {
2747                 pci_free_consistent(instance->pdev, ioc->sense_len,
2748                                     sense, sense_handle);
2749         }
2750
2751         for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) {
2752                 pci_free_consistent(instance->pdev,
2753                                     kern_sge32[i].length,
2754                                     kbuff_arr[i], kern_sge32[i].phys_addr);
2755         }
2756
2757         megasas_return_cmd(instance, cmd);
2758         return error;
2759 }
2760
2761 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
2762 {
2763         int i;
2764
2765         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
2766
2767                 if ((megasas_mgmt_info.instance[i]) &&
2768                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
2769                         return megasas_mgmt_info.instance[i];
2770         }
2771
2772         return NULL;
2773 }
2774
2775 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
2776 {
2777         struct megasas_iocpacket __user *user_ioc =
2778             (struct megasas_iocpacket __user *)arg;
2779         struct megasas_iocpacket *ioc;
2780         struct megasas_instance *instance;
2781         int error;
2782
2783         ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
2784         if (!ioc)
2785                 return -ENOMEM;
2786
2787         if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
2788                 error = -EFAULT;
2789                 goto out_kfree_ioc;
2790         }
2791
2792         instance = megasas_lookup_instance(ioc->host_no);
2793         if (!instance) {
2794                 error = -ENODEV;
2795                 goto out_kfree_ioc;
2796         }
2797
2798         /*
2799          * We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
2800          */
2801         if (down_interruptible(&instance->ioctl_sem)) {
2802                 error = -ERESTARTSYS;
2803                 goto out_kfree_ioc;
2804         }
2805         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
2806         up(&instance->ioctl_sem);
2807
2808       out_kfree_ioc:
2809         kfree(ioc);
2810         return error;
2811 }
2812
2813 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
2814 {
2815         struct megasas_instance *instance;
2816         struct megasas_aen aen;
2817         int error;
2818
2819         if (file->private_data != file) {
2820                 printk(KERN_DEBUG "megasas: fasync_helper was not "
2821                        "called first\n");
2822                 return -EINVAL;
2823         }
2824
2825         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
2826                 return -EFAULT;
2827
2828         instance = megasas_lookup_instance(aen.host_no);
2829
2830         if (!instance)
2831                 return -ENODEV;
2832
2833         down(&instance->aen_mutex);
2834         error = megasas_register_aen(instance, aen.seq_num,
2835                                      aen.class_locale_word);
2836         up(&instance->aen_mutex);
2837         return error;
2838 }
2839
2840 /**
2841  * megasas_mgmt_ioctl - char node ioctl entry point
2842  */
2843 static long
2844 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2845 {
2846         switch (cmd) {
2847         case MEGASAS_IOC_FIRMWARE:
2848                 return megasas_mgmt_ioctl_fw(file, arg);
2849
2850         case MEGASAS_IOC_GET_AEN:
2851                 return megasas_mgmt_ioctl_aen(file, arg);
2852         }
2853
2854         return -ENOTTY;
2855 }
2856
2857 #ifdef CONFIG_COMPAT
2858 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
2859 {
2860         struct compat_megasas_iocpacket __user *cioc =
2861             (struct compat_megasas_iocpacket __user *)arg;
2862         struct megasas_iocpacket __user *ioc =
2863             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
2864         int i;
2865         int error = 0;
2866
2867         if (clear_user(ioc, sizeof(*ioc)))
2868                 return -EFAULT;
2869
2870         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
2871             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
2872             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
2873             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
2874             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
2875             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
2876                 return -EFAULT;
2877
2878         for (i = 0; i < MAX_IOCTL_SGE; i++) {
2879                 compat_uptr_t ptr;
2880
2881                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
2882                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
2883                     copy_in_user(&ioc->sgl[i].iov_len,
2884                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
2885                         return -EFAULT;
2886         }
2887
2888         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
2889
2890         if (copy_in_user(&cioc->frame.hdr.cmd_status,
2891                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
2892                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
2893                 return -EFAULT;
2894         }
2895         return error;
2896 }
2897
2898 static long
2899 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
2900                           unsigned long arg)
2901 {
2902         switch (cmd) {
2903         case MEGASAS_IOC_FIRMWARE32:
2904                 return megasas_mgmt_compat_ioctl_fw(file, arg);
2905         case MEGASAS_IOC_GET_AEN:
2906                 return megasas_mgmt_ioctl_aen(file, arg);
2907         }
2908
2909         return -ENOTTY;
2910 }
2911 #endif
2912
2913 /*
2914  * File operations structure for management interface
2915  */
2916 static struct file_operations megasas_mgmt_fops = {
2917         .owner = THIS_MODULE,
2918         .open = megasas_mgmt_open,
2919         .release = megasas_mgmt_release,
2920         .fasync = megasas_mgmt_fasync,
2921         .unlocked_ioctl = megasas_mgmt_ioctl,
2922 #ifdef CONFIG_COMPAT
2923         .compat_ioctl = megasas_mgmt_compat_ioctl,
2924 #endif
2925 };
2926
2927 /*
2928  * PCI hotplug support registration structure
2929  */
2930 static struct pci_driver megasas_pci_driver = {
2931
2932         .name = "megaraid_sas",
2933         .id_table = megasas_pci_table,
2934         .probe = megasas_probe_one,
2935         .remove = __devexit_p(megasas_detach_one),
2936         .shutdown = megasas_shutdown,
2937 };
2938
2939 /*
2940  * Sysfs driver attributes
2941  */
2942 static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
2943 {
2944         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
2945                         MEGASAS_VERSION);
2946 }
2947
2948 static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
2949
2950 static ssize_t
2951 megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
2952 {
2953         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
2954                         MEGASAS_RELDATE);
2955 }
2956
2957 static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
2958                    NULL);
2959
2960 static ssize_t
2961 megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
2962 {
2963         return sprintf(buf,"%u",megasas_dbg_lvl);
2964 }
2965
2966 static ssize_t
2967 megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
2968 {
2969         int retval = count;
2970         if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
2971                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
2972                 retval = -EINVAL;
2973         }
2974         return retval;
2975 }
2976
2977 static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUGO, megasas_sysfs_show_dbg_lvl,
2978                    megasas_sysfs_set_dbg_lvl);
2979
2980 /**
2981  * megasas_init - Driver load entry point
2982  */
2983 static int __init megasas_init(void)
2984 {
2985         int rval;
2986
2987         /*
2988          * Announce driver version and other information
2989          */
2990         printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
2991                MEGASAS_EXT_VERSION);
2992
2993         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
2994
2995         /*
2996          * Register character device node
2997          */
2998         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
2999
3000         if (rval < 0) {
3001                 printk(KERN_DEBUG "megasas: failed to open device node\n");
3002                 return rval;
3003         }
3004
3005         megasas_mgmt_majorno = rval;
3006
3007         /*
3008          * Register ourselves as PCI hotplug module
3009          */
3010         rval = pci_register_driver(&megasas_pci_driver);
3011
3012         if (rval) {
3013                 printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
3014                 goto err_pcidrv;
3015         }
3016
3017         rval = driver_create_file(&megasas_pci_driver.driver,
3018                                   &driver_attr_version);
3019         if (rval)
3020                 goto err_dcf_attr_ver;
3021         rval = driver_create_file(&megasas_pci_driver.driver,
3022                                   &driver_attr_release_date);
3023         if (rval)
3024                 goto err_dcf_rel_date;
3025         rval = driver_create_file(&megasas_pci_driver.driver,
3026                                   &driver_attr_dbg_lvl);
3027         if (rval)
3028                 goto err_dcf_dbg_lvl;
3029
3030         return rval;
3031 err_dcf_dbg_lvl:
3032         driver_remove_file(&megasas_pci_driver.driver,
3033                            &driver_attr_release_date);
3034 err_dcf_rel_date:
3035         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
3036 err_dcf_attr_ver:
3037         pci_unregister_driver(&megasas_pci_driver);
3038 err_pcidrv:
3039         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
3040         return rval;
3041 }
3042
3043 /**
3044  * megasas_exit - Driver unload entry point
3045  */
3046 static void __exit megasas_exit(void)
3047 {
3048         driver_remove_file(&megasas_pci_driver.driver,
3049                            &driver_attr_dbg_lvl);
3050         driver_remove_file(&megasas_pci_driver.driver,
3051                            &driver_attr_release_date);
3052         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
3053
3054         pci_unregister_driver(&megasas_pci_driver);
3055         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
3056 }
3057
3058 module_init(megasas_init);
3059 module_exit(megasas_exit);