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