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