]> err.no Git - linux-2.6/blob - drivers/scsi/megaraid/megaraid_sas.c
Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/teigland/dlm
[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 };
1196
1197 /**
1198  * megasas_complete_int_cmd -   Completes an internal command
1199  * @instance:                   Adapter soft state
1200  * @cmd:                        Command to be completed
1201  *
1202  * The megasas_issue_blocked_cmd() function waits for a command to complete
1203  * after it issues a command. This function wakes up that waiting routine by
1204  * calling wake_up() on the wait queue.
1205  */
1206 static void
1207 megasas_complete_int_cmd(struct megasas_instance *instance,
1208                          struct megasas_cmd *cmd)
1209 {
1210         cmd->cmd_status = cmd->frame->io.cmd_status;
1211
1212         if (cmd->cmd_status == ENODATA) {
1213                 cmd->cmd_status = 0;
1214         }
1215         wake_up(&instance->int_cmd_wait_q);
1216 }
1217
1218 /**
1219  * megasas_complete_abort -     Completes aborting a command
1220  * @instance:                   Adapter soft state
1221  * @cmd:                        Cmd that was issued to abort another cmd
1222  *
1223  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q 
1224  * after it issues an abort on a previously issued command. This function 
1225  * wakes up all functions waiting on the same wait queue.
1226  */
1227 static void
1228 megasas_complete_abort(struct megasas_instance *instance,
1229                        struct megasas_cmd *cmd)
1230 {
1231         if (cmd->sync_cmd) {
1232                 cmd->sync_cmd = 0;
1233                 cmd->cmd_status = 0;
1234                 wake_up(&instance->abort_cmd_wait_q);
1235         }
1236
1237         return;
1238 }
1239
1240 /**
1241  * megasas_complete_cmd -       Completes a command
1242  * @instance:                   Adapter soft state
1243  * @cmd:                        Command to be completed
1244  * @alt_status:                 If non-zero, use this value as status to 
1245  *                              SCSI mid-layer instead of the value returned
1246  *                              by the FW. This should be used if caller wants
1247  *                              an alternate status (as in the case of aborted
1248  *                              commands)
1249  */
1250 static void
1251 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
1252                      u8 alt_status)
1253 {
1254         int exception = 0;
1255         struct megasas_header *hdr = &cmd->frame->hdr;
1256
1257         if (cmd->scmd)
1258                 cmd->scmd->SCp.ptr = NULL;
1259
1260         switch (hdr->cmd) {
1261
1262         case MFI_CMD_PD_SCSI_IO:
1263         case MFI_CMD_LD_SCSI_IO:
1264
1265                 /*
1266                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
1267                  * issued either through an IO path or an IOCTL path. If it
1268                  * was via IOCTL, we will send it to internal completion.
1269                  */
1270                 if (cmd->sync_cmd) {
1271                         cmd->sync_cmd = 0;
1272                         megasas_complete_int_cmd(instance, cmd);
1273                         break;
1274                 }
1275
1276         case MFI_CMD_LD_READ:
1277         case MFI_CMD_LD_WRITE:
1278
1279                 if (alt_status) {
1280                         cmd->scmd->result = alt_status << 16;
1281                         exception = 1;
1282                 }
1283
1284                 if (exception) {
1285
1286                         atomic_dec(&instance->fw_outstanding);
1287
1288                         scsi_dma_unmap(cmd->scmd);
1289                         cmd->scmd->scsi_done(cmd->scmd);
1290                         megasas_return_cmd(instance, cmd);
1291
1292                         break;
1293                 }
1294
1295                 switch (hdr->cmd_status) {
1296
1297                 case MFI_STAT_OK:
1298                         cmd->scmd->result = DID_OK << 16;
1299                         break;
1300
1301                 case MFI_STAT_SCSI_IO_FAILED:
1302                 case MFI_STAT_LD_INIT_IN_PROGRESS:
1303                         cmd->scmd->result =
1304                             (DID_ERROR << 16) | hdr->scsi_status;
1305                         break;
1306
1307                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
1308
1309                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
1310
1311                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
1312                                 memset(cmd->scmd->sense_buffer, 0,
1313                                        SCSI_SENSE_BUFFERSIZE);
1314                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
1315                                        hdr->sense_len);
1316
1317                                 cmd->scmd->result |= DRIVER_SENSE << 24;
1318                         }
1319
1320                         break;
1321
1322                 case MFI_STAT_LD_OFFLINE:
1323                 case MFI_STAT_DEVICE_NOT_FOUND:
1324                         cmd->scmd->result = DID_BAD_TARGET << 16;
1325                         break;
1326
1327                 default:
1328                         printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
1329                                hdr->cmd_status);
1330                         cmd->scmd->result = DID_ERROR << 16;
1331                         break;
1332                 }
1333
1334                 atomic_dec(&instance->fw_outstanding);
1335
1336                 scsi_dma_unmap(cmd->scmd);
1337                 cmd->scmd->scsi_done(cmd->scmd);
1338                 megasas_return_cmd(instance, cmd);
1339
1340                 break;
1341
1342         case MFI_CMD_SMP:
1343         case MFI_CMD_STP:
1344         case MFI_CMD_DCMD:
1345
1346                 /*
1347                  * See if got an event notification
1348                  */
1349                 if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT)
1350                         megasas_service_aen(instance, cmd);
1351                 else
1352                         megasas_complete_int_cmd(instance, cmd);
1353
1354                 break;
1355
1356         case MFI_CMD_ABORT:
1357                 /*
1358                  * Cmd issued to abort another cmd returned
1359                  */
1360                 megasas_complete_abort(instance, cmd);
1361                 break;
1362
1363         default:
1364                 printk("megasas: Unknown command completed! [0x%X]\n",
1365                        hdr->cmd);
1366                 break;
1367         }
1368 }
1369
1370 /**
1371  * megasas_deplete_reply_queue -        Processes all completed commands
1372  * @instance:                           Adapter soft state
1373  * @alt_status:                         Alternate status to be returned to
1374  *                                      SCSI mid-layer instead of the status
1375  *                                      returned by the FW
1376  */
1377 static int
1378 megasas_deplete_reply_queue(struct megasas_instance *instance, u8 alt_status)
1379 {
1380         /*
1381          * Check if it is our interrupt
1382          * Clear the interrupt 
1383          */
1384         if(instance->instancet->clear_intr(instance->reg_set))
1385                 return IRQ_NONE;
1386
1387         if (instance->hw_crit_error)
1388                 goto out_done;
1389         /*
1390          * Schedule the tasklet for cmd completion
1391          */
1392         tasklet_schedule(&instance->isr_tasklet);
1393 out_done:
1394         return IRQ_HANDLED;
1395 }
1396
1397 /**
1398  * megasas_isr - isr entry point
1399  */
1400 static irqreturn_t megasas_isr(int irq, void *devp)
1401 {
1402         return megasas_deplete_reply_queue((struct megasas_instance *)devp,
1403                                            DID_OK);
1404 }
1405
1406 /**
1407  * megasas_transition_to_ready -        Move the FW to READY state
1408  * @instance:                           Adapter soft state
1409  *
1410  * During the initialization, FW passes can potentially be in any one of
1411  * several possible states. If the FW in operational, waiting-for-handshake
1412  * states, driver must take steps to bring it to ready state. Otherwise, it
1413  * has to wait for the ready state.
1414  */
1415 static int
1416 megasas_transition_to_ready(struct megasas_instance* instance)
1417 {
1418         int i;
1419         u8 max_wait;
1420         u32 fw_state;
1421         u32 cur_state;
1422
1423         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
1424
1425         if (fw_state != MFI_STATE_READY)
1426                 printk(KERN_INFO "megasas: Waiting for FW to come to ready"
1427                        " state\n");
1428
1429         while (fw_state != MFI_STATE_READY) {
1430
1431                 switch (fw_state) {
1432
1433                 case MFI_STATE_FAULT:
1434
1435                         printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
1436                         return -ENODEV;
1437
1438                 case MFI_STATE_WAIT_HANDSHAKE:
1439                         /*
1440                          * Set the CLR bit in inbound doorbell
1441                          */
1442                         writel(MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
1443                                 &instance->reg_set->inbound_doorbell);
1444
1445                         max_wait = 2;
1446                         cur_state = MFI_STATE_WAIT_HANDSHAKE;
1447                         break;
1448
1449                 case MFI_STATE_BOOT_MESSAGE_PENDING:
1450                         writel(MFI_INIT_HOTPLUG,
1451                                 &instance->reg_set->inbound_doorbell);
1452
1453                         max_wait = 10;
1454                         cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
1455                         break;
1456
1457                 case MFI_STATE_OPERATIONAL:
1458                         /*
1459                          * Bring it to READY state; assuming max wait 10 secs
1460                          */
1461                         instance->instancet->disable_intr(instance->reg_set);
1462                         writel(MFI_RESET_FLAGS, &instance->reg_set->inbound_doorbell);
1463
1464                         max_wait = 10;
1465                         cur_state = MFI_STATE_OPERATIONAL;
1466                         break;
1467
1468                 case MFI_STATE_UNDEFINED:
1469                         /*
1470                          * This state should not last for more than 2 seconds
1471                          */
1472                         max_wait = 2;
1473                         cur_state = MFI_STATE_UNDEFINED;
1474                         break;
1475
1476                 case MFI_STATE_BB_INIT:
1477                         max_wait = 2;
1478                         cur_state = MFI_STATE_BB_INIT;
1479                         break;
1480
1481                 case MFI_STATE_FW_INIT:
1482                         max_wait = 20;
1483                         cur_state = MFI_STATE_FW_INIT;
1484                         break;
1485
1486                 case MFI_STATE_FW_INIT_2:
1487                         max_wait = 20;
1488                         cur_state = MFI_STATE_FW_INIT_2;
1489                         break;
1490
1491                 case MFI_STATE_DEVICE_SCAN:
1492                         max_wait = 20;
1493                         cur_state = MFI_STATE_DEVICE_SCAN;
1494                         break;
1495
1496                 case MFI_STATE_FLUSH_CACHE:
1497                         max_wait = 20;
1498                         cur_state = MFI_STATE_FLUSH_CACHE;
1499                         break;
1500
1501                 default:
1502                         printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
1503                                fw_state);
1504                         return -ENODEV;
1505                 }
1506
1507                 /*
1508                  * The cur_state should not last for more than max_wait secs
1509                  */
1510                 for (i = 0; i < (max_wait * 1000); i++) {
1511                         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &  
1512                                         MFI_STATE_MASK ;
1513
1514                         if (fw_state == cur_state) {
1515                                 msleep(1);
1516                         } else
1517                                 break;
1518                 }
1519
1520                 /*
1521                  * Return error if fw_state hasn't changed after max_wait
1522                  */
1523                 if (fw_state == cur_state) {
1524                         printk(KERN_DEBUG "FW state [%d] hasn't changed "
1525                                "in %d secs\n", fw_state, max_wait);
1526                         return -ENODEV;
1527                 }
1528         };
1529         printk(KERN_INFO "megasas: FW now in Ready state\n");
1530
1531         return 0;
1532 }
1533
1534 /**
1535  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
1536  * @instance:                           Adapter soft state
1537  */
1538 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
1539 {
1540         int i;
1541         u32 max_cmd = instance->max_fw_cmds;
1542         struct megasas_cmd *cmd;
1543
1544         if (!instance->frame_dma_pool)
1545                 return;
1546
1547         /*
1548          * Return all frames to pool
1549          */
1550         for (i = 0; i < max_cmd; i++) {
1551
1552                 cmd = instance->cmd_list[i];
1553
1554                 if (cmd->frame)
1555                         pci_pool_free(instance->frame_dma_pool, cmd->frame,
1556                                       cmd->frame_phys_addr);
1557
1558                 if (cmd->sense)
1559                         pci_pool_free(instance->sense_dma_pool, cmd->sense,
1560                                       cmd->sense_phys_addr);
1561         }
1562
1563         /*
1564          * Now destroy the pool itself
1565          */
1566         pci_pool_destroy(instance->frame_dma_pool);
1567         pci_pool_destroy(instance->sense_dma_pool);
1568
1569         instance->frame_dma_pool = NULL;
1570         instance->sense_dma_pool = NULL;
1571 }
1572
1573 /**
1574  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
1575  * @instance:                   Adapter soft state
1576  *
1577  * Each command packet has an embedded DMA memory buffer that is used for
1578  * filling MFI frame and the SG list that immediately follows the frame. This
1579  * function creates those DMA memory buffers for each command packet by using
1580  * PCI pool facility.
1581  */
1582 static int megasas_create_frame_pool(struct megasas_instance *instance)
1583 {
1584         int i;
1585         u32 max_cmd;
1586         u32 sge_sz;
1587         u32 sgl_sz;
1588         u32 total_sz;
1589         u32 frame_count;
1590         struct megasas_cmd *cmd;
1591
1592         max_cmd = instance->max_fw_cmds;
1593
1594         /*
1595          * Size of our frame is 64 bytes for MFI frame, followed by max SG
1596          * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
1597          */
1598         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1599             sizeof(struct megasas_sge32);
1600
1601         /*
1602          * Calculated the number of 64byte frames required for SGL
1603          */
1604         sgl_sz = sge_sz * instance->max_num_sge;
1605         frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
1606
1607         /*
1608          * We need one extra frame for the MFI command
1609          */
1610         frame_count++;
1611
1612         total_sz = MEGAMFI_FRAME_SIZE * frame_count;
1613         /*
1614          * Use DMA pool facility provided by PCI layer
1615          */
1616         instance->frame_dma_pool = pci_pool_create("megasas frame pool",
1617                                                    instance->pdev, total_sz, 64,
1618                                                    0);
1619
1620         if (!instance->frame_dma_pool) {
1621                 printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
1622                 return -ENOMEM;
1623         }
1624
1625         instance->sense_dma_pool = pci_pool_create("megasas sense pool",
1626                                                    instance->pdev, 128, 4, 0);
1627
1628         if (!instance->sense_dma_pool) {
1629                 printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
1630
1631                 pci_pool_destroy(instance->frame_dma_pool);
1632                 instance->frame_dma_pool = NULL;
1633
1634                 return -ENOMEM;
1635         }
1636
1637         /*
1638          * Allocate and attach a frame to each of the commands in cmd_list.
1639          * By making cmd->index as the context instead of the &cmd, we can
1640          * always use 32bit context regardless of the architecture
1641          */
1642         for (i = 0; i < max_cmd; i++) {
1643
1644                 cmd = instance->cmd_list[i];
1645
1646                 cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
1647                                             GFP_KERNEL, &cmd->frame_phys_addr);
1648
1649                 cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
1650                                             GFP_KERNEL, &cmd->sense_phys_addr);
1651
1652                 /*
1653                  * megasas_teardown_frame_pool() takes care of freeing
1654                  * whatever has been allocated
1655                  */
1656                 if (!cmd->frame || !cmd->sense) {
1657                         printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
1658                         megasas_teardown_frame_pool(instance);
1659                         return -ENOMEM;
1660                 }
1661
1662                 cmd->frame->io.context = cmd->index;
1663         }
1664
1665         return 0;
1666 }
1667
1668 /**
1669  * megasas_free_cmds -  Free all the cmds in the free cmd pool
1670  * @instance:           Adapter soft state
1671  */
1672 static void megasas_free_cmds(struct megasas_instance *instance)
1673 {
1674         int i;
1675         /* First free the MFI frame pool */
1676         megasas_teardown_frame_pool(instance);
1677
1678         /* Free all the commands in the cmd_list */
1679         for (i = 0; i < instance->max_fw_cmds; i++)
1680                 kfree(instance->cmd_list[i]);
1681
1682         /* Free the cmd_list buffer itself */
1683         kfree(instance->cmd_list);
1684         instance->cmd_list = NULL;
1685
1686         INIT_LIST_HEAD(&instance->cmd_pool);
1687 }
1688
1689 /**
1690  * megasas_alloc_cmds - Allocates the command packets
1691  * @instance:           Adapter soft state
1692  *
1693  * Each command that is issued to the FW, whether IO commands from the OS or
1694  * internal commands like IOCTLs, are wrapped in local data structure called
1695  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
1696  * the FW.
1697  *
1698  * Each frame has a 32-bit field called context (tag). This context is used
1699  * to get back the megasas_cmd from the frame when a frame gets completed in
1700  * the ISR. Typically the address of the megasas_cmd itself would be used as
1701  * the context. But we wanted to keep the differences between 32 and 64 bit
1702  * systems to the mininum. We always use 32 bit integers for the context. In
1703  * this driver, the 32 bit values are the indices into an array cmd_list.
1704  * This array is used only to look up the megasas_cmd given the context. The
1705  * free commands themselves are maintained in a linked list called cmd_pool.
1706  */
1707 static int megasas_alloc_cmds(struct megasas_instance *instance)
1708 {
1709         int i;
1710         int j;
1711         u32 max_cmd;
1712         struct megasas_cmd *cmd;
1713
1714         max_cmd = instance->max_fw_cmds;
1715
1716         /*
1717          * instance->cmd_list is an array of struct megasas_cmd pointers.
1718          * Allocate the dynamic array first and then allocate individual
1719          * commands.
1720          */
1721         instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
1722
1723         if (!instance->cmd_list) {
1724                 printk(KERN_DEBUG "megasas: out of memory\n");
1725                 return -ENOMEM;
1726         }
1727
1728
1729         for (i = 0; i < max_cmd; i++) {
1730                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
1731                                                 GFP_KERNEL);
1732
1733                 if (!instance->cmd_list[i]) {
1734
1735                         for (j = 0; j < i; j++)
1736                                 kfree(instance->cmd_list[j]);
1737
1738                         kfree(instance->cmd_list);
1739                         instance->cmd_list = NULL;
1740
1741                         return -ENOMEM;
1742                 }
1743         }
1744
1745         /*
1746          * Add all the commands to command pool (instance->cmd_pool)
1747          */
1748         for (i = 0; i < max_cmd; i++) {
1749                 cmd = instance->cmd_list[i];
1750                 memset(cmd, 0, sizeof(struct megasas_cmd));
1751                 cmd->index = i;
1752                 cmd->instance = instance;
1753
1754                 list_add_tail(&cmd->list, &instance->cmd_pool);
1755         }
1756
1757         /*
1758          * Create a frame pool and assign one frame to each cmd
1759          */
1760         if (megasas_create_frame_pool(instance)) {
1761                 printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
1762                 megasas_free_cmds(instance);
1763         }
1764
1765         return 0;
1766 }
1767
1768 /**
1769  * megasas_get_controller_info -        Returns FW's controller structure
1770  * @instance:                           Adapter soft state
1771  * @ctrl_info:                          Controller information structure
1772  *
1773  * Issues an internal command (DCMD) to get the FW's controller structure.
1774  * This information is mainly used to find out the maximum IO transfer per
1775  * command supported by the FW.
1776  */
1777 static int
1778 megasas_get_ctrl_info(struct megasas_instance *instance,
1779                       struct megasas_ctrl_info *ctrl_info)
1780 {
1781         int ret = 0;
1782         struct megasas_cmd *cmd;
1783         struct megasas_dcmd_frame *dcmd;
1784         struct megasas_ctrl_info *ci;
1785         dma_addr_t ci_h = 0;
1786
1787         cmd = megasas_get_cmd(instance);
1788
1789         if (!cmd) {
1790                 printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
1791                 return -ENOMEM;
1792         }
1793
1794         dcmd = &cmd->frame->dcmd;
1795
1796         ci = pci_alloc_consistent(instance->pdev,
1797                                   sizeof(struct megasas_ctrl_info), &ci_h);
1798
1799         if (!ci) {
1800                 printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
1801                 megasas_return_cmd(instance, cmd);
1802                 return -ENOMEM;
1803         }
1804
1805         memset(ci, 0, sizeof(*ci));
1806         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1807
1808         dcmd->cmd = MFI_CMD_DCMD;
1809         dcmd->cmd_status = 0xFF;
1810         dcmd->sge_count = 1;
1811         dcmd->flags = MFI_FRAME_DIR_READ;
1812         dcmd->timeout = 0;
1813         dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info);
1814         dcmd->opcode = MR_DCMD_CTRL_GET_INFO;
1815         dcmd->sgl.sge32[0].phys_addr = ci_h;
1816         dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info);
1817
1818         if (!megasas_issue_polled(instance, cmd)) {
1819                 ret = 0;
1820                 memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
1821         } else {
1822                 ret = -1;
1823         }
1824
1825         pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
1826                             ci, ci_h);
1827
1828         megasas_return_cmd(instance, cmd);
1829         return ret;
1830 }
1831
1832 /**
1833  * megasas_issue_init_mfi -     Initializes the FW
1834  * @instance:           Adapter soft state
1835  *
1836  * Issues the INIT MFI cmd
1837  */
1838 static int
1839 megasas_issue_init_mfi(struct megasas_instance *instance)
1840 {
1841         u32 context;
1842
1843         struct megasas_cmd *cmd;
1844
1845         struct megasas_init_frame *init_frame;
1846         struct megasas_init_queue_info *initq_info;
1847         dma_addr_t init_frame_h;
1848         dma_addr_t initq_info_h;
1849
1850         /*
1851          * Prepare a init frame. Note the init frame points to queue info
1852          * structure. Each frame has SGL allocated after first 64 bytes. For
1853          * this frame - since we don't need any SGL - we use SGL's space as
1854          * queue info structure
1855          *
1856          * We will not get a NULL command below. We just created the pool.
1857          */
1858         cmd = megasas_get_cmd(instance);
1859
1860         init_frame = (struct megasas_init_frame *)cmd->frame;
1861         initq_info = (struct megasas_init_queue_info *)
1862                 ((unsigned long)init_frame + 64);
1863
1864         init_frame_h = cmd->frame_phys_addr;
1865         initq_info_h = init_frame_h + 64;
1866
1867         context = init_frame->context;
1868         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
1869         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
1870         init_frame->context = context;
1871
1872         initq_info->reply_queue_entries = instance->max_fw_cmds + 1;
1873         initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h;
1874
1875         initq_info->producer_index_phys_addr_lo = instance->producer_h;
1876         initq_info->consumer_index_phys_addr_lo = instance->consumer_h;
1877
1878         init_frame->cmd = MFI_CMD_INIT;
1879         init_frame->cmd_status = 0xFF;
1880         init_frame->queue_info_new_phys_addr_lo = initq_info_h;
1881
1882         init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info);
1883
1884         /*
1885          * disable the intr before firing the init frame to FW
1886          */
1887         instance->instancet->disable_intr(instance->reg_set);
1888
1889         /*
1890          * Issue the init frame in polled mode
1891          */
1892
1893         if (megasas_issue_polled(instance, cmd)) {
1894                 printk(KERN_ERR "megasas: Failed to init firmware\n");
1895                 megasas_return_cmd(instance, cmd);
1896                 goto fail_fw_init;
1897         }
1898
1899         megasas_return_cmd(instance, cmd);
1900
1901         return 0;
1902
1903 fail_fw_init:
1904         return -EINVAL;
1905 }
1906
1907 /**
1908  * megasas_start_timer - Initializes a timer object
1909  * @instance:           Adapter soft state
1910  * @timer:              timer object to be initialized
1911  * @fn:                 timer function
1912  * @interval:           time interval between timer function call
1913  */
1914 static inline void
1915 megasas_start_timer(struct megasas_instance *instance,
1916                         struct timer_list *timer,
1917                         void *fn, unsigned long interval)
1918 {
1919         init_timer(timer);
1920         timer->expires = jiffies + interval;
1921         timer->data = (unsigned long)instance;
1922         timer->function = fn;
1923         add_timer(timer);
1924 }
1925
1926 /**
1927  * megasas_io_completion_timer - Timer fn
1928  * @instance_addr:      Address of adapter soft state
1929  *
1930  * Schedules tasklet for cmd completion
1931  * if poll_mode_io is set
1932  */
1933 static void
1934 megasas_io_completion_timer(unsigned long instance_addr)
1935 {
1936         struct megasas_instance *instance =
1937                         (struct megasas_instance *)instance_addr;
1938
1939         if (atomic_read(&instance->fw_outstanding))
1940                 tasklet_schedule(&instance->isr_tasklet);
1941
1942         /* Restart timer */
1943         if (poll_mode_io)
1944                 mod_timer(&instance->io_completion_timer,
1945                         jiffies + MEGASAS_COMPLETION_TIMER_INTERVAL);
1946 }
1947
1948 /**
1949  * megasas_init_mfi -   Initializes the FW
1950  * @instance:           Adapter soft state
1951  *
1952  * This is the main function for initializing MFI firmware.
1953  */
1954 static int megasas_init_mfi(struct megasas_instance *instance)
1955 {
1956         u32 context_sz;
1957         u32 reply_q_sz;
1958         u32 max_sectors_1;
1959         u32 max_sectors_2;
1960         u32 tmp_sectors;
1961         struct megasas_register_set __iomem *reg_set;
1962         struct megasas_ctrl_info *ctrl_info;
1963         /*
1964          * Map the message registers
1965          */
1966         instance->base_addr = pci_resource_start(instance->pdev, 0);
1967
1968         if (pci_request_regions(instance->pdev, "megasas: LSI")) {
1969                 printk(KERN_DEBUG "megasas: IO memory region busy!\n");
1970                 return -EBUSY;
1971         }
1972
1973         instance->reg_set = ioremap_nocache(instance->base_addr, 8192);
1974
1975         if (!instance->reg_set) {
1976                 printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
1977                 goto fail_ioremap;
1978         }
1979
1980         reg_set = instance->reg_set;
1981
1982         switch(instance->pdev->device)
1983         {
1984                 case PCI_DEVICE_ID_LSI_SAS1078R:        
1985                         instance->instancet = &megasas_instance_template_ppc;
1986                         break;
1987                 case PCI_DEVICE_ID_LSI_SAS1064R:
1988                 case PCI_DEVICE_ID_DELL_PERC5:
1989                 default:
1990                         instance->instancet = &megasas_instance_template_xscale;
1991                         break;
1992         }
1993
1994         /*
1995          * We expect the FW state to be READY
1996          */
1997         if (megasas_transition_to_ready(instance))
1998                 goto fail_ready_state;
1999
2000         /*
2001          * Get various operational parameters from status register
2002          */
2003         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
2004         /*
2005          * Reduce the max supported cmds by 1. This is to ensure that the
2006          * reply_q_sz (1 more than the max cmd that driver may send)
2007          * does not exceed max cmds that the FW can support
2008          */
2009         instance->max_fw_cmds = instance->max_fw_cmds-1;
2010         instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >> 
2011                                         0x10;
2012         /*
2013          * Create a pool of commands
2014          */
2015         if (megasas_alloc_cmds(instance))
2016                 goto fail_alloc_cmds;
2017
2018         /*
2019          * Allocate memory for reply queue. Length of reply queue should
2020          * be _one_ more than the maximum commands handled by the firmware.
2021          *
2022          * Note: When FW completes commands, it places corresponding contex
2023          * values in this circular reply queue. This circular queue is a fairly
2024          * typical producer-consumer queue. FW is the producer (of completed
2025          * commands) and the driver is the consumer.
2026          */
2027         context_sz = sizeof(u32);
2028         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
2029
2030         instance->reply_queue = pci_alloc_consistent(instance->pdev,
2031                                                      reply_q_sz,
2032                                                      &instance->reply_queue_h);
2033
2034         if (!instance->reply_queue) {
2035                 printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
2036                 goto fail_reply_queue;
2037         }
2038
2039         if (megasas_issue_init_mfi(instance))
2040                 goto fail_fw_init;
2041
2042         ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
2043
2044         /*
2045          * Compute the max allowed sectors per IO: The controller info has two
2046          * limits on max sectors. Driver should use the minimum of these two.
2047          *
2048          * 1 << stripe_sz_ops.min = max sectors per strip
2049          *
2050          * Note that older firmwares ( < FW ver 30) didn't report information
2051          * to calculate max_sectors_1. So the number ended up as zero always.
2052          */
2053         tmp_sectors = 0;
2054         if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
2055
2056                 max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
2057                     ctrl_info->max_strips_per_io;
2058                 max_sectors_2 = ctrl_info->max_request_size;
2059
2060                 tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2);
2061         }
2062
2063         instance->max_sectors_per_req = instance->max_num_sge *
2064                                                 PAGE_SIZE / 512;
2065         if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
2066                 instance->max_sectors_per_req = tmp_sectors;
2067
2068         kfree(ctrl_info);
2069
2070         /*
2071         * Setup tasklet for cmd completion
2072         */
2073
2074         tasklet_init(&instance->isr_tasklet, megasas_complete_cmd_dpc,
2075                 (unsigned long)instance);
2076
2077         /* Initialize the cmd completion timer */
2078         if (poll_mode_io)
2079                 megasas_start_timer(instance, &instance->io_completion_timer,
2080                                 megasas_io_completion_timer,
2081                                 MEGASAS_COMPLETION_TIMER_INTERVAL);
2082         return 0;
2083
2084       fail_fw_init:
2085
2086         pci_free_consistent(instance->pdev, reply_q_sz,
2087                             instance->reply_queue, instance->reply_queue_h);
2088       fail_reply_queue:
2089         megasas_free_cmds(instance);
2090
2091       fail_alloc_cmds:
2092       fail_ready_state:
2093         iounmap(instance->reg_set);
2094
2095       fail_ioremap:
2096         pci_release_regions(instance->pdev);
2097
2098         return -EINVAL;
2099 }
2100
2101 /**
2102  * megasas_release_mfi -        Reverses the FW initialization
2103  * @intance:                    Adapter soft state
2104  */
2105 static void megasas_release_mfi(struct megasas_instance *instance)
2106 {
2107         u32 reply_q_sz = sizeof(u32) * (instance->max_fw_cmds + 1);
2108
2109         pci_free_consistent(instance->pdev, reply_q_sz,
2110                             instance->reply_queue, instance->reply_queue_h);
2111
2112         megasas_free_cmds(instance);
2113
2114         iounmap(instance->reg_set);
2115
2116         pci_release_regions(instance->pdev);
2117 }
2118
2119 /**
2120  * megasas_get_seq_num -        Gets latest event sequence numbers
2121  * @instance:                   Adapter soft state
2122  * @eli:                        FW event log sequence numbers information
2123  *
2124  * FW maintains a log of all events in a non-volatile area. Upper layers would
2125  * usually find out the latest sequence number of the events, the seq number at
2126  * the boot etc. They would "read" all the events below the latest seq number
2127  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
2128  * number), they would subsribe to AEN (asynchronous event notification) and
2129  * wait for the events to happen.
2130  */
2131 static int
2132 megasas_get_seq_num(struct megasas_instance *instance,
2133                     struct megasas_evt_log_info *eli)
2134 {
2135         struct megasas_cmd *cmd;
2136         struct megasas_dcmd_frame *dcmd;
2137         struct megasas_evt_log_info *el_info;
2138         dma_addr_t el_info_h = 0;
2139
2140         cmd = megasas_get_cmd(instance);
2141
2142         if (!cmd) {
2143                 return -ENOMEM;
2144         }
2145
2146         dcmd = &cmd->frame->dcmd;
2147         el_info = pci_alloc_consistent(instance->pdev,
2148                                        sizeof(struct megasas_evt_log_info),
2149                                        &el_info_h);
2150
2151         if (!el_info) {
2152                 megasas_return_cmd(instance, cmd);
2153                 return -ENOMEM;
2154         }
2155
2156         memset(el_info, 0, sizeof(*el_info));
2157         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2158
2159         dcmd->cmd = MFI_CMD_DCMD;
2160         dcmd->cmd_status = 0x0;
2161         dcmd->sge_count = 1;
2162         dcmd->flags = MFI_FRAME_DIR_READ;
2163         dcmd->timeout = 0;
2164         dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info);
2165         dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO;
2166         dcmd->sgl.sge32[0].phys_addr = el_info_h;
2167         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info);
2168
2169         megasas_issue_blocked_cmd(instance, cmd);
2170
2171         /*
2172          * Copy the data back into callers buffer
2173          */
2174         memcpy(eli, el_info, sizeof(struct megasas_evt_log_info));
2175
2176         pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
2177                             el_info, el_info_h);
2178
2179         megasas_return_cmd(instance, cmd);
2180
2181         return 0;
2182 }
2183
2184 /**
2185  * megasas_register_aen -       Registers for asynchronous event notification
2186  * @instance:                   Adapter soft state
2187  * @seq_num:                    The starting sequence number
2188  * @class_locale:               Class of the event
2189  *
2190  * This function subscribes for AEN for events beyond the @seq_num. It requests
2191  * to be notified if and only if the event is of type @class_locale
2192  */
2193 static int
2194 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
2195                      u32 class_locale_word)
2196 {
2197         int ret_val;
2198         struct megasas_cmd *cmd;
2199         struct megasas_dcmd_frame *dcmd;
2200         union megasas_evt_class_locale curr_aen;
2201         union megasas_evt_class_locale prev_aen;
2202
2203         /*
2204          * If there an AEN pending already (aen_cmd), check if the
2205          * class_locale of that pending AEN is inclusive of the new
2206          * AEN request we currently have. If it is, then we don't have
2207          * to do anything. In other words, whichever events the current
2208          * AEN request is subscribing to, have already been subscribed
2209          * to.
2210          *
2211          * If the old_cmd is _not_ inclusive, then we have to abort
2212          * that command, form a class_locale that is superset of both
2213          * old and current and re-issue to the FW
2214          */
2215
2216         curr_aen.word = class_locale_word;
2217
2218         if (instance->aen_cmd) {
2219
2220                 prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
2221
2222                 /*
2223                  * A class whose enum value is smaller is inclusive of all
2224                  * higher values. If a PROGRESS (= -1) was previously
2225                  * registered, then a new registration requests for higher
2226                  * classes need not be sent to FW. They are automatically
2227                  * included.
2228                  *
2229                  * Locale numbers don't have such hierarchy. They are bitmap
2230                  * values
2231                  */
2232                 if ((prev_aen.members.class <= curr_aen.members.class) &&
2233                     !((prev_aen.members.locale & curr_aen.members.locale) ^
2234                       curr_aen.members.locale)) {
2235                         /*
2236                          * Previously issued event registration includes
2237                          * current request. Nothing to do.
2238                          */
2239                         return 0;
2240                 } else {
2241                         curr_aen.members.locale |= prev_aen.members.locale;
2242
2243                         if (prev_aen.members.class < curr_aen.members.class)
2244                                 curr_aen.members.class = prev_aen.members.class;
2245
2246                         instance->aen_cmd->abort_aen = 1;
2247                         ret_val = megasas_issue_blocked_abort_cmd(instance,
2248                                                                   instance->
2249                                                                   aen_cmd);
2250
2251                         if (ret_val) {
2252                                 printk(KERN_DEBUG "megasas: Failed to abort "
2253                                        "previous AEN command\n");
2254                                 return ret_val;
2255                         }
2256                 }
2257         }
2258
2259         cmd = megasas_get_cmd(instance);
2260
2261         if (!cmd)
2262                 return -ENOMEM;
2263
2264         dcmd = &cmd->frame->dcmd;
2265
2266         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
2267
2268         /*
2269          * Prepare DCMD for aen registration
2270          */
2271         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2272
2273         dcmd->cmd = MFI_CMD_DCMD;
2274         dcmd->cmd_status = 0x0;
2275         dcmd->sge_count = 1;
2276         dcmd->flags = MFI_FRAME_DIR_READ;
2277         dcmd->timeout = 0;
2278         dcmd->data_xfer_len = sizeof(struct megasas_evt_detail);
2279         dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT;
2280         dcmd->mbox.w[0] = seq_num;
2281         dcmd->mbox.w[1] = curr_aen.word;
2282         dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h;
2283         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail);
2284
2285         /*
2286          * Store reference to the cmd used to register for AEN. When an
2287          * application wants us to register for AEN, we have to abort this
2288          * cmd and re-register with a new EVENT LOCALE supplied by that app
2289          */
2290         instance->aen_cmd = cmd;
2291
2292         /*
2293          * Issue the aen registration frame
2294          */
2295         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
2296
2297         return 0;
2298 }
2299
2300 /**
2301  * megasas_start_aen -  Subscribes to AEN during driver load time
2302  * @instance:           Adapter soft state
2303  */
2304 static int megasas_start_aen(struct megasas_instance *instance)
2305 {
2306         struct megasas_evt_log_info eli;
2307         union megasas_evt_class_locale class_locale;
2308
2309         /*
2310          * Get the latest sequence number from FW
2311          */
2312         memset(&eli, 0, sizeof(eli));
2313
2314         if (megasas_get_seq_num(instance, &eli))
2315                 return -1;
2316
2317         /*
2318          * Register AEN with FW for latest sequence number plus 1
2319          */
2320         class_locale.members.reserved = 0;
2321         class_locale.members.locale = MR_EVT_LOCALE_ALL;
2322         class_locale.members.class = MR_EVT_CLASS_DEBUG;
2323
2324         return megasas_register_aen(instance, eli.newest_seq_num + 1,
2325                                     class_locale.word);
2326 }
2327
2328 /**
2329  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
2330  * @instance:           Adapter soft state
2331  */
2332 static int megasas_io_attach(struct megasas_instance *instance)
2333 {
2334         struct Scsi_Host *host = instance->host;
2335
2336         /*
2337          * Export parameters required by SCSI mid-layer
2338          */
2339         host->irq = instance->pdev->irq;
2340         host->unique_id = instance->unique_id;
2341         host->can_queue = instance->max_fw_cmds - MEGASAS_INT_CMDS;
2342         host->this_id = instance->init_id;
2343         host->sg_tablesize = instance->max_num_sge;
2344         host->max_sectors = instance->max_sectors_per_req;
2345         host->cmd_per_lun = 128;
2346         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
2347         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
2348         host->max_lun = MEGASAS_MAX_LUN;
2349         host->max_cmd_len = 16;
2350
2351         /*
2352          * Notify the mid-layer about the new controller
2353          */
2354         if (scsi_add_host(host, &instance->pdev->dev)) {
2355                 printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
2356                 return -ENODEV;
2357         }
2358
2359         /*
2360          * Trigger SCSI to scan our drives
2361          */
2362         scsi_scan_host(host);
2363         return 0;
2364 }
2365
2366 static int
2367 megasas_set_dma_mask(struct pci_dev *pdev)
2368 {
2369         /*
2370          * All our contollers are capable of performing 64-bit DMA
2371          */
2372         if (IS_DMA64) {
2373                 if (pci_set_dma_mask(pdev, DMA_64BIT_MASK) != 0) {
2374
2375                         if (pci_set_dma_mask(pdev, DMA_32BIT_MASK) != 0)
2376                                 goto fail_set_dma_mask;
2377                 }
2378         } else {
2379                 if (pci_set_dma_mask(pdev, DMA_32BIT_MASK) != 0)
2380                         goto fail_set_dma_mask;
2381         }
2382         return 0;
2383
2384 fail_set_dma_mask:
2385         return 1;
2386 }
2387
2388 /**
2389  * megasas_probe_one -  PCI hotplug entry point
2390  * @pdev:               PCI device structure
2391  * @id:                 PCI ids of supported hotplugged adapter 
2392  */
2393 static int __devinit
2394 megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
2395 {
2396         int rval;
2397         struct Scsi_Host *host;
2398         struct megasas_instance *instance;
2399
2400         /*
2401          * Announce PCI information
2402          */
2403         printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
2404                pdev->vendor, pdev->device, pdev->subsystem_vendor,
2405                pdev->subsystem_device);
2406
2407         printk("bus %d:slot %d:func %d\n",
2408                pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
2409
2410         /*
2411          * PCI prepping: enable device set bus mastering and dma mask
2412          */
2413         rval = pci_enable_device(pdev);
2414
2415         if (rval) {
2416                 return rval;
2417         }
2418
2419         pci_set_master(pdev);
2420
2421         if (megasas_set_dma_mask(pdev))
2422                 goto fail_set_dma_mask;
2423
2424         host = scsi_host_alloc(&megasas_template,
2425                                sizeof(struct megasas_instance));
2426
2427         if (!host) {
2428                 printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
2429                 goto fail_alloc_instance;
2430         }
2431
2432         instance = (struct megasas_instance *)host->hostdata;
2433         memset(instance, 0, sizeof(*instance));
2434
2435         instance->producer = pci_alloc_consistent(pdev, sizeof(u32),
2436                                                   &instance->producer_h);
2437         instance->consumer = pci_alloc_consistent(pdev, sizeof(u32),
2438                                                   &instance->consumer_h);
2439
2440         if (!instance->producer || !instance->consumer) {
2441                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
2442                        "producer, consumer\n");
2443                 goto fail_alloc_dma_buf;
2444         }
2445
2446         *instance->producer = 0;
2447         *instance->consumer = 0;
2448
2449         instance->evt_detail = pci_alloc_consistent(pdev,
2450                                                     sizeof(struct
2451                                                            megasas_evt_detail),
2452                                                     &instance->evt_detail_h);
2453
2454         if (!instance->evt_detail) {
2455                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
2456                        "event detail structure\n");
2457                 goto fail_alloc_dma_buf;
2458         }
2459
2460         /*
2461          * Initialize locks and queues
2462          */
2463         INIT_LIST_HEAD(&instance->cmd_pool);
2464
2465         atomic_set(&instance->fw_outstanding,0);
2466
2467         init_waitqueue_head(&instance->int_cmd_wait_q);
2468         init_waitqueue_head(&instance->abort_cmd_wait_q);
2469
2470         spin_lock_init(&instance->cmd_pool_lock);
2471         spin_lock_init(&instance->completion_lock);
2472
2473         mutex_init(&instance->aen_mutex);
2474         sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
2475
2476         /*
2477          * Initialize PCI related and misc parameters
2478          */
2479         instance->pdev = pdev;
2480         instance->host = host;
2481         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
2482         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
2483
2484         megasas_dbg_lvl = 0;
2485         instance->flag = 0;
2486         instance->last_time = 0;
2487
2488         /*
2489          * Initialize MFI Firmware
2490          */
2491         if (megasas_init_mfi(instance))
2492                 goto fail_init_mfi;
2493
2494         /*
2495          * Register IRQ
2496          */
2497         if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED, "megasas", instance)) {
2498                 printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
2499                 goto fail_irq;
2500         }
2501
2502         instance->instancet->enable_intr(instance->reg_set);
2503
2504         /*
2505          * Store instance in PCI softstate
2506          */
2507         pci_set_drvdata(pdev, instance);
2508
2509         /*
2510          * Add this controller to megasas_mgmt_info structure so that it
2511          * can be exported to management applications
2512          */
2513         megasas_mgmt_info.count++;
2514         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
2515         megasas_mgmt_info.max_index++;
2516
2517         /*
2518          * Initiate AEN (Asynchronous Event Notification)
2519          */
2520         if (megasas_start_aen(instance)) {
2521                 printk(KERN_DEBUG "megasas: start aen failed\n");
2522                 goto fail_start_aen;
2523         }
2524
2525         /*
2526          * Register with SCSI mid-layer
2527          */
2528         if (megasas_io_attach(instance))
2529                 goto fail_io_attach;
2530
2531         return 0;
2532
2533       fail_start_aen:
2534       fail_io_attach:
2535         megasas_mgmt_info.count--;
2536         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
2537         megasas_mgmt_info.max_index--;
2538
2539         pci_set_drvdata(pdev, NULL);
2540         instance->instancet->disable_intr(instance->reg_set);
2541         free_irq(instance->pdev->irq, instance);
2542
2543         megasas_release_mfi(instance);
2544
2545       fail_irq:
2546       fail_init_mfi:
2547       fail_alloc_dma_buf:
2548         if (instance->evt_detail)
2549                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
2550                                     instance->evt_detail,
2551                                     instance->evt_detail_h);
2552
2553         if (instance->producer)
2554                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
2555                                     instance->producer_h);
2556         if (instance->consumer)
2557                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
2558                                     instance->consumer_h);
2559         scsi_host_put(host);
2560
2561       fail_alloc_instance:
2562       fail_set_dma_mask:
2563         pci_disable_device(pdev);
2564
2565         return -ENODEV;
2566 }
2567
2568 /**
2569  * megasas_flush_cache -        Requests FW to flush all its caches
2570  * @instance:                   Adapter soft state
2571  */
2572 static void megasas_flush_cache(struct megasas_instance *instance)
2573 {
2574         struct megasas_cmd *cmd;
2575         struct megasas_dcmd_frame *dcmd;
2576
2577         cmd = megasas_get_cmd(instance);
2578
2579         if (!cmd)
2580                 return;
2581
2582         dcmd = &cmd->frame->dcmd;
2583
2584         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2585
2586         dcmd->cmd = MFI_CMD_DCMD;
2587         dcmd->cmd_status = 0x0;
2588         dcmd->sge_count = 0;
2589         dcmd->flags = MFI_FRAME_DIR_NONE;
2590         dcmd->timeout = 0;
2591         dcmd->data_xfer_len = 0;
2592         dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH;
2593         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
2594
2595         megasas_issue_blocked_cmd(instance, cmd);
2596
2597         megasas_return_cmd(instance, cmd);
2598
2599         return;
2600 }
2601
2602 /**
2603  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
2604  * @instance:                           Adapter soft state
2605  * @opcode:                             Shutdown/Hibernate
2606  */
2607 static void megasas_shutdown_controller(struct megasas_instance *instance,
2608                                         u32 opcode)
2609 {
2610         struct megasas_cmd *cmd;
2611         struct megasas_dcmd_frame *dcmd;
2612
2613         cmd = megasas_get_cmd(instance);
2614
2615         if (!cmd)
2616                 return;
2617
2618         if (instance->aen_cmd)
2619                 megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd);
2620
2621         dcmd = &cmd->frame->dcmd;
2622
2623         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2624
2625         dcmd->cmd = MFI_CMD_DCMD;
2626         dcmd->cmd_status = 0x0;
2627         dcmd->sge_count = 0;
2628         dcmd->flags = MFI_FRAME_DIR_NONE;
2629         dcmd->timeout = 0;
2630         dcmd->data_xfer_len = 0;
2631         dcmd->opcode = opcode;
2632
2633         megasas_issue_blocked_cmd(instance, cmd);
2634
2635         megasas_return_cmd(instance, cmd);
2636
2637         return;
2638 }
2639
2640 /**
2641  * megasas_suspend -    driver suspend entry point
2642  * @pdev:               PCI device structure
2643  * @state:              PCI power state to suspend routine
2644  */
2645 static int __devinit
2646 megasas_suspend(struct pci_dev *pdev, pm_message_t state)
2647 {
2648         struct Scsi_Host *host;
2649         struct megasas_instance *instance;
2650
2651         instance = pci_get_drvdata(pdev);
2652         host = instance->host;
2653
2654         if (poll_mode_io)
2655                 del_timer_sync(&instance->io_completion_timer);
2656
2657         megasas_flush_cache(instance);
2658         megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
2659         tasklet_kill(&instance->isr_tasklet);
2660
2661         pci_set_drvdata(instance->pdev, instance);
2662         instance->instancet->disable_intr(instance->reg_set);
2663         free_irq(instance->pdev->irq, instance);
2664
2665         pci_save_state(pdev);
2666         pci_disable_device(pdev);
2667
2668         pci_set_power_state(pdev, pci_choose_state(pdev, state));
2669
2670         return 0;
2671 }
2672
2673 /**
2674  * megasas_resume-      driver resume entry point
2675  * @pdev:               PCI device structure
2676  */
2677 static int __devinit
2678 megasas_resume(struct pci_dev *pdev)
2679 {
2680         int rval;
2681         struct Scsi_Host *host;
2682         struct megasas_instance *instance;
2683
2684         instance = pci_get_drvdata(pdev);
2685         host = instance->host;
2686         pci_set_power_state(pdev, PCI_D0);
2687         pci_enable_wake(pdev, PCI_D0, 0);
2688         pci_restore_state(pdev);
2689
2690         /*
2691          * PCI prepping: enable device set bus mastering and dma mask
2692          */
2693         rval = pci_enable_device(pdev);
2694
2695         if (rval) {
2696                 printk(KERN_ERR "megasas: Enable device failed\n");
2697                 return rval;
2698         }
2699
2700         pci_set_master(pdev);
2701
2702         if (megasas_set_dma_mask(pdev))
2703                 goto fail_set_dma_mask;
2704
2705         /*
2706          * Initialize MFI Firmware
2707          */
2708
2709         *instance->producer = 0;
2710         *instance->consumer = 0;
2711
2712         atomic_set(&instance->fw_outstanding, 0);
2713
2714         /*
2715          * We expect the FW state to be READY
2716          */
2717         if (megasas_transition_to_ready(instance))
2718                 goto fail_ready_state;
2719
2720         if (megasas_issue_init_mfi(instance))
2721                 goto fail_init_mfi;
2722
2723         tasklet_init(&instance->isr_tasklet, megasas_complete_cmd_dpc,
2724                         (unsigned long)instance);
2725
2726         /*
2727          * Register IRQ
2728          */
2729         if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED,
2730                 "megasas", instance)) {
2731                 printk(KERN_ERR "megasas: Failed to register IRQ\n");
2732                 goto fail_irq;
2733         }
2734
2735         instance->instancet->enable_intr(instance->reg_set);
2736
2737         /*
2738          * Initiate AEN (Asynchronous Event Notification)
2739          */
2740         if (megasas_start_aen(instance))
2741                 printk(KERN_ERR "megasas: Start AEN failed\n");
2742
2743         /* Initialize the cmd completion timer */
2744         if (poll_mode_io)
2745                 megasas_start_timer(instance, &instance->io_completion_timer,
2746                                 megasas_io_completion_timer,
2747                                 MEGASAS_COMPLETION_TIMER_INTERVAL);
2748         return 0;
2749
2750 fail_irq:
2751 fail_init_mfi:
2752         if (instance->evt_detail)
2753                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
2754                                 instance->evt_detail,
2755                                 instance->evt_detail_h);
2756
2757         if (instance->producer)
2758                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
2759                                 instance->producer_h);
2760         if (instance->consumer)
2761                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
2762                                 instance->consumer_h);
2763         scsi_host_put(host);
2764
2765 fail_set_dma_mask:
2766 fail_ready_state:
2767
2768         pci_disable_device(pdev);
2769
2770         return -ENODEV;
2771 }
2772
2773 /**
2774  * megasas_detach_one - PCI hot"un"plug entry point
2775  * @pdev:               PCI device structure
2776  */
2777 static void megasas_detach_one(struct pci_dev *pdev)
2778 {
2779         int i;
2780         struct Scsi_Host *host;
2781         struct megasas_instance *instance;
2782
2783         instance = pci_get_drvdata(pdev);
2784         host = instance->host;
2785
2786         if (poll_mode_io)
2787                 del_timer_sync(&instance->io_completion_timer);
2788
2789         scsi_remove_host(instance->host);
2790         megasas_flush_cache(instance);
2791         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
2792         tasklet_kill(&instance->isr_tasklet);
2793
2794         /*
2795          * Take the instance off the instance array. Note that we will not
2796          * decrement the max_index. We let this array be sparse array
2797          */
2798         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
2799                 if (megasas_mgmt_info.instance[i] == instance) {
2800                         megasas_mgmt_info.count--;
2801                         megasas_mgmt_info.instance[i] = NULL;
2802
2803                         break;
2804                 }
2805         }
2806
2807         pci_set_drvdata(instance->pdev, NULL);
2808
2809         instance->instancet->disable_intr(instance->reg_set);
2810
2811         free_irq(instance->pdev->irq, instance);
2812
2813         megasas_release_mfi(instance);
2814
2815         pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
2816                             instance->evt_detail, instance->evt_detail_h);
2817
2818         pci_free_consistent(pdev, sizeof(u32), instance->producer,
2819                             instance->producer_h);
2820
2821         pci_free_consistent(pdev, sizeof(u32), instance->consumer,
2822                             instance->consumer_h);
2823
2824         scsi_host_put(host);
2825
2826         pci_set_drvdata(pdev, NULL);
2827
2828         pci_disable_device(pdev);
2829
2830         return;
2831 }
2832
2833 /**
2834  * megasas_shutdown -   Shutdown entry point
2835  * @device:             Generic device structure
2836  */
2837 static void megasas_shutdown(struct pci_dev *pdev)
2838 {
2839         struct megasas_instance *instance = pci_get_drvdata(pdev);
2840         megasas_flush_cache(instance);
2841 }
2842
2843 /**
2844  * megasas_mgmt_open -  char node "open" entry point
2845  */
2846 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
2847 {
2848         /*
2849          * Allow only those users with admin rights
2850          */
2851         if (!capable(CAP_SYS_ADMIN))
2852                 return -EACCES;
2853
2854         return 0;
2855 }
2856
2857 /**
2858  * megasas_mgmt_release - char node "release" entry point
2859  */
2860 static int megasas_mgmt_release(struct inode *inode, struct file *filep)
2861 {
2862         filep->private_data = NULL;
2863         fasync_helper(-1, filep, 0, &megasas_async_queue);
2864
2865         return 0;
2866 }
2867
2868 /**
2869  * megasas_mgmt_fasync -        Async notifier registration from applications
2870  *
2871  * This function adds the calling process to a driver global queue. When an
2872  * event occurs, SIGIO will be sent to all processes in this queue.
2873  */
2874 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
2875 {
2876         int rc;
2877
2878         mutex_lock(&megasas_async_queue_mutex);
2879
2880         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
2881
2882         mutex_unlock(&megasas_async_queue_mutex);
2883
2884         if (rc >= 0) {
2885                 /* For sanity check when we get ioctl */
2886                 filep->private_data = filep;
2887                 return 0;
2888         }
2889
2890         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
2891
2892         return rc;
2893 }
2894
2895 /**
2896  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
2897  * @instance:                   Adapter soft state
2898  * @argp:                       User's ioctl packet
2899  */
2900 static int
2901 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
2902                       struct megasas_iocpacket __user * user_ioc,
2903                       struct megasas_iocpacket *ioc)
2904 {
2905         struct megasas_sge32 *kern_sge32;
2906         struct megasas_cmd *cmd;
2907         void *kbuff_arr[MAX_IOCTL_SGE];
2908         dma_addr_t buf_handle = 0;
2909         int error = 0, i;
2910         void *sense = NULL;
2911         dma_addr_t sense_handle;
2912         u32 *sense_ptr;
2913         unsigned long *sense_buff;
2914
2915         memset(kbuff_arr, 0, sizeof(kbuff_arr));
2916
2917         if (ioc->sge_count > MAX_IOCTL_SGE) {
2918                 printk(KERN_DEBUG "megasas: SGE count [%d] >  max limit [%d]\n",
2919                        ioc->sge_count, MAX_IOCTL_SGE);
2920                 return -EINVAL;
2921         }
2922
2923         cmd = megasas_get_cmd(instance);
2924         if (!cmd) {
2925                 printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
2926                 return -ENOMEM;
2927         }
2928
2929         /*
2930          * User's IOCTL packet has 2 frames (maximum). Copy those two
2931          * frames into our cmd's frames. cmd->frame's context will get
2932          * overwritten when we copy from user's frames. So set that value
2933          * alone separately
2934          */
2935         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
2936         cmd->frame->hdr.context = cmd->index;
2937
2938         /*
2939          * The management interface between applications and the fw uses
2940          * MFI frames. E.g, RAID configuration changes, LD property changes
2941          * etc are accomplishes through different kinds of MFI frames. The
2942          * driver needs to care only about substituting user buffers with
2943          * kernel buffers in SGLs. The location of SGL is embedded in the
2944          * struct iocpacket itself.
2945          */
2946         kern_sge32 = (struct megasas_sge32 *)
2947             ((unsigned long)cmd->frame + ioc->sgl_off);
2948
2949         /*
2950          * For each user buffer, create a mirror buffer and copy in
2951          */
2952         for (i = 0; i < ioc->sge_count; i++) {
2953                 kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
2954                                                     ioc->sgl[i].iov_len,
2955                                                     &buf_handle, GFP_KERNEL);
2956                 if (!kbuff_arr[i]) {
2957                         printk(KERN_DEBUG "megasas: Failed to alloc "
2958                                "kernel SGL buffer for IOCTL \n");
2959                         error = -ENOMEM;
2960                         goto out;
2961                 }
2962
2963                 /*
2964                  * We don't change the dma_coherent_mask, so
2965                  * pci_alloc_consistent only returns 32bit addresses
2966                  */
2967                 kern_sge32[i].phys_addr = (u32) buf_handle;
2968                 kern_sge32[i].length = ioc->sgl[i].iov_len;
2969
2970                 /*
2971                  * We created a kernel buffer corresponding to the
2972                  * user buffer. Now copy in from the user buffer
2973                  */
2974                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
2975                                    (u32) (ioc->sgl[i].iov_len))) {
2976                         error = -EFAULT;
2977                         goto out;
2978                 }
2979         }
2980
2981         if (ioc->sense_len) {
2982                 sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
2983                                              &sense_handle, GFP_KERNEL);
2984                 if (!sense) {
2985                         error = -ENOMEM;
2986                         goto out;
2987                 }
2988
2989                 sense_ptr =
2990                     (u32 *) ((unsigned long)cmd->frame + ioc->sense_off);
2991                 *sense_ptr = sense_handle;
2992         }
2993
2994         /*
2995          * Set the sync_cmd flag so that the ISR knows not to complete this
2996          * cmd to the SCSI mid-layer
2997          */
2998         cmd->sync_cmd = 1;
2999         megasas_issue_blocked_cmd(instance, cmd);
3000         cmd->sync_cmd = 0;
3001
3002         /*
3003          * copy out the kernel buffers to user buffers
3004          */
3005         for (i = 0; i < ioc->sge_count; i++) {
3006                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
3007                                  ioc->sgl[i].iov_len)) {
3008                         error = -EFAULT;
3009                         goto out;
3010                 }
3011         }
3012
3013         /*
3014          * copy out the sense
3015          */
3016         if (ioc->sense_len) {
3017                 /*
3018                  * sense_buff points to the location that has the user
3019                  * sense buffer address
3020                  */
3021                 sense_buff = (unsigned long *) ((unsigned long)ioc->frame.raw +
3022                                                                 ioc->sense_off);
3023
3024                 if (copy_to_user((void __user *)(unsigned long)(*sense_buff),
3025                                 sense, ioc->sense_len)) {
3026                         printk(KERN_ERR "megasas: Failed to copy out to user "
3027                                         "sense data\n");
3028                         error = -EFAULT;
3029                         goto out;
3030                 }
3031         }
3032
3033         /*
3034          * copy the status codes returned by the fw
3035          */
3036         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
3037                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
3038                 printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
3039                 error = -EFAULT;
3040         }
3041
3042       out:
3043         if (sense) {
3044                 dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
3045                                     sense, sense_handle);
3046         }
3047
3048         for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) {
3049                 dma_free_coherent(&instance->pdev->dev,
3050                                     kern_sge32[i].length,
3051                                     kbuff_arr[i], kern_sge32[i].phys_addr);
3052         }
3053
3054         megasas_return_cmd(instance, cmd);
3055         return error;
3056 }
3057
3058 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
3059 {
3060         int i;
3061
3062         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
3063
3064                 if ((megasas_mgmt_info.instance[i]) &&
3065                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
3066                         return megasas_mgmt_info.instance[i];
3067         }
3068
3069         return NULL;
3070 }
3071
3072 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
3073 {
3074         struct megasas_iocpacket __user *user_ioc =
3075             (struct megasas_iocpacket __user *)arg;
3076         struct megasas_iocpacket *ioc;
3077         struct megasas_instance *instance;
3078         int error;
3079
3080         ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
3081         if (!ioc)
3082                 return -ENOMEM;
3083
3084         if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
3085                 error = -EFAULT;
3086                 goto out_kfree_ioc;
3087         }
3088
3089         instance = megasas_lookup_instance(ioc->host_no);
3090         if (!instance) {
3091                 error = -ENODEV;
3092                 goto out_kfree_ioc;
3093         }
3094
3095         /*
3096          * We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
3097          */
3098         if (down_interruptible(&instance->ioctl_sem)) {
3099                 error = -ERESTARTSYS;
3100                 goto out_kfree_ioc;
3101         }
3102         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
3103         up(&instance->ioctl_sem);
3104
3105       out_kfree_ioc:
3106         kfree(ioc);
3107         return error;
3108 }
3109
3110 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
3111 {
3112         struct megasas_instance *instance;
3113         struct megasas_aen aen;
3114         int error;
3115
3116         if (file->private_data != file) {
3117                 printk(KERN_DEBUG "megasas: fasync_helper was not "
3118                        "called first\n");
3119                 return -EINVAL;
3120         }
3121
3122         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
3123                 return -EFAULT;
3124
3125         instance = megasas_lookup_instance(aen.host_no);
3126
3127         if (!instance)
3128                 return -ENODEV;
3129
3130         mutex_lock(&instance->aen_mutex);
3131         error = megasas_register_aen(instance, aen.seq_num,
3132                                      aen.class_locale_word);
3133         mutex_unlock(&instance->aen_mutex);
3134         return error;
3135 }
3136
3137 /**
3138  * megasas_mgmt_ioctl - char node ioctl entry point
3139  */
3140 static long
3141 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3142 {
3143         switch (cmd) {
3144         case MEGASAS_IOC_FIRMWARE:
3145                 return megasas_mgmt_ioctl_fw(file, arg);
3146
3147         case MEGASAS_IOC_GET_AEN:
3148                 return megasas_mgmt_ioctl_aen(file, arg);
3149         }
3150
3151         return -ENOTTY;
3152 }
3153
3154 #ifdef CONFIG_COMPAT
3155 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
3156 {
3157         struct compat_megasas_iocpacket __user *cioc =
3158             (struct compat_megasas_iocpacket __user *)arg;
3159         struct megasas_iocpacket __user *ioc =
3160             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
3161         int i;
3162         int error = 0;
3163
3164         if (clear_user(ioc, sizeof(*ioc)))
3165                 return -EFAULT;
3166
3167         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
3168             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
3169             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
3170             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
3171             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
3172             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
3173                 return -EFAULT;
3174
3175         for (i = 0; i < MAX_IOCTL_SGE; i++) {
3176                 compat_uptr_t ptr;
3177
3178                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
3179                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
3180                     copy_in_user(&ioc->sgl[i].iov_len,
3181                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
3182                         return -EFAULT;
3183         }
3184
3185         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
3186
3187         if (copy_in_user(&cioc->frame.hdr.cmd_status,
3188                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
3189                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
3190                 return -EFAULT;
3191         }
3192         return error;
3193 }
3194
3195 static long
3196 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
3197                           unsigned long arg)
3198 {
3199         switch (cmd) {
3200         case MEGASAS_IOC_FIRMWARE32:
3201                 return megasas_mgmt_compat_ioctl_fw(file, arg);
3202         case MEGASAS_IOC_GET_AEN:
3203                 return megasas_mgmt_ioctl_aen(file, arg);
3204         }
3205
3206         return -ENOTTY;
3207 }
3208 #endif
3209
3210 /*
3211  * File operations structure for management interface
3212  */
3213 static const struct file_operations megasas_mgmt_fops = {
3214         .owner = THIS_MODULE,
3215         .open = megasas_mgmt_open,
3216         .release = megasas_mgmt_release,
3217         .fasync = megasas_mgmt_fasync,
3218         .unlocked_ioctl = megasas_mgmt_ioctl,
3219 #ifdef CONFIG_COMPAT
3220         .compat_ioctl = megasas_mgmt_compat_ioctl,
3221 #endif
3222 };
3223
3224 /*
3225  * PCI hotplug support registration structure
3226  */
3227 static struct pci_driver megasas_pci_driver = {
3228
3229         .name = "megaraid_sas",
3230         .id_table = megasas_pci_table,
3231         .probe = megasas_probe_one,
3232         .remove = __devexit_p(megasas_detach_one),
3233         .suspend = megasas_suspend,
3234         .resume = megasas_resume,
3235         .shutdown = megasas_shutdown,
3236 };
3237
3238 /*
3239  * Sysfs driver attributes
3240  */
3241 static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
3242 {
3243         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
3244                         MEGASAS_VERSION);
3245 }
3246
3247 static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
3248
3249 static ssize_t
3250 megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
3251 {
3252         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
3253                         MEGASAS_RELDATE);
3254 }
3255
3256 static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
3257                    NULL);
3258
3259 static ssize_t
3260 megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
3261 {
3262         return sprintf(buf, "%u\n", megasas_dbg_lvl);
3263 }
3264
3265 static ssize_t
3266 megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
3267 {
3268         int retval = count;
3269         if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
3270                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
3271                 retval = -EINVAL;
3272         }
3273         return retval;
3274 }
3275
3276 static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUGO, megasas_sysfs_show_dbg_lvl,
3277                 megasas_sysfs_set_dbg_lvl);
3278
3279 static ssize_t
3280 megasas_sysfs_show_poll_mode_io(struct device_driver *dd, char *buf)
3281 {
3282         return sprintf(buf, "%u\n", poll_mode_io);
3283 }
3284
3285 static ssize_t
3286 megasas_sysfs_set_poll_mode_io(struct device_driver *dd,
3287                                 const char *buf, size_t count)
3288 {
3289         int retval = count;
3290         int tmp = poll_mode_io;
3291         int i;
3292         struct megasas_instance *instance;
3293
3294         if (sscanf(buf, "%u", &poll_mode_io) < 1) {
3295                 printk(KERN_ERR "megasas: could not set poll_mode_io\n");
3296                 retval = -EINVAL;
3297         }
3298
3299         /*
3300          * Check if poll_mode_io is already set or is same as previous value
3301          */
3302         if ((tmp && poll_mode_io) || (tmp == poll_mode_io))
3303                 goto out;
3304
3305         if (poll_mode_io) {
3306                 /*
3307                  * Start timers for all adapters
3308                  */
3309                 for (i = 0; i < megasas_mgmt_info.max_index; i++) {
3310                         instance = megasas_mgmt_info.instance[i];
3311                         if (instance) {
3312                                 megasas_start_timer(instance,
3313                                         &instance->io_completion_timer,
3314                                         megasas_io_completion_timer,
3315                                         MEGASAS_COMPLETION_TIMER_INTERVAL);
3316                         }
3317                 }
3318         } else {
3319                 /*
3320                  * Delete timers for all adapters
3321                  */
3322                 for (i = 0; i < megasas_mgmt_info.max_index; i++) {
3323                         instance = megasas_mgmt_info.instance[i];
3324                         if (instance)
3325                                 del_timer_sync(&instance->io_completion_timer);
3326                 }
3327         }
3328
3329 out:
3330         return retval;
3331 }
3332
3333 static DRIVER_ATTR(poll_mode_io, S_IRUGO|S_IWUGO,
3334                 megasas_sysfs_show_poll_mode_io,
3335                 megasas_sysfs_set_poll_mode_io);
3336
3337 /**
3338  * megasas_init - Driver load entry point
3339  */
3340 static int __init megasas_init(void)
3341 {
3342         int rval;
3343
3344         /*
3345          * Announce driver version and other information
3346          */
3347         printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
3348                MEGASAS_EXT_VERSION);
3349
3350         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
3351
3352         /*
3353          * Register character device node
3354          */
3355         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
3356
3357         if (rval < 0) {
3358                 printk(KERN_DEBUG "megasas: failed to open device node\n");
3359                 return rval;
3360         }
3361
3362         megasas_mgmt_majorno = rval;
3363
3364         /*
3365          * Register ourselves as PCI hotplug module
3366          */
3367         rval = pci_register_driver(&megasas_pci_driver);
3368
3369         if (rval) {
3370                 printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
3371                 goto err_pcidrv;
3372         }
3373
3374         rval = driver_create_file(&megasas_pci_driver.driver,
3375                                   &driver_attr_version);
3376         if (rval)
3377                 goto err_dcf_attr_ver;
3378         rval = driver_create_file(&megasas_pci_driver.driver,
3379                                   &driver_attr_release_date);
3380         if (rval)
3381                 goto err_dcf_rel_date;
3382         rval = driver_create_file(&megasas_pci_driver.driver,
3383                                   &driver_attr_dbg_lvl);
3384         if (rval)
3385                 goto err_dcf_dbg_lvl;
3386         rval = driver_create_file(&megasas_pci_driver.driver,
3387                                   &driver_attr_poll_mode_io);
3388         if (rval)
3389                 goto err_dcf_poll_mode_io;
3390
3391         return rval;
3392
3393 err_dcf_poll_mode_io:
3394         driver_remove_file(&megasas_pci_driver.driver,
3395                            &driver_attr_dbg_lvl);
3396 err_dcf_dbg_lvl:
3397         driver_remove_file(&megasas_pci_driver.driver,
3398                            &driver_attr_release_date);
3399 err_dcf_rel_date:
3400         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
3401 err_dcf_attr_ver:
3402         pci_unregister_driver(&megasas_pci_driver);
3403 err_pcidrv:
3404         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
3405         return rval;
3406 }
3407
3408 /**
3409  * megasas_exit - Driver unload entry point
3410  */
3411 static void __exit megasas_exit(void)
3412 {
3413         driver_remove_file(&megasas_pci_driver.driver,
3414                            &driver_attr_poll_mode_io);
3415         driver_remove_file(&megasas_pci_driver.driver,
3416                            &driver_attr_dbg_lvl);
3417         driver_remove_file(&megasas_pci_driver.driver,
3418                            &driver_attr_release_date);
3419         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
3420
3421         pci_unregister_driver(&megasas_pci_driver);
3422         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
3423 }
3424
3425 module_init(megasas_init);
3426 module_exit(megasas_exit);