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