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