Merge branch 'llseek' of git://git.kernel.org/pub/scm/linux/kernel/git/arnd/bkl
[linux-2.6.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.17.1-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/uio.h>
37 #include <linux/slab.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->pad_0 = 0;
847         pthru->flags = flags;
848         pthru->data_xfer_len = scsi_bufflen(scp);
849
850         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
851
852         /*
853         * If the command is for the tape device, set the
854         * pthru timeout to the os layer timeout value.
855         */
856         if (scp->device->type == TYPE_TAPE) {
857                 if ((scp->request->timeout / HZ) > 0xFFFF)
858                         pthru->timeout = 0xFFFF;
859                 else
860                         pthru->timeout = scp->request->timeout / HZ;
861         }
862
863         /*
864          * Construct SGL
865          */
866         if (instance->flag_ieee == 1) {
867                 pthru->flags |= MFI_FRAME_SGL64;
868                 pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
869                                                       &pthru->sgl);
870         } else if (IS_DMA64) {
871                 pthru->flags |= MFI_FRAME_SGL64;
872                 pthru->sge_count = megasas_make_sgl64(instance, scp,
873                                                       &pthru->sgl);
874         } else
875                 pthru->sge_count = megasas_make_sgl32(instance, scp,
876                                                       &pthru->sgl);
877
878         if (pthru->sge_count > instance->max_num_sge) {
879                 printk(KERN_ERR "megasas: DCDB two many SGE NUM=%x\n",
880                         pthru->sge_count);
881                 return 0;
882         }
883
884         /*
885          * Sense info specific
886          */
887         pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
888         pthru->sense_buf_phys_addr_hi = 0;
889         pthru->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
890
891         /*
892          * Compute the total number of frames this command consumes. FW uses
893          * this number to pull sufficient number of frames from host memory.
894          */
895         cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
896                                                         PTHRU_FRAME);
897
898         return cmd->frame_count;
899 }
900
901 /**
902  * megasas_build_ldio - Prepares IOs to logical devices
903  * @instance:           Adapter soft state
904  * @scp:                SCSI command
905  * @cmd:                Command to be prepared
906  *
907  * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
908  */
909 static int
910 megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
911                    struct megasas_cmd *cmd)
912 {
913         u32 device_id;
914         u8 sc = scp->cmnd[0];
915         u16 flags = 0;
916         struct megasas_io_frame *ldio;
917
918         device_id = MEGASAS_DEV_INDEX(instance, scp);
919         ldio = (struct megasas_io_frame *)cmd->frame;
920
921         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
922                 flags = MFI_FRAME_DIR_WRITE;
923         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
924                 flags = MFI_FRAME_DIR_READ;
925
926         if (instance->flag_ieee == 1) {
927                 flags |= MFI_FRAME_IEEE;
928         }
929
930         /*
931          * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
932          */
933         ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
934         ldio->cmd_status = 0x0;
935         ldio->scsi_status = 0x0;
936         ldio->target_id = device_id;
937         ldio->timeout = 0;
938         ldio->reserved_0 = 0;
939         ldio->pad_0 = 0;
940         ldio->flags = flags;
941         ldio->start_lba_hi = 0;
942         ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
943
944         /*
945          * 6-byte READ(0x08) or WRITE(0x0A) cdb
946          */
947         if (scp->cmd_len == 6) {
948                 ldio->lba_count = (u32) scp->cmnd[4];
949                 ldio->start_lba_lo = ((u32) scp->cmnd[1] << 16) |
950                     ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
951
952                 ldio->start_lba_lo &= 0x1FFFFF;
953         }
954
955         /*
956          * 10-byte READ(0x28) or WRITE(0x2A) cdb
957          */
958         else if (scp->cmd_len == 10) {
959                 ldio->lba_count = (u32) scp->cmnd[8] |
960                     ((u32) scp->cmnd[7] << 8);
961                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
962                     ((u32) scp->cmnd[3] << 16) |
963                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
964         }
965
966         /*
967          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
968          */
969         else if (scp->cmd_len == 12) {
970                 ldio->lba_count = ((u32) scp->cmnd[6] << 24) |
971                     ((u32) scp->cmnd[7] << 16) |
972                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
973
974                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
975                     ((u32) scp->cmnd[3] << 16) |
976                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
977         }
978
979         /*
980          * 16-byte READ(0x88) or WRITE(0x8A) cdb
981          */
982         else if (scp->cmd_len == 16) {
983                 ldio->lba_count = ((u32) scp->cmnd[10] << 24) |
984                     ((u32) scp->cmnd[11] << 16) |
985                     ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
986
987                 ldio->start_lba_lo = ((u32) scp->cmnd[6] << 24) |
988                     ((u32) scp->cmnd[7] << 16) |
989                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
990
991                 ldio->start_lba_hi = ((u32) scp->cmnd[2] << 24) |
992                     ((u32) scp->cmnd[3] << 16) |
993                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
994
995         }
996
997         /*
998          * Construct SGL
999          */
1000         if (instance->flag_ieee) {
1001                 ldio->flags |= MFI_FRAME_SGL64;
1002                 ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
1003                                               &ldio->sgl);
1004         } else if (IS_DMA64) {
1005                 ldio->flags |= MFI_FRAME_SGL64;
1006                 ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
1007         } else
1008                 ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
1009
1010         if (ldio->sge_count > instance->max_num_sge) {
1011                 printk(KERN_ERR "megasas: build_ld_io: sge_count = %x\n",
1012                         ldio->sge_count);
1013                 return 0;
1014         }
1015
1016         /*
1017          * Sense info specific
1018          */
1019         ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
1020         ldio->sense_buf_phys_addr_hi = 0;
1021         ldio->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
1022
1023         /*
1024          * Compute the total number of frames this command consumes. FW uses
1025          * this number to pull sufficient number of frames from host memory.
1026          */
1027         cmd->frame_count = megasas_get_frame_count(instance,
1028                         ldio->sge_count, IO_FRAME);
1029
1030         return cmd->frame_count;
1031 }
1032
1033 /**
1034  * megasas_is_ldio -            Checks if the cmd is for logical drive
1035  * @scmd:                       SCSI command
1036  *      
1037  * Called by megasas_queue_command to find out if the command to be queued
1038  * is a logical drive command   
1039  */
1040 static inline int megasas_is_ldio(struct scsi_cmnd *cmd)
1041 {
1042         if (!MEGASAS_IS_LOGICAL(cmd))
1043                 return 0;
1044         switch (cmd->cmnd[0]) {
1045         case READ_10:
1046         case WRITE_10:
1047         case READ_12:
1048         case WRITE_12:
1049         case READ_6:
1050         case WRITE_6:
1051         case READ_16:
1052         case WRITE_16:
1053                 return 1;
1054         default:
1055                 return 0;
1056         }
1057 }
1058
1059  /**
1060  * megasas_dump_pending_frames -        Dumps the frame address of all pending cmds
1061  *                                      in FW
1062  * @instance:                           Adapter soft state
1063  */
1064 static inline void
1065 megasas_dump_pending_frames(struct megasas_instance *instance)
1066 {
1067         struct megasas_cmd *cmd;
1068         int i,n;
1069         union megasas_sgl *mfi_sgl;
1070         struct megasas_io_frame *ldio;
1071         struct megasas_pthru_frame *pthru;
1072         u32 sgcount;
1073         u32 max_cmd = instance->max_fw_cmds;
1074
1075         printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
1076         printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
1077         if (IS_DMA64)
1078                 printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
1079         else
1080                 printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
1081
1082         printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
1083         for (i = 0; i < max_cmd; i++) {
1084                 cmd = instance->cmd_list[i];
1085                 if(!cmd->scmd)
1086                         continue;
1087                 printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
1088                 if (megasas_is_ldio(cmd->scmd)){
1089                         ldio = (struct megasas_io_frame *)cmd->frame;
1090                         mfi_sgl = &ldio->sgl;
1091                         sgcount = ldio->sge_count;
1092                         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);
1093                 }
1094                 else {
1095                         pthru = (struct megasas_pthru_frame *) cmd->frame;
1096                         mfi_sgl = &pthru->sgl;
1097                         sgcount = pthru->sge_count;
1098                         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);
1099                 }
1100         if(megasas_dbg_lvl & MEGASAS_DBG_LVL){
1101                 for (n = 0; n < sgcount; n++){
1102                         if (IS_DMA64)
1103                                 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) ;
1104                         else
1105                                 printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",mfi_sgl->sge32[n].length , mfi_sgl->sge32[n].phys_addr) ;
1106                         }
1107                 }
1108                 printk(KERN_ERR "\n");
1109         } /*for max_cmd*/
1110         printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
1111         for (i = 0; i < max_cmd; i++) {
1112
1113                 cmd = instance->cmd_list[i];
1114
1115                 if(cmd->sync_cmd == 1){
1116                         printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
1117                 }
1118         }
1119         printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no);
1120 }
1121
1122 /**
1123  * megasas_queue_command -      Queue entry point
1124  * @scmd:                       SCSI command to be queued
1125  * @done:                       Callback entry point
1126  */
1127 static int
1128 megasas_queue_command(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *))
1129 {
1130         u32 frame_count;
1131         struct megasas_cmd *cmd;
1132         struct megasas_instance *instance;
1133
1134         instance = (struct megasas_instance *)
1135             scmd->device->host->hostdata;
1136
1137         /* Don't process if we have already declared adapter dead */
1138         if (instance->hw_crit_error)
1139                 return SCSI_MLQUEUE_HOST_BUSY;
1140
1141         scmd->scsi_done = done;
1142         scmd->result = 0;
1143
1144         if (MEGASAS_IS_LOGICAL(scmd) &&
1145             (scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) {
1146                 scmd->result = DID_BAD_TARGET << 16;
1147                 goto out_done;
1148         }
1149
1150         switch (scmd->cmnd[0]) {
1151         case SYNCHRONIZE_CACHE:
1152                 /*
1153                  * FW takes care of flush cache on its own
1154                  * No need to send it down
1155                  */
1156                 scmd->result = DID_OK << 16;
1157                 goto out_done;
1158         default:
1159                 break;
1160         }
1161
1162         cmd = megasas_get_cmd(instance);
1163         if (!cmd)
1164                 return SCSI_MLQUEUE_HOST_BUSY;
1165
1166         /*
1167          * Logical drive command
1168          */
1169         if (megasas_is_ldio(scmd))
1170                 frame_count = megasas_build_ldio(instance, scmd, cmd);
1171         else
1172                 frame_count = megasas_build_dcdb(instance, scmd, cmd);
1173
1174         if (!frame_count)
1175                 goto out_return_cmd;
1176
1177         cmd->scmd = scmd;
1178         scmd->SCp.ptr = (char *)cmd;
1179
1180         /*
1181          * Issue the command to the FW
1182          */
1183         atomic_inc(&instance->fw_outstanding);
1184
1185         instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
1186                                 cmd->frame_count-1, instance->reg_set);
1187         /*
1188          * Check if we have pend cmds to be completed
1189          */
1190         if (poll_mode_io && atomic_read(&instance->fw_outstanding))
1191                 tasklet_schedule(&instance->isr_tasklet);
1192
1193
1194         return 0;
1195
1196  out_return_cmd:
1197         megasas_return_cmd(instance, cmd);
1198  out_done:
1199         done(scmd);
1200         return 0;
1201 }
1202
1203 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
1204 {
1205         int i;
1206
1207         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
1208
1209                 if ((megasas_mgmt_info.instance[i]) &&
1210                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
1211                         return megasas_mgmt_info.instance[i];
1212         }
1213
1214         return NULL;
1215 }
1216
1217 static int megasas_slave_configure(struct scsi_device *sdev)
1218 {
1219         u16             pd_index = 0;
1220         struct  megasas_instance *instance ;
1221
1222         instance = megasas_lookup_instance(sdev->host->host_no);
1223
1224         /*
1225         * Don't export physical disk devices to the disk driver.
1226         *
1227         * FIXME: Currently we don't export them to the midlayer at all.
1228         *        That will be fixed once LSI engineers have audited the
1229         *        firmware for possible issues.
1230         */
1231         if (sdev->channel < MEGASAS_MAX_PD_CHANNELS &&
1232                                 sdev->type == TYPE_DISK) {
1233                 pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1234                                                                 sdev->id;
1235                 if (instance->pd_list[pd_index].driveState ==
1236                                                 MR_PD_STATE_SYSTEM) {
1237                         blk_queue_rq_timeout(sdev->request_queue,
1238                                 MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
1239                         return 0;
1240                 }
1241                 return -ENXIO;
1242         }
1243
1244         /*
1245         * The RAID firmware may require extended timeouts.
1246         */
1247         blk_queue_rq_timeout(sdev->request_queue,
1248                 MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
1249         return 0;
1250 }
1251
1252 static int megasas_slave_alloc(struct scsi_device *sdev)
1253 {
1254         u16             pd_index = 0;
1255         struct megasas_instance *instance ;
1256         instance = megasas_lookup_instance(sdev->host->host_no);
1257         if ((sdev->channel < MEGASAS_MAX_PD_CHANNELS) &&
1258                                 (sdev->type == TYPE_DISK)) {
1259                 /*
1260                  * Open the OS scan to the SYSTEM PD
1261                  */
1262                 pd_index =
1263                         (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1264                         sdev->id;
1265                 if ((instance->pd_list[pd_index].driveState ==
1266                                         MR_PD_STATE_SYSTEM) &&
1267                         (instance->pd_list[pd_index].driveType ==
1268                                                 TYPE_DISK)) {
1269                         return 0;
1270                 }
1271                 return -ENXIO;
1272         }
1273         return 0;
1274 }
1275
1276 /**
1277  * megasas_complete_cmd_dpc      -      Returns FW's controller structure
1278  * @instance_addr:                      Address of adapter soft state
1279  *
1280  * Tasklet to complete cmds
1281  */
1282 static void megasas_complete_cmd_dpc(unsigned long instance_addr)
1283 {
1284         u32 producer;
1285         u32 consumer;
1286         u32 context;
1287         struct megasas_cmd *cmd;
1288         struct megasas_instance *instance =
1289                                 (struct megasas_instance *)instance_addr;
1290         unsigned long flags;
1291
1292         /* If we have already declared adapter dead, donot complete cmds */
1293         if (instance->hw_crit_error)
1294                 return;
1295
1296         spin_lock_irqsave(&instance->completion_lock, flags);
1297
1298         producer = *instance->producer;
1299         consumer = *instance->consumer;
1300
1301         while (consumer != producer) {
1302                 context = instance->reply_queue[consumer];
1303
1304                 cmd = instance->cmd_list[context];
1305
1306                 megasas_complete_cmd(instance, cmd, DID_OK);
1307
1308                 consumer++;
1309                 if (consumer == (instance->max_fw_cmds + 1)) {
1310                         consumer = 0;
1311                 }
1312         }
1313
1314         *instance->consumer = producer;
1315
1316         spin_unlock_irqrestore(&instance->completion_lock, flags);
1317
1318         /*
1319          * Check if we can restore can_queue
1320          */
1321         if (instance->flag & MEGASAS_FW_BUSY
1322                 && time_after(jiffies, instance->last_time + 5 * HZ)
1323                 && atomic_read(&instance->fw_outstanding) < 17) {
1324
1325                 spin_lock_irqsave(instance->host->host_lock, flags);
1326                 instance->flag &= ~MEGASAS_FW_BUSY;
1327                 if ((instance->pdev->device ==
1328                         PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1329                         (instance->pdev->device ==
1330                         PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
1331                         instance->host->can_queue =
1332                                 instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
1333                 } else
1334                         instance->host->can_queue =
1335                                 instance->max_fw_cmds - MEGASAS_INT_CMDS;
1336
1337                 spin_unlock_irqrestore(instance->host->host_lock, flags);
1338         }
1339 }
1340
1341 /**
1342  * megasas_wait_for_outstanding -       Wait for all outstanding cmds
1343  * @instance:                           Adapter soft state
1344  *
1345  * This function waits for upto MEGASAS_RESET_WAIT_TIME seconds for FW to
1346  * complete all its outstanding commands. Returns error if one or more IOs
1347  * are pending after this time period. It also marks the controller dead.
1348  */
1349 static int megasas_wait_for_outstanding(struct megasas_instance *instance)
1350 {
1351         int i;
1352         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
1353
1354         for (i = 0; i < wait_time; i++) {
1355
1356                 int outstanding = atomic_read(&instance->fw_outstanding);
1357
1358                 if (!outstanding)
1359                         break;
1360
1361                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
1362                         printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
1363                                "commands to complete\n",i,outstanding);
1364                         /*
1365                          * Call cmd completion routine. Cmd to be
1366                          * be completed directly without depending on isr.
1367                          */
1368                         megasas_complete_cmd_dpc((unsigned long)instance);
1369                 }
1370
1371                 msleep(1000);
1372         }
1373
1374         if (atomic_read(&instance->fw_outstanding)) {
1375                 /*
1376                 * Send signal to FW to stop processing any pending cmds.
1377                 * The controller will be taken offline by the OS now.
1378                 */
1379                 if ((instance->pdev->device ==
1380                         PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1381                         (instance->pdev->device ==
1382                         PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
1383                         writel(MFI_STOP_ADP,
1384                                 &instance->reg_set->reserved_0[0]);
1385                 } else {
1386                         writel(MFI_STOP_ADP,
1387                                 &instance->reg_set->inbound_doorbell);
1388                 }
1389                 megasas_dump_pending_frames(instance);
1390                 instance->hw_crit_error = 1;
1391                 return FAILED;
1392         }
1393
1394         return SUCCESS;
1395 }
1396
1397 /**
1398  * megasas_generic_reset -      Generic reset routine
1399  * @scmd:                       Mid-layer SCSI command
1400  *
1401  * This routine implements a generic reset handler for device, bus and host
1402  * reset requests. Device, bus and host specific reset handlers can use this
1403  * function after they do their specific tasks.
1404  */
1405 static int megasas_generic_reset(struct scsi_cmnd *scmd)
1406 {
1407         int ret_val;
1408         struct megasas_instance *instance;
1409
1410         instance = (struct megasas_instance *)scmd->device->host->hostdata;
1411
1412         scmd_printk(KERN_NOTICE, scmd, "megasas: RESET -%ld cmd=%x retries=%x\n",
1413                  scmd->serial_number, scmd->cmnd[0], scmd->retries);
1414
1415         if (instance->hw_crit_error) {
1416                 printk(KERN_ERR "megasas: cannot recover from previous reset "
1417                        "failures\n");
1418                 return FAILED;
1419         }
1420
1421         ret_val = megasas_wait_for_outstanding(instance);
1422         if (ret_val == SUCCESS)
1423                 printk(KERN_NOTICE "megasas: reset successful \n");
1424         else
1425                 printk(KERN_ERR "megasas: failed to do reset\n");
1426
1427         return ret_val;
1428 }
1429
1430 /**
1431  * megasas_reset_timer - quiesce the adapter if required
1432  * @scmd:               scsi cmnd
1433  *
1434  * Sets the FW busy flag and reduces the host->can_queue if the
1435  * cmd has not been completed within the timeout period.
1436  */
1437 static enum
1438 blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
1439 {
1440         struct megasas_cmd *cmd = (struct megasas_cmd *)scmd->SCp.ptr;
1441         struct megasas_instance *instance;
1442         unsigned long flags;
1443
1444         if (time_after(jiffies, scmd->jiffies_at_alloc +
1445                                 (MEGASAS_DEFAULT_CMD_TIMEOUT * 2) * HZ)) {
1446                 return BLK_EH_NOT_HANDLED;
1447         }
1448
1449         instance = cmd->instance;
1450         if (!(instance->flag & MEGASAS_FW_BUSY)) {
1451                 /* FW is busy, throttle IO */
1452                 spin_lock_irqsave(instance->host->host_lock, flags);
1453
1454                 instance->host->can_queue = 16;
1455                 instance->last_time = jiffies;
1456                 instance->flag |= MEGASAS_FW_BUSY;
1457
1458                 spin_unlock_irqrestore(instance->host->host_lock, flags);
1459         }
1460         return BLK_EH_RESET_TIMER;
1461 }
1462
1463 /**
1464  * megasas_reset_device -       Device reset handler entry point
1465  */
1466 static int megasas_reset_device(struct scsi_cmnd *scmd)
1467 {
1468         int ret;
1469
1470         /*
1471          * First wait for all commands to complete
1472          */
1473         ret = megasas_generic_reset(scmd);
1474
1475         return ret;
1476 }
1477
1478 /**
1479  * megasas_reset_bus_host -     Bus & host reset handler entry point
1480  */
1481 static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
1482 {
1483         int ret;
1484
1485         /*
1486          * First wait for all commands to complete
1487          */
1488         ret = megasas_generic_reset(scmd);
1489
1490         return ret;
1491 }
1492
1493 /**
1494  * megasas_bios_param - Returns disk geometry for a disk
1495  * @sdev:               device handle
1496  * @bdev:               block device
1497  * @capacity:           drive capacity
1498  * @geom:               geometry parameters
1499  */
1500 static int
1501 megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
1502                  sector_t capacity, int geom[])
1503 {
1504         int heads;
1505         int sectors;
1506         sector_t cylinders;
1507         unsigned long tmp;
1508         /* Default heads (64) & sectors (32) */
1509         heads = 64;
1510         sectors = 32;
1511
1512         tmp = heads * sectors;
1513         cylinders = capacity;
1514
1515         sector_div(cylinders, tmp);
1516
1517         /*
1518          * Handle extended translation size for logical drives > 1Gb
1519          */
1520
1521         if (capacity >= 0x200000) {
1522                 heads = 255;
1523                 sectors = 63;
1524                 tmp = heads*sectors;
1525                 cylinders = capacity;
1526                 sector_div(cylinders, tmp);
1527         }
1528
1529         geom[0] = heads;
1530         geom[1] = sectors;
1531         geom[2] = cylinders;
1532
1533         return 0;
1534 }
1535
1536 static void megasas_aen_polling(struct work_struct *work);
1537
1538 /**
1539  * megasas_service_aen -        Processes an event notification
1540  * @instance:                   Adapter soft state
1541  * @cmd:                        AEN command completed by the ISR
1542  *
1543  * For AEN, driver sends a command down to FW that is held by the FW till an
1544  * event occurs. When an event of interest occurs, FW completes the command
1545  * that it was previously holding.
1546  *
1547  * This routines sends SIGIO signal to processes that have registered with the
1548  * driver for AEN.
1549  */
1550 static void
1551 megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
1552 {
1553         unsigned long flags;
1554         /*
1555          * Don't signal app if it is just an aborted previously registered aen
1556          */
1557         if ((!cmd->abort_aen) && (instance->unload == 0)) {
1558                 spin_lock_irqsave(&poll_aen_lock, flags);
1559                 megasas_poll_wait_aen = 1;
1560                 spin_unlock_irqrestore(&poll_aen_lock, flags);
1561                 wake_up(&megasas_poll_wait);
1562                 kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
1563         }
1564         else
1565                 cmd->abort_aen = 0;
1566
1567         instance->aen_cmd = NULL;
1568         megasas_return_cmd(instance, cmd);
1569
1570         if (instance->unload == 0) {
1571                 struct megasas_aen_event *ev;
1572                 ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
1573                 if (!ev) {
1574                         printk(KERN_ERR "megasas_service_aen: out of memory\n");
1575                 } else {
1576                         ev->instance = instance;
1577                         instance->ev = ev;
1578                         INIT_WORK(&ev->hotplug_work, megasas_aen_polling);
1579                         schedule_delayed_work(
1580                                 (struct delayed_work *)&ev->hotplug_work, 0);
1581                 }
1582         }
1583 }
1584
1585 /*
1586  * Scsi host template for megaraid_sas driver
1587  */
1588 static struct scsi_host_template megasas_template = {
1589
1590         .module = THIS_MODULE,
1591         .name = "LSI SAS based MegaRAID driver",
1592         .proc_name = "megaraid_sas",
1593         .slave_configure = megasas_slave_configure,
1594         .slave_alloc = megasas_slave_alloc,
1595         .queuecommand = megasas_queue_command,
1596         .eh_device_reset_handler = megasas_reset_device,
1597         .eh_bus_reset_handler = megasas_reset_bus_host,
1598         .eh_host_reset_handler = megasas_reset_bus_host,
1599         .eh_timed_out = megasas_reset_timer,
1600         .bios_param = megasas_bios_param,
1601         .use_clustering = ENABLE_CLUSTERING,
1602 };
1603
1604 /**
1605  * megasas_complete_int_cmd -   Completes an internal command
1606  * @instance:                   Adapter soft state
1607  * @cmd:                        Command to be completed
1608  *
1609  * The megasas_issue_blocked_cmd() function waits for a command to complete
1610  * after it issues a command. This function wakes up that waiting routine by
1611  * calling wake_up() on the wait queue.
1612  */
1613 static void
1614 megasas_complete_int_cmd(struct megasas_instance *instance,
1615                          struct megasas_cmd *cmd)
1616 {
1617         cmd->cmd_status = cmd->frame->io.cmd_status;
1618
1619         if (cmd->cmd_status == ENODATA) {
1620                 cmd->cmd_status = 0;
1621         }
1622         wake_up(&instance->int_cmd_wait_q);
1623 }
1624
1625 /**
1626  * megasas_complete_abort -     Completes aborting a command
1627  * @instance:                   Adapter soft state
1628  * @cmd:                        Cmd that was issued to abort another cmd
1629  *
1630  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q 
1631  * after it issues an abort on a previously issued command. This function 
1632  * wakes up all functions waiting on the same wait queue.
1633  */
1634 static void
1635 megasas_complete_abort(struct megasas_instance *instance,
1636                        struct megasas_cmd *cmd)
1637 {
1638         if (cmd->sync_cmd) {
1639                 cmd->sync_cmd = 0;
1640                 cmd->cmd_status = 0;
1641                 wake_up(&instance->abort_cmd_wait_q);
1642         }
1643
1644         return;
1645 }
1646
1647 /**
1648  * megasas_complete_cmd -       Completes a command
1649  * @instance:                   Adapter soft state
1650  * @cmd:                        Command to be completed
1651  * @alt_status:                 If non-zero, use this value as status to 
1652  *                              SCSI mid-layer instead of the value returned
1653  *                              by the FW. This should be used if caller wants
1654  *                              an alternate status (as in the case of aborted
1655  *                              commands)
1656  */
1657 static void
1658 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
1659                      u8 alt_status)
1660 {
1661         int exception = 0;
1662         struct megasas_header *hdr = &cmd->frame->hdr;
1663         unsigned long flags;
1664
1665         if (cmd->scmd)
1666                 cmd->scmd->SCp.ptr = NULL;
1667
1668         switch (hdr->cmd) {
1669
1670         case MFI_CMD_PD_SCSI_IO:
1671         case MFI_CMD_LD_SCSI_IO:
1672
1673                 /*
1674                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
1675                  * issued either through an IO path or an IOCTL path. If it
1676                  * was via IOCTL, we will send it to internal completion.
1677                  */
1678                 if (cmd->sync_cmd) {
1679                         cmd->sync_cmd = 0;
1680                         megasas_complete_int_cmd(instance, cmd);
1681                         break;
1682                 }
1683
1684         case MFI_CMD_LD_READ:
1685         case MFI_CMD_LD_WRITE:
1686
1687                 if (alt_status) {
1688                         cmd->scmd->result = alt_status << 16;
1689                         exception = 1;
1690                 }
1691
1692                 if (exception) {
1693
1694                         atomic_dec(&instance->fw_outstanding);
1695
1696                         scsi_dma_unmap(cmd->scmd);
1697                         cmd->scmd->scsi_done(cmd->scmd);
1698                         megasas_return_cmd(instance, cmd);
1699
1700                         break;
1701                 }
1702
1703                 switch (hdr->cmd_status) {
1704
1705                 case MFI_STAT_OK:
1706                         cmd->scmd->result = DID_OK << 16;
1707                         break;
1708
1709                 case MFI_STAT_SCSI_IO_FAILED:
1710                 case MFI_STAT_LD_INIT_IN_PROGRESS:
1711                         cmd->scmd->result =
1712                             (DID_ERROR << 16) | hdr->scsi_status;
1713                         break;
1714
1715                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
1716
1717                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
1718
1719                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
1720                                 memset(cmd->scmd->sense_buffer, 0,
1721                                        SCSI_SENSE_BUFFERSIZE);
1722                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
1723                                        hdr->sense_len);
1724
1725                                 cmd->scmd->result |= DRIVER_SENSE << 24;
1726                         }
1727
1728                         break;
1729
1730                 case MFI_STAT_LD_OFFLINE:
1731                 case MFI_STAT_DEVICE_NOT_FOUND:
1732                         cmd->scmd->result = DID_BAD_TARGET << 16;
1733                         break;
1734
1735                 default:
1736                         printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
1737                                hdr->cmd_status);
1738                         cmd->scmd->result = DID_ERROR << 16;
1739                         break;
1740                 }
1741
1742                 atomic_dec(&instance->fw_outstanding);
1743
1744                 scsi_dma_unmap(cmd->scmd);
1745                 cmd->scmd->scsi_done(cmd->scmd);
1746                 megasas_return_cmd(instance, cmd);
1747
1748                 break;
1749
1750         case MFI_CMD_SMP:
1751         case MFI_CMD_STP:
1752         case MFI_CMD_DCMD:
1753                 if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
1754                         cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET) {
1755                         spin_lock_irqsave(&poll_aen_lock, flags);
1756                         megasas_poll_wait_aen = 0;
1757                         spin_unlock_irqrestore(&poll_aen_lock, flags);
1758                 }
1759
1760                 /*
1761                  * See if got an event notification
1762                  */
1763                 if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT)
1764                         megasas_service_aen(instance, cmd);
1765                 else
1766                         megasas_complete_int_cmd(instance, cmd);
1767
1768                 break;
1769
1770         case MFI_CMD_ABORT:
1771                 /*
1772                  * Cmd issued to abort another cmd returned
1773                  */
1774                 megasas_complete_abort(instance, cmd);
1775                 break;
1776
1777         default:
1778                 printk("megasas: Unknown command completed! [0x%X]\n",
1779                        hdr->cmd);
1780                 break;
1781         }
1782 }
1783
1784 /**
1785  * megasas_deplete_reply_queue -        Processes all completed commands
1786  * @instance:                           Adapter soft state
1787  * @alt_status:                         Alternate status to be returned to
1788  *                                      SCSI mid-layer instead of the status
1789  *                                      returned by the FW
1790  */
1791 static int
1792 megasas_deplete_reply_queue(struct megasas_instance *instance, u8 alt_status)
1793 {
1794         /*
1795          * Check if it is our interrupt
1796          * Clear the interrupt 
1797          */
1798         if(instance->instancet->clear_intr(instance->reg_set))
1799                 return IRQ_NONE;
1800
1801         if (instance->hw_crit_error)
1802                 goto out_done;
1803         /*
1804          * Schedule the tasklet for cmd completion
1805          */
1806         tasklet_schedule(&instance->isr_tasklet);
1807 out_done:
1808         return IRQ_HANDLED;
1809 }
1810
1811 /**
1812  * megasas_isr - isr entry point
1813  */
1814 static irqreturn_t megasas_isr(int irq, void *devp)
1815 {
1816         return megasas_deplete_reply_queue((struct megasas_instance *)devp,
1817                                            DID_OK);
1818 }
1819
1820 /**
1821  * megasas_transition_to_ready -        Move the FW to READY state
1822  * @instance:                           Adapter soft state
1823  *
1824  * During the initialization, FW passes can potentially be in any one of
1825  * several possible states. If the FW in operational, waiting-for-handshake
1826  * states, driver must take steps to bring it to ready state. Otherwise, it
1827  * has to wait for the ready state.
1828  */
1829 static int
1830 megasas_transition_to_ready(struct megasas_instance* instance)
1831 {
1832         int i;
1833         u8 max_wait;
1834         u32 fw_state;
1835         u32 cur_state;
1836         u32 abs_state, curr_abs_state;
1837
1838         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
1839
1840         if (fw_state != MFI_STATE_READY)
1841                 printk(KERN_INFO "megasas: Waiting for FW to come to ready"
1842                        " state\n");
1843
1844         while (fw_state != MFI_STATE_READY) {
1845
1846                 abs_state =
1847                 instance->instancet->read_fw_status_reg(instance->reg_set);
1848
1849                 switch (fw_state) {
1850
1851                 case MFI_STATE_FAULT:
1852
1853                         printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
1854                         return -ENODEV;
1855
1856                 case MFI_STATE_WAIT_HANDSHAKE:
1857                         /*
1858                          * Set the CLR bit in inbound doorbell
1859                          */
1860                         if ((instance->pdev->device ==
1861                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1862                                 (instance->pdev->device ==
1863                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
1864
1865                                 writel(
1866                                   MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
1867                                   &instance->reg_set->reserved_0[0]);
1868                         } else {
1869                                 writel(
1870                                     MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
1871                                         &instance->reg_set->inbound_doorbell);
1872                         }
1873
1874                         max_wait = MEGASAS_RESET_WAIT_TIME;
1875                         cur_state = MFI_STATE_WAIT_HANDSHAKE;
1876                         break;
1877
1878                 case MFI_STATE_BOOT_MESSAGE_PENDING:
1879                         if ((instance->pdev->device ==
1880                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1881                         (instance->pdev->device ==
1882                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
1883                                 writel(MFI_INIT_HOTPLUG,
1884                                 &instance->reg_set->reserved_0[0]);
1885                         } else
1886                                 writel(MFI_INIT_HOTPLUG,
1887                                         &instance->reg_set->inbound_doorbell);
1888
1889                         max_wait = MEGASAS_RESET_WAIT_TIME;
1890                         cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
1891                         break;
1892
1893                 case MFI_STATE_OPERATIONAL:
1894                         /*
1895                          * Bring it to READY state; assuming max wait 10 secs
1896                          */
1897                         instance->instancet->disable_intr(instance->reg_set);
1898                         if ((instance->pdev->device ==
1899                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1900                                 (instance->pdev->device ==
1901                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
1902                                 writel(MFI_RESET_FLAGS,
1903                                         &instance->reg_set->reserved_0[0]);
1904                         } else
1905                                 writel(MFI_RESET_FLAGS,
1906                                         &instance->reg_set->inbound_doorbell);
1907
1908                         max_wait = MEGASAS_RESET_WAIT_TIME;
1909                         cur_state = MFI_STATE_OPERATIONAL;
1910                         break;
1911
1912                 case MFI_STATE_UNDEFINED:
1913                         /*
1914                          * This state should not last for more than 2 seconds
1915                          */
1916                         max_wait = MEGASAS_RESET_WAIT_TIME;
1917                         cur_state = MFI_STATE_UNDEFINED;
1918                         break;
1919
1920                 case MFI_STATE_BB_INIT:
1921                         max_wait = MEGASAS_RESET_WAIT_TIME;
1922                         cur_state = MFI_STATE_BB_INIT;
1923                         break;
1924
1925                 case MFI_STATE_FW_INIT:
1926                         max_wait = MEGASAS_RESET_WAIT_TIME;
1927                         cur_state = MFI_STATE_FW_INIT;
1928                         break;
1929
1930                 case MFI_STATE_FW_INIT_2:
1931                         max_wait = MEGASAS_RESET_WAIT_TIME;
1932                         cur_state = MFI_STATE_FW_INIT_2;
1933                         break;
1934
1935                 case MFI_STATE_DEVICE_SCAN:
1936                         max_wait = MEGASAS_RESET_WAIT_TIME;
1937                         cur_state = MFI_STATE_DEVICE_SCAN;
1938                         break;
1939
1940                 case MFI_STATE_FLUSH_CACHE:
1941                         max_wait = MEGASAS_RESET_WAIT_TIME;
1942                         cur_state = MFI_STATE_FLUSH_CACHE;
1943                         break;
1944
1945                 default:
1946                         printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
1947                                fw_state);
1948                         return -ENODEV;
1949                 }
1950
1951                 /*
1952                  * The cur_state should not last for more than max_wait secs
1953                  */
1954                 for (i = 0; i < (max_wait * 1000); i++) {
1955                         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &  
1956                                         MFI_STATE_MASK ;
1957                 curr_abs_state =
1958                 instance->instancet->read_fw_status_reg(instance->reg_set);
1959
1960                         if (abs_state == curr_abs_state) {
1961                                 msleep(1);
1962                         } else
1963                                 break;
1964                 }
1965
1966                 /*
1967                  * Return error if fw_state hasn't changed after max_wait
1968                  */
1969                 if (curr_abs_state == abs_state) {
1970                         printk(KERN_DEBUG "FW state [%d] hasn't changed "
1971                                "in %d secs\n", fw_state, max_wait);
1972                         return -ENODEV;
1973                 }
1974         };
1975         printk(KERN_INFO "megasas: FW now in Ready state\n");
1976
1977         return 0;
1978 }
1979
1980 /**
1981  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
1982  * @instance:                           Adapter soft state
1983  */
1984 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
1985 {
1986         int i;
1987         u32 max_cmd = instance->max_fw_cmds;
1988         struct megasas_cmd *cmd;
1989
1990         if (!instance->frame_dma_pool)
1991                 return;
1992
1993         /*
1994          * Return all frames to pool
1995          */
1996         for (i = 0; i < max_cmd; i++) {
1997
1998                 cmd = instance->cmd_list[i];
1999
2000                 if (cmd->frame)
2001                         pci_pool_free(instance->frame_dma_pool, cmd->frame,
2002                                       cmd->frame_phys_addr);
2003
2004                 if (cmd->sense)
2005                         pci_pool_free(instance->sense_dma_pool, cmd->sense,
2006                                       cmd->sense_phys_addr);
2007         }
2008
2009         /*
2010          * Now destroy the pool itself
2011          */
2012         pci_pool_destroy(instance->frame_dma_pool);
2013         pci_pool_destroy(instance->sense_dma_pool);
2014
2015         instance->frame_dma_pool = NULL;
2016         instance->sense_dma_pool = NULL;
2017 }
2018
2019 /**
2020  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
2021  * @instance:                   Adapter soft state
2022  *
2023  * Each command packet has an embedded DMA memory buffer that is used for
2024  * filling MFI frame and the SG list that immediately follows the frame. This
2025  * function creates those DMA memory buffers for each command packet by using
2026  * PCI pool facility.
2027  */
2028 static int megasas_create_frame_pool(struct megasas_instance *instance)
2029 {
2030         int i;
2031         u32 max_cmd;
2032         u32 sge_sz;
2033         u32 sgl_sz;
2034         u32 total_sz;
2035         u32 frame_count;
2036         struct megasas_cmd *cmd;
2037
2038         max_cmd = instance->max_fw_cmds;
2039
2040         /*
2041          * Size of our frame is 64 bytes for MFI frame, followed by max SG
2042          * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
2043          */
2044         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
2045             sizeof(struct megasas_sge32);
2046
2047         if (instance->flag_ieee) {
2048                 sge_sz = sizeof(struct megasas_sge_skinny);
2049         }
2050
2051         /*
2052          * Calculated the number of 64byte frames required for SGL
2053          */
2054         sgl_sz = sge_sz * instance->max_num_sge;
2055         frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
2056
2057         /*
2058          * We need one extra frame for the MFI command
2059          */
2060         frame_count++;
2061
2062         total_sz = MEGAMFI_FRAME_SIZE * frame_count;
2063         /*
2064          * Use DMA pool facility provided by PCI layer
2065          */
2066         instance->frame_dma_pool = pci_pool_create("megasas frame pool",
2067                                                    instance->pdev, total_sz, 64,
2068                                                    0);
2069
2070         if (!instance->frame_dma_pool) {
2071                 printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
2072                 return -ENOMEM;
2073         }
2074
2075         instance->sense_dma_pool = pci_pool_create("megasas sense pool",
2076                                                    instance->pdev, 128, 4, 0);
2077
2078         if (!instance->sense_dma_pool) {
2079                 printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
2080
2081                 pci_pool_destroy(instance->frame_dma_pool);
2082                 instance->frame_dma_pool = NULL;
2083
2084                 return -ENOMEM;
2085         }
2086
2087         /*
2088          * Allocate and attach a frame to each of the commands in cmd_list.
2089          * By making cmd->index as the context instead of the &cmd, we can
2090          * always use 32bit context regardless of the architecture
2091          */
2092         for (i = 0; i < max_cmd; i++) {
2093
2094                 cmd = instance->cmd_list[i];
2095
2096                 cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
2097                                             GFP_KERNEL, &cmd->frame_phys_addr);
2098
2099                 cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
2100                                             GFP_KERNEL, &cmd->sense_phys_addr);
2101
2102                 /*
2103                  * megasas_teardown_frame_pool() takes care of freeing
2104                  * whatever has been allocated
2105                  */
2106                 if (!cmd->frame || !cmd->sense) {
2107                         printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
2108                         megasas_teardown_frame_pool(instance);
2109                         return -ENOMEM;
2110                 }
2111
2112                 cmd->frame->io.context = cmd->index;
2113                 cmd->frame->io.pad_0 = 0;
2114         }
2115
2116         return 0;
2117 }
2118
2119 /**
2120  * megasas_free_cmds -  Free all the cmds in the free cmd pool
2121  * @instance:           Adapter soft state
2122  */
2123 static void megasas_free_cmds(struct megasas_instance *instance)
2124 {
2125         int i;
2126         /* First free the MFI frame pool */
2127         megasas_teardown_frame_pool(instance);
2128
2129         /* Free all the commands in the cmd_list */
2130         for (i = 0; i < instance->max_fw_cmds; i++)
2131                 kfree(instance->cmd_list[i]);
2132
2133         /* Free the cmd_list buffer itself */
2134         kfree(instance->cmd_list);
2135         instance->cmd_list = NULL;
2136
2137         INIT_LIST_HEAD(&instance->cmd_pool);
2138 }
2139
2140 /**
2141  * megasas_alloc_cmds - Allocates the command packets
2142  * @instance:           Adapter soft state
2143  *
2144  * Each command that is issued to the FW, whether IO commands from the OS or
2145  * internal commands like IOCTLs, are wrapped in local data structure called
2146  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
2147  * the FW.
2148  *
2149  * Each frame has a 32-bit field called context (tag). This context is used
2150  * to get back the megasas_cmd from the frame when a frame gets completed in
2151  * the ISR. Typically the address of the megasas_cmd itself would be used as
2152  * the context. But we wanted to keep the differences between 32 and 64 bit
2153  * systems to the mininum. We always use 32 bit integers for the context. In
2154  * this driver, the 32 bit values are the indices into an array cmd_list.
2155  * This array is used only to look up the megasas_cmd given the context. The
2156  * free commands themselves are maintained in a linked list called cmd_pool.
2157  */
2158 static int megasas_alloc_cmds(struct megasas_instance *instance)
2159 {
2160         int i;
2161         int j;
2162         u32 max_cmd;
2163         struct megasas_cmd *cmd;
2164
2165         max_cmd = instance->max_fw_cmds;
2166
2167         /*
2168          * instance->cmd_list is an array of struct megasas_cmd pointers.
2169          * Allocate the dynamic array first and then allocate individual
2170          * commands.
2171          */
2172         instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
2173
2174         if (!instance->cmd_list) {
2175                 printk(KERN_DEBUG "megasas: out of memory\n");
2176                 return -ENOMEM;
2177         }
2178
2179
2180         for (i = 0; i < max_cmd; i++) {
2181                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
2182                                                 GFP_KERNEL);
2183
2184                 if (!instance->cmd_list[i]) {
2185
2186                         for (j = 0; j < i; j++)
2187                                 kfree(instance->cmd_list[j]);
2188
2189                         kfree(instance->cmd_list);
2190                         instance->cmd_list = NULL;
2191
2192                         return -ENOMEM;
2193                 }
2194         }
2195
2196         /*
2197          * Add all the commands to command pool (instance->cmd_pool)
2198          */
2199         for (i = 0; i < max_cmd; i++) {
2200                 cmd = instance->cmd_list[i];
2201                 memset(cmd, 0, sizeof(struct megasas_cmd));
2202                 cmd->index = i;
2203                 cmd->instance = instance;
2204
2205                 list_add_tail(&cmd->list, &instance->cmd_pool);
2206         }
2207
2208         /*
2209          * Create a frame pool and assign one frame to each cmd
2210          */
2211         if (megasas_create_frame_pool(instance)) {
2212                 printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
2213                 megasas_free_cmds(instance);
2214         }
2215
2216         return 0;
2217 }
2218
2219 /*
2220  * megasas_get_pd_list_info -   Returns FW's pd_list structure
2221  * @instance:                           Adapter soft state
2222  * @pd_list:                            pd_list structure
2223  *
2224  * Issues an internal command (DCMD) to get the FW's controller PD
2225  * list structure.  This information is mainly used to find out SYSTEM
2226  * supported by the FW.
2227  */
2228 static int
2229 megasas_get_pd_list(struct megasas_instance *instance)
2230 {
2231         int ret = 0, pd_index = 0;
2232         struct megasas_cmd *cmd;
2233         struct megasas_dcmd_frame *dcmd;
2234         struct MR_PD_LIST *ci;
2235         struct MR_PD_ADDRESS *pd_addr;
2236         dma_addr_t ci_h = 0;
2237
2238         cmd = megasas_get_cmd(instance);
2239
2240         if (!cmd) {
2241                 printk(KERN_DEBUG "megasas (get_pd_list): Failed to get cmd\n");
2242                 return -ENOMEM;
2243         }
2244
2245         dcmd = &cmd->frame->dcmd;
2246
2247         ci = pci_alloc_consistent(instance->pdev,
2248                   MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), &ci_h);
2249
2250         if (!ci) {
2251                 printk(KERN_DEBUG "Failed to alloc mem for pd_list\n");
2252                 megasas_return_cmd(instance, cmd);
2253                 return -ENOMEM;
2254         }
2255
2256         memset(ci, 0, sizeof(*ci));
2257         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2258
2259         dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
2260         dcmd->mbox.b[1] = 0;
2261         dcmd->cmd = MFI_CMD_DCMD;
2262         dcmd->cmd_status = 0xFF;
2263         dcmd->sge_count = 1;
2264         dcmd->flags = MFI_FRAME_DIR_READ;
2265         dcmd->timeout = 0;
2266         dcmd->pad_0 = 0;
2267         dcmd->data_xfer_len = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST);
2268         dcmd->opcode = MR_DCMD_PD_LIST_QUERY;
2269         dcmd->sgl.sge32[0].phys_addr = ci_h;
2270         dcmd->sgl.sge32[0].length = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST);
2271
2272         if (!megasas_issue_polled(instance, cmd)) {
2273                 ret = 0;
2274         } else {
2275                 ret = -1;
2276         }
2277
2278         /*
2279         * the following function will get the instance PD LIST.
2280         */
2281
2282         pd_addr = ci->addr;
2283
2284         if ( ret == 0 &&
2285                 (ci->count <
2286                   (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL))) {
2287
2288                 memset(instance->pd_list, 0,
2289                         MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
2290
2291                 for (pd_index = 0; pd_index < ci->count; pd_index++) {
2292
2293                         instance->pd_list[pd_addr->deviceId].tid        =
2294                                                         pd_addr->deviceId;
2295                         instance->pd_list[pd_addr->deviceId].driveType  =
2296                                                         pd_addr->scsiDevType;
2297                         instance->pd_list[pd_addr->deviceId].driveState =
2298                                                         MR_PD_STATE_SYSTEM;
2299                         pd_addr++;
2300                 }
2301         }
2302
2303         pci_free_consistent(instance->pdev,
2304                                 MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
2305                                 ci, ci_h);
2306         megasas_return_cmd(instance, cmd);
2307
2308         return ret;
2309 }
2310
2311 /*
2312  * megasas_get_ld_list_info -   Returns FW's ld_list structure
2313  * @instance:                           Adapter soft state
2314  * @ld_list:                            ld_list structure
2315  *
2316  * Issues an internal command (DCMD) to get the FW's controller PD
2317  * list structure.  This information is mainly used to find out SYSTEM
2318  * supported by the FW.
2319  */
2320 static int
2321 megasas_get_ld_list(struct megasas_instance *instance)
2322 {
2323         int ret = 0, ld_index = 0, ids = 0;
2324         struct megasas_cmd *cmd;
2325         struct megasas_dcmd_frame *dcmd;
2326         struct MR_LD_LIST *ci;
2327         dma_addr_t ci_h = 0;
2328
2329         cmd = megasas_get_cmd(instance);
2330
2331         if (!cmd) {
2332                 printk(KERN_DEBUG "megasas_get_ld_list: Failed to get cmd\n");
2333                 return -ENOMEM;
2334         }
2335
2336         dcmd = &cmd->frame->dcmd;
2337
2338         ci = pci_alloc_consistent(instance->pdev,
2339                                 sizeof(struct MR_LD_LIST),
2340                                 &ci_h);
2341
2342         if (!ci) {
2343                 printk(KERN_DEBUG "Failed to alloc mem in get_ld_list\n");
2344                 megasas_return_cmd(instance, cmd);
2345                 return -ENOMEM;
2346         }
2347
2348         memset(ci, 0, sizeof(*ci));
2349         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2350
2351         dcmd->cmd = MFI_CMD_DCMD;
2352         dcmd->cmd_status = 0xFF;
2353         dcmd->sge_count = 1;
2354         dcmd->flags = MFI_FRAME_DIR_READ;
2355         dcmd->timeout = 0;
2356         dcmd->data_xfer_len = sizeof(struct MR_LD_LIST);
2357         dcmd->opcode = MR_DCMD_LD_GET_LIST;
2358         dcmd->sgl.sge32[0].phys_addr = ci_h;
2359         dcmd->sgl.sge32[0].length = sizeof(struct MR_LD_LIST);
2360         dcmd->pad_0  = 0;
2361
2362         if (!megasas_issue_polled(instance, cmd)) {
2363                 ret = 0;
2364         } else {
2365                 ret = -1;
2366         }
2367
2368         /* the following function will get the instance PD LIST */
2369
2370         if ((ret == 0) && (ci->ldCount < MAX_LOGICAL_DRIVES)) {
2371                 memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
2372
2373                 for (ld_index = 0; ld_index < ci->ldCount; ld_index++) {
2374                         if (ci->ldList[ld_index].state != 0) {
2375                                 ids = ci->ldList[ld_index].ref.targetId;
2376                                 instance->ld_ids[ids] =
2377                                         ci->ldList[ld_index].ref.targetId;
2378                         }
2379                 }
2380         }
2381
2382         pci_free_consistent(instance->pdev,
2383                                 sizeof(struct MR_LD_LIST),
2384                                 ci,
2385                                 ci_h);
2386
2387         megasas_return_cmd(instance, cmd);
2388         return ret;
2389 }
2390
2391 /**
2392  * megasas_get_controller_info -        Returns FW's controller structure
2393  * @instance:                           Adapter soft state
2394  * @ctrl_info:                          Controller information structure
2395  *
2396  * Issues an internal command (DCMD) to get the FW's controller structure.
2397  * This information is mainly used to find out the maximum IO transfer per
2398  * command supported by the FW.
2399  */
2400 static int
2401 megasas_get_ctrl_info(struct megasas_instance *instance,
2402                       struct megasas_ctrl_info *ctrl_info)
2403 {
2404         int ret = 0;
2405         struct megasas_cmd *cmd;
2406         struct megasas_dcmd_frame *dcmd;
2407         struct megasas_ctrl_info *ci;
2408         dma_addr_t ci_h = 0;
2409
2410         cmd = megasas_get_cmd(instance);
2411
2412         if (!cmd) {
2413                 printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
2414                 return -ENOMEM;
2415         }
2416
2417         dcmd = &cmd->frame->dcmd;
2418
2419         ci = pci_alloc_consistent(instance->pdev,
2420                                   sizeof(struct megasas_ctrl_info), &ci_h);
2421
2422         if (!ci) {
2423                 printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
2424                 megasas_return_cmd(instance, cmd);
2425                 return -ENOMEM;
2426         }
2427
2428         memset(ci, 0, sizeof(*ci));
2429         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2430
2431         dcmd->cmd = MFI_CMD_DCMD;
2432         dcmd->cmd_status = 0xFF;
2433         dcmd->sge_count = 1;
2434         dcmd->flags = MFI_FRAME_DIR_READ;
2435         dcmd->timeout = 0;
2436         dcmd->pad_0 = 0;
2437         dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info);
2438         dcmd->opcode = MR_DCMD_CTRL_GET_INFO;
2439         dcmd->sgl.sge32[0].phys_addr = ci_h;
2440         dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info);
2441
2442         if (!megasas_issue_polled(instance, cmd)) {
2443                 ret = 0;
2444                 memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
2445         } else {
2446                 ret = -1;
2447         }
2448
2449         pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
2450                             ci, ci_h);
2451
2452         megasas_return_cmd(instance, cmd);
2453         return ret;
2454 }
2455
2456 /**
2457  * megasas_issue_init_mfi -     Initializes the FW
2458  * @instance:           Adapter soft state
2459  *
2460  * Issues the INIT MFI cmd
2461  */
2462 static int
2463 megasas_issue_init_mfi(struct megasas_instance *instance)
2464 {
2465         u32 context;
2466
2467         struct megasas_cmd *cmd;
2468
2469         struct megasas_init_frame *init_frame;
2470         struct megasas_init_queue_info *initq_info;
2471         dma_addr_t init_frame_h;
2472         dma_addr_t initq_info_h;
2473
2474         /*
2475          * Prepare a init frame. Note the init frame points to queue info
2476          * structure. Each frame has SGL allocated after first 64 bytes. For
2477          * this frame - since we don't need any SGL - we use SGL's space as
2478          * queue info structure
2479          *
2480          * We will not get a NULL command below. We just created the pool.
2481          */
2482         cmd = megasas_get_cmd(instance);
2483
2484         init_frame = (struct megasas_init_frame *)cmd->frame;
2485         initq_info = (struct megasas_init_queue_info *)
2486                 ((unsigned long)init_frame + 64);
2487
2488         init_frame_h = cmd->frame_phys_addr;
2489         initq_info_h = init_frame_h + 64;
2490
2491         context = init_frame->context;
2492         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
2493         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
2494         init_frame->context = context;
2495
2496         initq_info->reply_queue_entries = instance->max_fw_cmds + 1;
2497         initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h;
2498
2499         initq_info->producer_index_phys_addr_lo = instance->producer_h;
2500         initq_info->consumer_index_phys_addr_lo = instance->consumer_h;
2501
2502         init_frame->cmd = MFI_CMD_INIT;
2503         init_frame->cmd_status = 0xFF;
2504         init_frame->queue_info_new_phys_addr_lo = initq_info_h;
2505
2506         init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info);
2507
2508         /*
2509          * disable the intr before firing the init frame to FW
2510          */
2511         instance->instancet->disable_intr(instance->reg_set);
2512
2513         /*
2514          * Issue the init frame in polled mode
2515          */
2516
2517         if (megasas_issue_polled(instance, cmd)) {
2518                 printk(KERN_ERR "megasas: Failed to init firmware\n");
2519                 megasas_return_cmd(instance, cmd);
2520                 goto fail_fw_init;
2521         }
2522
2523         megasas_return_cmd(instance, cmd);
2524
2525         return 0;
2526
2527 fail_fw_init:
2528         return -EINVAL;
2529 }
2530
2531 /**
2532  * megasas_start_timer - Initializes a timer object
2533  * @instance:           Adapter soft state
2534  * @timer:              timer object to be initialized
2535  * @fn:                 timer function
2536  * @interval:           time interval between timer function call
2537  */
2538 static inline void
2539 megasas_start_timer(struct megasas_instance *instance,
2540                         struct timer_list *timer,
2541                         void *fn, unsigned long interval)
2542 {
2543         init_timer(timer);
2544         timer->expires = jiffies + interval;
2545         timer->data = (unsigned long)instance;
2546         timer->function = fn;
2547         add_timer(timer);
2548 }
2549
2550 /**
2551  * megasas_io_completion_timer - Timer fn
2552  * @instance_addr:      Address of adapter soft state
2553  *
2554  * Schedules tasklet for cmd completion
2555  * if poll_mode_io is set
2556  */
2557 static void
2558 megasas_io_completion_timer(unsigned long instance_addr)
2559 {
2560         struct megasas_instance *instance =
2561                         (struct megasas_instance *)instance_addr;
2562
2563         if (atomic_read(&instance->fw_outstanding))
2564                 tasklet_schedule(&instance->isr_tasklet);
2565
2566         /* Restart timer */
2567         if (poll_mode_io)
2568                 mod_timer(&instance->io_completion_timer,
2569                         jiffies + MEGASAS_COMPLETION_TIMER_INTERVAL);
2570 }
2571
2572 /**
2573  * megasas_init_mfi -   Initializes the FW
2574  * @instance:           Adapter soft state
2575  *
2576  * This is the main function for initializing MFI firmware.
2577  */
2578 static int megasas_init_mfi(struct megasas_instance *instance)
2579 {
2580         u32 context_sz;
2581         u32 reply_q_sz;
2582         u32 max_sectors_1;
2583         u32 max_sectors_2;
2584         u32 tmp_sectors;
2585         struct megasas_register_set __iomem *reg_set;
2586         struct megasas_ctrl_info *ctrl_info;
2587         /*
2588          * Map the message registers
2589          */
2590         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
2591                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
2592                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2593                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0079GEN2)) {
2594                 instance->base_addr = pci_resource_start(instance->pdev, 1);
2595         } else {
2596                 instance->base_addr = pci_resource_start(instance->pdev, 0);
2597         }
2598
2599         if (pci_request_selected_regions(instance->pdev,
2600                 pci_select_bars(instance->pdev, IORESOURCE_MEM),
2601                 "megasas: LSI")) {
2602                 printk(KERN_DEBUG "megasas: IO memory region busy!\n");
2603                 return -EBUSY;
2604         }
2605
2606         instance->reg_set = ioremap_nocache(instance->base_addr, 8192);
2607
2608         if (!instance->reg_set) {
2609                 printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
2610                 goto fail_ioremap;
2611         }
2612
2613         reg_set = instance->reg_set;
2614
2615         switch(instance->pdev->device)
2616         {
2617                 case PCI_DEVICE_ID_LSI_SAS1078R:
2618                 case PCI_DEVICE_ID_LSI_SAS1078DE:
2619                         instance->instancet = &megasas_instance_template_ppc;
2620                         break;
2621                 case PCI_DEVICE_ID_LSI_SAS1078GEN2:
2622                 case PCI_DEVICE_ID_LSI_SAS0079GEN2:
2623                         instance->instancet = &megasas_instance_template_gen2;
2624                         break;
2625                 case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
2626                 case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
2627                         instance->instancet = &megasas_instance_template_skinny;
2628                         break;
2629                 case PCI_DEVICE_ID_LSI_SAS1064R:
2630                 case PCI_DEVICE_ID_DELL_PERC5:
2631                 default:
2632                         instance->instancet = &megasas_instance_template_xscale;
2633                         break;
2634         }
2635
2636         /*
2637          * We expect the FW state to be READY
2638          */
2639         if (megasas_transition_to_ready(instance))
2640                 goto fail_ready_state;
2641
2642         /*
2643          * Get various operational parameters from status register
2644          */
2645         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
2646         /*
2647          * Reduce the max supported cmds by 1. This is to ensure that the
2648          * reply_q_sz (1 more than the max cmd that driver may send)
2649          * does not exceed max cmds that the FW can support
2650          */
2651         instance->max_fw_cmds = instance->max_fw_cmds-1;
2652         instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >> 
2653                                         0x10;
2654         /*
2655          * Create a pool of commands
2656          */
2657         if (megasas_alloc_cmds(instance))
2658                 goto fail_alloc_cmds;
2659
2660         /*
2661          * Allocate memory for reply queue. Length of reply queue should
2662          * be _one_ more than the maximum commands handled by the firmware.
2663          *
2664          * Note: When FW completes commands, it places corresponding contex
2665          * values in this circular reply queue. This circular queue is a fairly
2666          * typical producer-consumer queue. FW is the producer (of completed
2667          * commands) and the driver is the consumer.
2668          */
2669         context_sz = sizeof(u32);
2670         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
2671
2672         instance->reply_queue = pci_alloc_consistent(instance->pdev,
2673                                                      reply_q_sz,
2674                                                      &instance->reply_queue_h);
2675
2676         if (!instance->reply_queue) {
2677                 printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
2678                 goto fail_reply_queue;
2679         }
2680
2681         if (megasas_issue_init_mfi(instance))
2682                 goto fail_fw_init;
2683
2684         memset(instance->pd_list, 0 ,
2685                 (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
2686         megasas_get_pd_list(instance);
2687
2688         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
2689         megasas_get_ld_list(instance);
2690
2691         ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
2692
2693         /*
2694          * Compute the max allowed sectors per IO: The controller info has two
2695          * limits on max sectors. Driver should use the minimum of these two.
2696          *
2697          * 1 << stripe_sz_ops.min = max sectors per strip
2698          *
2699          * Note that older firmwares ( < FW ver 30) didn't report information
2700          * to calculate max_sectors_1. So the number ended up as zero always.
2701          */
2702         tmp_sectors = 0;
2703         if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
2704
2705                 max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
2706                     ctrl_info->max_strips_per_io;
2707                 max_sectors_2 = ctrl_info->max_request_size;
2708
2709                 tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2);
2710         }
2711
2712         instance->max_sectors_per_req = instance->max_num_sge *
2713                                                 PAGE_SIZE / 512;
2714         if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
2715                 instance->max_sectors_per_req = tmp_sectors;
2716
2717         kfree(ctrl_info);
2718
2719         /*
2720         * Setup tasklet for cmd completion
2721         */
2722
2723         tasklet_init(&instance->isr_tasklet, megasas_complete_cmd_dpc,
2724                 (unsigned long)instance);
2725
2726         /* Initialize the cmd completion timer */
2727         if (poll_mode_io)
2728                 megasas_start_timer(instance, &instance->io_completion_timer,
2729                                 megasas_io_completion_timer,
2730                                 MEGASAS_COMPLETION_TIMER_INTERVAL);
2731         return 0;
2732
2733       fail_fw_init:
2734
2735         pci_free_consistent(instance->pdev, reply_q_sz,
2736                             instance->reply_queue, instance->reply_queue_h);
2737       fail_reply_queue:
2738         megasas_free_cmds(instance);
2739
2740       fail_alloc_cmds:
2741       fail_ready_state:
2742         iounmap(instance->reg_set);
2743
2744       fail_ioremap:
2745         pci_release_selected_regions(instance->pdev,
2746                 pci_select_bars(instance->pdev, IORESOURCE_MEM));
2747
2748         return -EINVAL;
2749 }
2750
2751 /**
2752  * megasas_release_mfi -        Reverses the FW initialization
2753  * @intance:                    Adapter soft state
2754  */
2755 static void megasas_release_mfi(struct megasas_instance *instance)
2756 {
2757         u32 reply_q_sz = sizeof(u32) * (instance->max_fw_cmds + 1);
2758
2759         pci_free_consistent(instance->pdev, reply_q_sz,
2760                             instance->reply_queue, instance->reply_queue_h);
2761
2762         megasas_free_cmds(instance);
2763
2764         iounmap(instance->reg_set);
2765
2766         pci_release_selected_regions(instance->pdev,
2767                 pci_select_bars(instance->pdev, IORESOURCE_MEM));
2768 }
2769
2770 /**
2771  * megasas_get_seq_num -        Gets latest event sequence numbers
2772  * @instance:                   Adapter soft state
2773  * @eli:                        FW event log sequence numbers information
2774  *
2775  * FW maintains a log of all events in a non-volatile area. Upper layers would
2776  * usually find out the latest sequence number of the events, the seq number at
2777  * the boot etc. They would "read" all the events below the latest seq number
2778  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
2779  * number), they would subsribe to AEN (asynchronous event notification) and
2780  * wait for the events to happen.
2781  */
2782 static int
2783 megasas_get_seq_num(struct megasas_instance *instance,
2784                     struct megasas_evt_log_info *eli)
2785 {
2786         struct megasas_cmd *cmd;
2787         struct megasas_dcmd_frame *dcmd;
2788         struct megasas_evt_log_info *el_info;
2789         dma_addr_t el_info_h = 0;
2790
2791         cmd = megasas_get_cmd(instance);
2792
2793         if (!cmd) {
2794                 return -ENOMEM;
2795         }
2796
2797         dcmd = &cmd->frame->dcmd;
2798         el_info = pci_alloc_consistent(instance->pdev,
2799                                        sizeof(struct megasas_evt_log_info),
2800                                        &el_info_h);
2801
2802         if (!el_info) {
2803                 megasas_return_cmd(instance, cmd);
2804                 return -ENOMEM;
2805         }
2806
2807         memset(el_info, 0, sizeof(*el_info));
2808         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2809
2810         dcmd->cmd = MFI_CMD_DCMD;
2811         dcmd->cmd_status = 0x0;
2812         dcmd->sge_count = 1;
2813         dcmd->flags = MFI_FRAME_DIR_READ;
2814         dcmd->timeout = 0;
2815         dcmd->pad_0 = 0;
2816         dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info);
2817         dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO;
2818         dcmd->sgl.sge32[0].phys_addr = el_info_h;
2819         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info);
2820
2821         megasas_issue_blocked_cmd(instance, cmd);
2822
2823         /*
2824          * Copy the data back into callers buffer
2825          */
2826         memcpy(eli, el_info, sizeof(struct megasas_evt_log_info));
2827
2828         pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
2829                             el_info, el_info_h);
2830
2831         megasas_return_cmd(instance, cmd);
2832
2833         return 0;
2834 }
2835
2836 /**
2837  * megasas_register_aen -       Registers for asynchronous event notification
2838  * @instance:                   Adapter soft state
2839  * @seq_num:                    The starting sequence number
2840  * @class_locale:               Class of the event
2841  *
2842  * This function subscribes for AEN for events beyond the @seq_num. It requests
2843  * to be notified if and only if the event is of type @class_locale
2844  */
2845 static int
2846 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
2847                      u32 class_locale_word)
2848 {
2849         int ret_val;
2850         struct megasas_cmd *cmd;
2851         struct megasas_dcmd_frame *dcmd;
2852         union megasas_evt_class_locale curr_aen;
2853         union megasas_evt_class_locale prev_aen;
2854
2855         /*
2856          * If there an AEN pending already (aen_cmd), check if the
2857          * class_locale of that pending AEN is inclusive of the new
2858          * AEN request we currently have. If it is, then we don't have
2859          * to do anything. In other words, whichever events the current
2860          * AEN request is subscribing to, have already been subscribed
2861          * to.
2862          *
2863          * If the old_cmd is _not_ inclusive, then we have to abort
2864          * that command, form a class_locale that is superset of both
2865          * old and current and re-issue to the FW
2866          */
2867
2868         curr_aen.word = class_locale_word;
2869
2870         if (instance->aen_cmd) {
2871
2872                 prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
2873
2874                 /*
2875                  * A class whose enum value is smaller is inclusive of all
2876                  * higher values. If a PROGRESS (= -1) was previously
2877                  * registered, then a new registration requests for higher
2878                  * classes need not be sent to FW. They are automatically
2879                  * included.
2880                  *
2881                  * Locale numbers don't have such hierarchy. They are bitmap
2882                  * values
2883                  */
2884                 if ((prev_aen.members.class <= curr_aen.members.class) &&
2885                     !((prev_aen.members.locale & curr_aen.members.locale) ^
2886                       curr_aen.members.locale)) {
2887                         /*
2888                          * Previously issued event registration includes
2889                          * current request. Nothing to do.
2890                          */
2891                         return 0;
2892                 } else {
2893                         curr_aen.members.locale |= prev_aen.members.locale;
2894
2895                         if (prev_aen.members.class < curr_aen.members.class)
2896                                 curr_aen.members.class = prev_aen.members.class;
2897
2898                         instance->aen_cmd->abort_aen = 1;
2899                         ret_val = megasas_issue_blocked_abort_cmd(instance,
2900                                                                   instance->
2901                                                                   aen_cmd);
2902
2903                         if (ret_val) {
2904                                 printk(KERN_DEBUG "megasas: Failed to abort "
2905                                        "previous AEN command\n");
2906                                 return ret_val;
2907                         }
2908                 }
2909         }
2910
2911         cmd = megasas_get_cmd(instance);
2912
2913         if (!cmd)
2914                 return -ENOMEM;
2915
2916         dcmd = &cmd->frame->dcmd;
2917
2918         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
2919
2920         /*
2921          * Prepare DCMD for aen registration
2922          */
2923         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2924
2925         dcmd->cmd = MFI_CMD_DCMD;
2926         dcmd->cmd_status = 0x0;
2927         dcmd->sge_count = 1;
2928         dcmd->flags = MFI_FRAME_DIR_READ;
2929         dcmd->timeout = 0;
2930         dcmd->pad_0 = 0;
2931         dcmd->data_xfer_len = sizeof(struct megasas_evt_detail);
2932         dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT;
2933         dcmd->mbox.w[0] = seq_num;
2934         dcmd->mbox.w[1] = curr_aen.word;
2935         dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h;
2936         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail);
2937
2938         if (instance->aen_cmd != NULL) {
2939                 megasas_return_cmd(instance, cmd);
2940                 return 0;
2941         }
2942
2943         /*
2944          * Store reference to the cmd used to register for AEN. When an
2945          * application wants us to register for AEN, we have to abort this
2946          * cmd and re-register with a new EVENT LOCALE supplied by that app
2947          */
2948         instance->aen_cmd = cmd;
2949
2950         /*
2951          * Issue the aen registration frame
2952          */
2953         instance->instancet->fire_cmd(instance,
2954                         cmd->frame_phys_addr, 0, instance->reg_set);
2955
2956         return 0;
2957 }
2958
2959 /**
2960  * megasas_start_aen -  Subscribes to AEN during driver load time
2961  * @instance:           Adapter soft state
2962  */
2963 static int megasas_start_aen(struct megasas_instance *instance)
2964 {
2965         struct megasas_evt_log_info eli;
2966         union megasas_evt_class_locale class_locale;
2967
2968         /*
2969          * Get the latest sequence number from FW
2970          */
2971         memset(&eli, 0, sizeof(eli));
2972
2973         if (megasas_get_seq_num(instance, &eli))
2974                 return -1;
2975
2976         /*
2977          * Register AEN with FW for latest sequence number plus 1
2978          */
2979         class_locale.members.reserved = 0;
2980         class_locale.members.locale = MR_EVT_LOCALE_ALL;
2981         class_locale.members.class = MR_EVT_CLASS_DEBUG;
2982
2983         return megasas_register_aen(instance, eli.newest_seq_num + 1,
2984                                     class_locale.word);
2985 }
2986
2987 /**
2988  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
2989  * @instance:           Adapter soft state
2990  */
2991 static int megasas_io_attach(struct megasas_instance *instance)
2992 {
2993         struct Scsi_Host *host = instance->host;
2994
2995         /*
2996          * Export parameters required by SCSI mid-layer
2997          */
2998         host->irq = instance->pdev->irq;
2999         host->unique_id = instance->unique_id;
3000         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3001                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
3002                 host->can_queue =
3003                         instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
3004         } else
3005                 host->can_queue =
3006                         instance->max_fw_cmds - MEGASAS_INT_CMDS;
3007         host->this_id = instance->init_id;
3008         host->sg_tablesize = instance->max_num_sge;
3009         host->max_sectors = instance->max_sectors_per_req;
3010         host->cmd_per_lun = 128;
3011         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
3012         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
3013         host->max_lun = MEGASAS_MAX_LUN;
3014         host->max_cmd_len = 16;
3015
3016         /*
3017          * Notify the mid-layer about the new controller
3018          */
3019         if (scsi_add_host(host, &instance->pdev->dev)) {
3020                 printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
3021                 return -ENODEV;
3022         }
3023
3024         /*
3025          * Trigger SCSI to scan our drives
3026          */
3027         scsi_scan_host(host);
3028         return 0;
3029 }
3030
3031 static int
3032 megasas_set_dma_mask(struct pci_dev *pdev)
3033 {
3034         /*
3035          * All our contollers are capable of performing 64-bit DMA
3036          */
3037         if (IS_DMA64) {
3038                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) {
3039
3040                         if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
3041                                 goto fail_set_dma_mask;
3042                 }
3043         } else {
3044                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
3045                         goto fail_set_dma_mask;
3046         }
3047         return 0;
3048
3049 fail_set_dma_mask:
3050         return 1;
3051 }
3052
3053 /**
3054  * megasas_probe_one -  PCI hotplug entry point
3055  * @pdev:               PCI device structure
3056  * @id:                 PCI ids of supported hotplugged adapter 
3057  */
3058 static int __devinit
3059 megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
3060 {
3061         int rval;
3062         struct Scsi_Host *host;
3063         struct megasas_instance *instance;
3064
3065         /*
3066          * Announce PCI information
3067          */
3068         printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
3069                pdev->vendor, pdev->device, pdev->subsystem_vendor,
3070                pdev->subsystem_device);
3071
3072         printk("bus %d:slot %d:func %d\n",
3073                pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
3074
3075         /*
3076          * PCI prepping: enable device set bus mastering and dma mask
3077          */
3078         rval = pci_enable_device_mem(pdev);
3079
3080         if (rval) {
3081                 return rval;
3082         }
3083
3084         pci_set_master(pdev);
3085
3086         if (megasas_set_dma_mask(pdev))
3087                 goto fail_set_dma_mask;
3088
3089         host = scsi_host_alloc(&megasas_template,
3090                                sizeof(struct megasas_instance));
3091
3092         if (!host) {
3093                 printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
3094                 goto fail_alloc_instance;
3095         }
3096
3097         instance = (struct megasas_instance *)host->hostdata;
3098         memset(instance, 0, sizeof(*instance));
3099
3100         instance->producer = pci_alloc_consistent(pdev, sizeof(u32),
3101                                                   &instance->producer_h);
3102         instance->consumer = pci_alloc_consistent(pdev, sizeof(u32),
3103                                                   &instance->consumer_h);
3104
3105         if (!instance->producer || !instance->consumer) {
3106                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
3107                        "producer, consumer\n");
3108                 goto fail_alloc_dma_buf;
3109         }
3110
3111         *instance->producer = 0;
3112         *instance->consumer = 0;
3113         megasas_poll_wait_aen = 0;
3114         instance->flag_ieee = 0;
3115         instance->ev = NULL;
3116
3117         instance->evt_detail = pci_alloc_consistent(pdev,
3118                                                     sizeof(struct
3119                                                            megasas_evt_detail),
3120                                                     &instance->evt_detail_h);
3121
3122         if (!instance->evt_detail) {
3123                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
3124                        "event detail structure\n");
3125                 goto fail_alloc_dma_buf;
3126         }
3127
3128         /*
3129          * Initialize locks and queues
3130          */
3131         INIT_LIST_HEAD(&instance->cmd_pool);
3132
3133         atomic_set(&instance->fw_outstanding,0);
3134
3135         init_waitqueue_head(&instance->int_cmd_wait_q);
3136         init_waitqueue_head(&instance->abort_cmd_wait_q);
3137
3138         spin_lock_init(&instance->cmd_pool_lock);
3139         spin_lock_init(&instance->fire_lock);
3140         spin_lock_init(&instance->completion_lock);
3141         spin_lock_init(&poll_aen_lock);
3142
3143         mutex_init(&instance->aen_mutex);
3144
3145         /*
3146          * Initialize PCI related and misc parameters
3147          */
3148         instance->pdev = pdev;
3149         instance->host = host;
3150         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
3151         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
3152
3153         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3154                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
3155                 instance->flag_ieee = 1;
3156                 sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
3157         } else
3158                 sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
3159
3160         megasas_dbg_lvl = 0;
3161         instance->flag = 0;
3162         instance->unload = 1;
3163         instance->last_time = 0;
3164
3165         /*
3166          * Initialize MFI Firmware
3167          */
3168         if (megasas_init_mfi(instance))
3169                 goto fail_init_mfi;
3170
3171         /*
3172          * Register IRQ
3173          */
3174         if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED, "megasas", instance)) {
3175                 printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
3176                 goto fail_irq;
3177         }
3178
3179         instance->instancet->enable_intr(instance->reg_set);
3180
3181         /*
3182          * Store instance in PCI softstate
3183          */
3184         pci_set_drvdata(pdev, instance);
3185
3186         /*
3187          * Add this controller to megasas_mgmt_info structure so that it
3188          * can be exported to management applications
3189          */
3190         megasas_mgmt_info.count++;
3191         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
3192         megasas_mgmt_info.max_index++;
3193
3194         /*
3195          * Initiate AEN (Asynchronous Event Notification)
3196          */
3197         if (megasas_start_aen(instance)) {
3198                 printk(KERN_DEBUG "megasas: start aen failed\n");
3199                 goto fail_start_aen;
3200         }
3201
3202         /*
3203          * Register with SCSI mid-layer
3204          */
3205         if (megasas_io_attach(instance))
3206                 goto fail_io_attach;
3207
3208         instance->unload = 0;
3209         return 0;
3210
3211       fail_start_aen:
3212       fail_io_attach:
3213         megasas_mgmt_info.count--;
3214         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
3215         megasas_mgmt_info.max_index--;
3216
3217         pci_set_drvdata(pdev, NULL);
3218         instance->instancet->disable_intr(instance->reg_set);
3219         free_irq(instance->pdev->irq, instance);
3220
3221         megasas_release_mfi(instance);
3222
3223       fail_irq:
3224       fail_init_mfi:
3225       fail_alloc_dma_buf:
3226         if (instance->evt_detail)
3227                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
3228                                     instance->evt_detail,
3229                                     instance->evt_detail_h);
3230
3231         if (instance->producer)
3232                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
3233                                     instance->producer_h);
3234         if (instance->consumer)
3235                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
3236                                     instance->consumer_h);
3237         scsi_host_put(host);
3238
3239       fail_alloc_instance:
3240       fail_set_dma_mask:
3241         pci_disable_device(pdev);
3242
3243         return -ENODEV;
3244 }
3245
3246 /**
3247  * megasas_flush_cache -        Requests FW to flush all its caches
3248  * @instance:                   Adapter soft state
3249  */
3250 static void megasas_flush_cache(struct megasas_instance *instance)
3251 {
3252         struct megasas_cmd *cmd;
3253         struct megasas_dcmd_frame *dcmd;
3254
3255         cmd = megasas_get_cmd(instance);
3256
3257         if (!cmd)
3258                 return;
3259
3260         dcmd = &cmd->frame->dcmd;
3261
3262         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3263
3264         dcmd->cmd = MFI_CMD_DCMD;
3265         dcmd->cmd_status = 0x0;
3266         dcmd->sge_count = 0;
3267         dcmd->flags = MFI_FRAME_DIR_NONE;
3268         dcmd->timeout = 0;
3269         dcmd->pad_0 = 0;
3270         dcmd->data_xfer_len = 0;
3271         dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH;
3272         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
3273
3274         megasas_issue_blocked_cmd(instance, cmd);
3275
3276         megasas_return_cmd(instance, cmd);
3277
3278         return;
3279 }
3280
3281 /**
3282  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
3283  * @instance:                           Adapter soft state
3284  * @opcode:                             Shutdown/Hibernate
3285  */
3286 static void megasas_shutdown_controller(struct megasas_instance *instance,
3287                                         u32 opcode)
3288 {
3289         struct megasas_cmd *cmd;
3290         struct megasas_dcmd_frame *dcmd;
3291
3292         cmd = megasas_get_cmd(instance);
3293
3294         if (!cmd)
3295                 return;
3296
3297         if (instance->aen_cmd)
3298                 megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd);
3299
3300         dcmd = &cmd->frame->dcmd;
3301
3302         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3303
3304         dcmd->cmd = MFI_CMD_DCMD;
3305         dcmd->cmd_status = 0x0;
3306         dcmd->sge_count = 0;
3307         dcmd->flags = MFI_FRAME_DIR_NONE;
3308         dcmd->timeout = 0;
3309         dcmd->pad_0 = 0;
3310         dcmd->data_xfer_len = 0;
3311         dcmd->opcode = opcode;
3312
3313         megasas_issue_blocked_cmd(instance, cmd);
3314
3315         megasas_return_cmd(instance, cmd);
3316
3317         return;
3318 }
3319
3320 #ifdef CONFIG_PM
3321 /**
3322  * megasas_suspend -    driver suspend entry point
3323  * @pdev:               PCI device structure
3324  * @state:              PCI power state to suspend routine
3325  */
3326 static int
3327 megasas_suspend(struct pci_dev *pdev, pm_message_t state)
3328 {
3329         struct Scsi_Host *host;
3330         struct megasas_instance *instance;
3331
3332         instance = pci_get_drvdata(pdev);
3333         host = instance->host;
3334         instance->unload = 1;
3335
3336         if (poll_mode_io)
3337                 del_timer_sync(&instance->io_completion_timer);
3338
3339         megasas_flush_cache(instance);
3340         megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
3341
3342         /* cancel the delayed work if this work still in queue */
3343         if (instance->ev != NULL) {
3344                 struct megasas_aen_event *ev = instance->ev;
3345                 cancel_delayed_work(
3346                         (struct delayed_work *)&ev->hotplug_work);
3347                 flush_scheduled_work();
3348                 instance->ev = NULL;
3349         }
3350
3351         tasklet_kill(&instance->isr_tasklet);
3352
3353         pci_set_drvdata(instance->pdev, instance);
3354         instance->instancet->disable_intr(instance->reg_set);
3355         free_irq(instance->pdev->irq, instance);
3356
3357         pci_save_state(pdev);
3358         pci_disable_device(pdev);
3359
3360         pci_set_power_state(pdev, pci_choose_state(pdev, state));
3361
3362         return 0;
3363 }
3364
3365 /**
3366  * megasas_resume-      driver resume entry point
3367  * @pdev:               PCI device structure
3368  */
3369 static int
3370 megasas_resume(struct pci_dev *pdev)
3371 {
3372         int rval;
3373         struct Scsi_Host *host;
3374         struct megasas_instance *instance;
3375
3376         instance = pci_get_drvdata(pdev);
3377         host = instance->host;
3378         pci_set_power_state(pdev, PCI_D0);
3379         pci_enable_wake(pdev, PCI_D0, 0);
3380         pci_restore_state(pdev);
3381
3382         /*
3383          * PCI prepping: enable device set bus mastering and dma mask
3384          */
3385         rval = pci_enable_device_mem(pdev);
3386
3387         if (rval) {
3388                 printk(KERN_ERR "megasas: Enable device failed\n");
3389                 return rval;
3390         }
3391
3392         pci_set_master(pdev);
3393
3394         if (megasas_set_dma_mask(pdev))
3395                 goto fail_set_dma_mask;
3396
3397         /*
3398          * Initialize MFI Firmware
3399          */
3400
3401         *instance->producer = 0;
3402         *instance->consumer = 0;
3403
3404         atomic_set(&instance->fw_outstanding, 0);
3405
3406         /*
3407          * We expect the FW state to be READY
3408          */
3409         if (megasas_transition_to_ready(instance))
3410                 goto fail_ready_state;
3411
3412         if (megasas_issue_init_mfi(instance))
3413                 goto fail_init_mfi;
3414
3415         tasklet_init(&instance->isr_tasklet, megasas_complete_cmd_dpc,
3416                         (unsigned long)instance);
3417
3418         /*
3419          * Register IRQ
3420          */
3421         if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED,
3422                 "megasas", instance)) {
3423                 printk(KERN_ERR "megasas: Failed to register IRQ\n");
3424                 goto fail_irq;
3425         }
3426
3427         instance->instancet->enable_intr(instance->reg_set);
3428
3429         /*
3430          * Initiate AEN (Asynchronous Event Notification)
3431          */
3432         if (megasas_start_aen(instance))
3433                 printk(KERN_ERR "megasas: Start AEN failed\n");
3434
3435         /* Initialize the cmd completion timer */
3436         if (poll_mode_io)
3437                 megasas_start_timer(instance, &instance->io_completion_timer,
3438                                 megasas_io_completion_timer,
3439                                 MEGASAS_COMPLETION_TIMER_INTERVAL);
3440         instance->unload = 0;
3441
3442         return 0;
3443
3444 fail_irq:
3445 fail_init_mfi:
3446         if (instance->evt_detail)
3447                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
3448                                 instance->evt_detail,
3449                                 instance->evt_detail_h);
3450
3451         if (instance->producer)
3452                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
3453                                 instance->producer_h);
3454         if (instance->consumer)
3455                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
3456                                 instance->consumer_h);
3457         scsi_host_put(host);
3458
3459 fail_set_dma_mask:
3460 fail_ready_state:
3461
3462         pci_disable_device(pdev);
3463
3464         return -ENODEV;
3465 }
3466 #else
3467 #define megasas_suspend NULL
3468 #define megasas_resume  NULL
3469 #endif
3470
3471 /**
3472  * megasas_detach_one - PCI hot"un"plug entry point
3473  * @pdev:               PCI device structure
3474  */
3475 static void __devexit megasas_detach_one(struct pci_dev *pdev)
3476 {
3477         int i;
3478         struct Scsi_Host *host;
3479         struct megasas_instance *instance;
3480
3481         instance = pci_get_drvdata(pdev);
3482         instance->unload = 1;
3483         host = instance->host;
3484
3485         if (poll_mode_io)
3486                 del_timer_sync(&instance->io_completion_timer);
3487
3488         scsi_remove_host(instance->host);
3489         megasas_flush_cache(instance);
3490         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
3491
3492         /* cancel the delayed work if this work still in queue*/
3493         if (instance->ev != NULL) {
3494                 struct megasas_aen_event *ev = instance->ev;
3495                 cancel_delayed_work(
3496                         (struct delayed_work *)&ev->hotplug_work);
3497                 flush_scheduled_work();
3498                 instance->ev = NULL;
3499         }
3500
3501         tasklet_kill(&instance->isr_tasklet);
3502
3503         /*
3504          * Take the instance off the instance array. Note that we will not
3505          * decrement the max_index. We let this array be sparse array
3506          */
3507         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
3508                 if (megasas_mgmt_info.instance[i] == instance) {
3509                         megasas_mgmt_info.count--;
3510                         megasas_mgmt_info.instance[i] = NULL;
3511
3512                         break;
3513                 }
3514         }
3515
3516         pci_set_drvdata(instance->pdev, NULL);
3517
3518         instance->instancet->disable_intr(instance->reg_set);
3519
3520         free_irq(instance->pdev->irq, instance);
3521
3522         megasas_release_mfi(instance);
3523
3524         pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
3525                             instance->evt_detail, instance->evt_detail_h);
3526
3527         pci_free_consistent(pdev, sizeof(u32), instance->producer,
3528                             instance->producer_h);
3529
3530         pci_free_consistent(pdev, sizeof(u32), instance->consumer,
3531                             instance->consumer_h);
3532
3533         scsi_host_put(host);
3534
3535         pci_set_drvdata(pdev, NULL);
3536
3537         pci_disable_device(pdev);
3538
3539         return;
3540 }
3541
3542 /**
3543  * megasas_shutdown -   Shutdown entry point
3544  * @device:             Generic device structure
3545  */
3546 static void megasas_shutdown(struct pci_dev *pdev)
3547 {
3548         struct megasas_instance *instance = pci_get_drvdata(pdev);
3549         instance->unload = 1;
3550         megasas_flush_cache(instance);
3551         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
3552 }
3553
3554 /**
3555  * megasas_mgmt_open -  char node "open" entry point
3556  */
3557 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
3558 {
3559         /*
3560          * Allow only those users with admin rights
3561          */
3562         if (!capable(CAP_SYS_ADMIN))
3563                 return -EACCES;
3564
3565         return 0;
3566 }
3567
3568 /**
3569  * megasas_mgmt_fasync -        Async notifier registration from applications
3570  *
3571  * This function adds the calling process to a driver global queue. When an
3572  * event occurs, SIGIO will be sent to all processes in this queue.
3573  */
3574 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
3575 {
3576         int rc;
3577
3578         mutex_lock(&megasas_async_queue_mutex);
3579
3580         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
3581
3582         mutex_unlock(&megasas_async_queue_mutex);
3583
3584         if (rc >= 0) {
3585                 /* For sanity check when we get ioctl */
3586                 filep->private_data = filep;
3587                 return 0;
3588         }
3589
3590         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
3591
3592         return rc;
3593 }
3594
3595 /**
3596  * megasas_mgmt_poll -  char node "poll" entry point
3597  * */
3598 static unsigned int megasas_mgmt_poll(struct file *file, poll_table *wait)
3599 {
3600         unsigned int mask;
3601         unsigned long flags;
3602         poll_wait(file, &megasas_poll_wait, wait);
3603         spin_lock_irqsave(&poll_aen_lock, flags);
3604         if (megasas_poll_wait_aen)
3605                 mask =   (POLLIN | POLLRDNORM);
3606         else
3607                 mask = 0;
3608         spin_unlock_irqrestore(&poll_aen_lock, flags);
3609         return mask;
3610 }
3611
3612 /**
3613  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
3614  * @instance:                   Adapter soft state
3615  * @argp:                       User's ioctl packet
3616  */
3617 static int
3618 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
3619                       struct megasas_iocpacket __user * user_ioc,
3620                       struct megasas_iocpacket *ioc)
3621 {
3622         struct megasas_sge32 *kern_sge32;
3623         struct megasas_cmd *cmd;
3624         void *kbuff_arr[MAX_IOCTL_SGE];
3625         dma_addr_t buf_handle = 0;
3626         int error = 0, i;
3627         void *sense = NULL;
3628         dma_addr_t sense_handle;
3629         unsigned long *sense_ptr;
3630
3631         memset(kbuff_arr, 0, sizeof(kbuff_arr));
3632
3633         if (ioc->sge_count > MAX_IOCTL_SGE) {
3634                 printk(KERN_DEBUG "megasas: SGE count [%d] >  max limit [%d]\n",
3635                        ioc->sge_count, MAX_IOCTL_SGE);
3636                 return -EINVAL;
3637         }
3638
3639         cmd = megasas_get_cmd(instance);
3640         if (!cmd) {
3641                 printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
3642                 return -ENOMEM;
3643         }
3644
3645         /*
3646          * User's IOCTL packet has 2 frames (maximum). Copy those two
3647          * frames into our cmd's frames. cmd->frame's context will get
3648          * overwritten when we copy from user's frames. So set that value
3649          * alone separately
3650          */
3651         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
3652         cmd->frame->hdr.context = cmd->index;
3653         cmd->frame->hdr.pad_0 = 0;
3654
3655         /*
3656          * The management interface between applications and the fw uses
3657          * MFI frames. E.g, RAID configuration changes, LD property changes
3658          * etc are accomplishes through different kinds of MFI frames. The
3659          * driver needs to care only about substituting user buffers with
3660          * kernel buffers in SGLs. The location of SGL is embedded in the
3661          * struct iocpacket itself.
3662          */
3663         kern_sge32 = (struct megasas_sge32 *)
3664             ((unsigned long)cmd->frame + ioc->sgl_off);
3665
3666         /*
3667          * For each user buffer, create a mirror buffer and copy in
3668          */
3669         for (i = 0; i < ioc->sge_count; i++) {
3670                 kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
3671                                                     ioc->sgl[i].iov_len,
3672                                                     &buf_handle, GFP_KERNEL);
3673                 if (!kbuff_arr[i]) {
3674                         printk(KERN_DEBUG "megasas: Failed to alloc "
3675                                "kernel SGL buffer for IOCTL \n");
3676                         error = -ENOMEM;
3677                         goto out;
3678                 }
3679
3680                 /*
3681                  * We don't change the dma_coherent_mask, so
3682                  * pci_alloc_consistent only returns 32bit addresses
3683                  */
3684                 kern_sge32[i].phys_addr = (u32) buf_handle;
3685                 kern_sge32[i].length = ioc->sgl[i].iov_len;
3686
3687                 /*
3688                  * We created a kernel buffer corresponding to the
3689                  * user buffer. Now copy in from the user buffer
3690                  */
3691                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
3692                                    (u32) (ioc->sgl[i].iov_len))) {
3693                         error = -EFAULT;
3694                         goto out;
3695                 }
3696         }
3697
3698         if (ioc->sense_len) {
3699                 sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
3700                                              &sense_handle, GFP_KERNEL);
3701                 if (!sense) {
3702                         error = -ENOMEM;
3703                         goto out;
3704                 }
3705
3706                 sense_ptr =
3707                 (unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off);
3708                 *sense_ptr = sense_handle;
3709         }
3710
3711         /*
3712          * Set the sync_cmd flag so that the ISR knows not to complete this
3713          * cmd to the SCSI mid-layer
3714          */
3715         cmd->sync_cmd = 1;
3716         megasas_issue_blocked_cmd(instance, cmd);
3717         cmd->sync_cmd = 0;
3718
3719         /*
3720          * copy out the kernel buffers to user buffers
3721          */
3722         for (i = 0; i < ioc->sge_count; i++) {
3723                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
3724                                  ioc->sgl[i].iov_len)) {
3725                         error = -EFAULT;
3726                         goto out;
3727                 }
3728         }
3729
3730         /*
3731          * copy out the sense
3732          */
3733         if (ioc->sense_len) {
3734                 /*
3735                  * sense_ptr points to the location that has the user
3736                  * sense buffer address
3737                  */
3738                 sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
3739                                 ioc->sense_off);
3740
3741                 if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
3742                                  sense, ioc->sense_len)) {
3743                         printk(KERN_ERR "megasas: Failed to copy out to user "
3744                                         "sense data\n");
3745                         error = -EFAULT;
3746                         goto out;
3747                 }
3748         }
3749
3750         /*
3751          * copy the status codes returned by the fw
3752          */
3753         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
3754                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
3755                 printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
3756                 error = -EFAULT;
3757         }
3758
3759       out:
3760         if (sense) {
3761                 dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
3762                                     sense, sense_handle);
3763         }
3764
3765         for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) {
3766                 dma_free_coherent(&instance->pdev->dev,
3767                                     kern_sge32[i].length,
3768                                     kbuff_arr[i], kern_sge32[i].phys_addr);
3769         }
3770
3771         megasas_return_cmd(instance, cmd);
3772         return error;
3773 }
3774
3775 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
3776 {
3777         struct megasas_iocpacket __user *user_ioc =
3778             (struct megasas_iocpacket __user *)arg;
3779         struct megasas_iocpacket *ioc;
3780         struct megasas_instance *instance;
3781         int error;
3782
3783         ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
3784         if (!ioc)
3785                 return -ENOMEM;
3786
3787         if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
3788                 error = -EFAULT;
3789                 goto out_kfree_ioc;
3790         }
3791
3792         instance = megasas_lookup_instance(ioc->host_no);
3793         if (!instance) {
3794                 error = -ENODEV;
3795                 goto out_kfree_ioc;
3796         }
3797
3798         if (instance->hw_crit_error == 1) {
3799                 printk(KERN_DEBUG "Controller in Crit ERROR\n");
3800                 error = -ENODEV;
3801                 goto out_kfree_ioc;
3802         }
3803
3804         if (instance->unload == 1) {
3805                 error = -ENODEV;
3806                 goto out_kfree_ioc;
3807         }
3808
3809         /*
3810          * We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
3811          */
3812         if (down_interruptible(&instance->ioctl_sem)) {
3813                 error = -ERESTARTSYS;
3814                 goto out_kfree_ioc;
3815         }
3816         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
3817         up(&instance->ioctl_sem);
3818
3819       out_kfree_ioc:
3820         kfree(ioc);
3821         return error;
3822 }
3823
3824 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
3825 {
3826         struct megasas_instance *instance;
3827         struct megasas_aen aen;
3828         int error;
3829
3830         if (file->private_data != file) {
3831                 printk(KERN_DEBUG "megasas: fasync_helper was not "
3832                        "called first\n");
3833                 return -EINVAL;
3834         }
3835
3836         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
3837                 return -EFAULT;
3838
3839         instance = megasas_lookup_instance(aen.host_no);
3840
3841         if (!instance)
3842                 return -ENODEV;
3843
3844         if (instance->hw_crit_error == 1) {
3845                 error = -ENODEV;
3846         }
3847
3848         if (instance->unload == 1) {
3849                 return -ENODEV;
3850         }
3851
3852         mutex_lock(&instance->aen_mutex);
3853         error = megasas_register_aen(instance, aen.seq_num,
3854                                      aen.class_locale_word);
3855         mutex_unlock(&instance->aen_mutex);
3856         return error;
3857 }
3858
3859 /**
3860  * megasas_mgmt_ioctl - char node ioctl entry point
3861  */
3862 static long
3863 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3864 {
3865         switch (cmd) {
3866         case MEGASAS_IOC_FIRMWARE:
3867                 return megasas_mgmt_ioctl_fw(file, arg);
3868
3869         case MEGASAS_IOC_GET_AEN:
3870                 return megasas_mgmt_ioctl_aen(file, arg);
3871         }
3872
3873         return -ENOTTY;
3874 }
3875
3876 #ifdef CONFIG_COMPAT
3877 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
3878 {
3879         struct compat_megasas_iocpacket __user *cioc =
3880             (struct compat_megasas_iocpacket __user *)arg;
3881         struct megasas_iocpacket __user *ioc =
3882             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
3883         int i;
3884         int error = 0;
3885         compat_uptr_t ptr;
3886
3887         if (clear_user(ioc, sizeof(*ioc)))
3888                 return -EFAULT;
3889
3890         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
3891             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
3892             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
3893             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
3894             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
3895             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
3896                 return -EFAULT;
3897
3898         /*
3899          * The sense_ptr is used in megasas_mgmt_fw_ioctl only when
3900          * sense_len is not null, so prepare the 64bit value under
3901          * the same condition.
3902          */
3903         if (ioc->sense_len) {
3904                 void __user **sense_ioc_ptr =
3905                         (void __user **)(ioc->frame.raw + ioc->sense_off);
3906                 compat_uptr_t *sense_cioc_ptr =
3907                         (compat_uptr_t *)(cioc->frame.raw + cioc->sense_off);
3908                 if (get_user(ptr, sense_cioc_ptr) ||
3909                     put_user(compat_ptr(ptr), sense_ioc_ptr))
3910                         return -EFAULT;
3911         }
3912
3913         for (i = 0; i < MAX_IOCTL_SGE; i++) {
3914                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
3915                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
3916                     copy_in_user(&ioc->sgl[i].iov_len,
3917                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
3918                         return -EFAULT;
3919         }
3920
3921         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
3922
3923         if (copy_in_user(&cioc->frame.hdr.cmd_status,
3924                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
3925                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
3926                 return -EFAULT;
3927         }
3928         return error;
3929 }
3930
3931 static long
3932 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
3933                           unsigned long arg)
3934 {
3935         switch (cmd) {
3936         case MEGASAS_IOC_FIRMWARE32:
3937                 return megasas_mgmt_compat_ioctl_fw(file, arg);
3938         case MEGASAS_IOC_GET_AEN:
3939                 return megasas_mgmt_ioctl_aen(file, arg);
3940         }
3941
3942         return -ENOTTY;
3943 }
3944 #endif
3945
3946 /*
3947  * File operations structure for management interface
3948  */
3949 static const struct file_operations megasas_mgmt_fops = {
3950         .owner = THIS_MODULE,
3951         .open = megasas_mgmt_open,
3952         .fasync = megasas_mgmt_fasync,
3953         .unlocked_ioctl = megasas_mgmt_ioctl,
3954         .poll = megasas_mgmt_poll,
3955 #ifdef CONFIG_COMPAT
3956         .compat_ioctl = megasas_mgmt_compat_ioctl,
3957 #endif
3958         .llseek = noop_llseek,
3959 };
3960
3961 /*
3962  * PCI hotplug support registration structure
3963  */
3964 static struct pci_driver megasas_pci_driver = {
3965
3966         .name = "megaraid_sas",
3967         .id_table = megasas_pci_table,
3968         .probe = megasas_probe_one,
3969         .remove = __devexit_p(megasas_detach_one),
3970         .suspend = megasas_suspend,
3971         .resume = megasas_resume,
3972         .shutdown = megasas_shutdown,
3973 };
3974
3975 /*
3976  * Sysfs driver attributes
3977  */
3978 static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
3979 {
3980         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
3981                         MEGASAS_VERSION);
3982 }
3983
3984 static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
3985
3986 static ssize_t
3987 megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
3988 {
3989         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
3990                         MEGASAS_RELDATE);
3991 }
3992
3993 static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
3994                    NULL);
3995
3996 static ssize_t
3997 megasas_sysfs_show_support_poll_for_event(struct device_driver *dd, char *buf)
3998 {
3999         return sprintf(buf, "%u\n", support_poll_for_event);
4000 }
4001
4002 static DRIVER_ATTR(support_poll_for_event, S_IRUGO,
4003                         megasas_sysfs_show_support_poll_for_event, NULL);
4004
4005 static ssize_t
4006 megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
4007 {
4008         return sprintf(buf, "%u\n", megasas_dbg_lvl);
4009 }
4010
4011 static ssize_t
4012 megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
4013 {
4014         int retval = count;
4015         if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
4016                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
4017                 retval = -EINVAL;
4018         }
4019         return retval;
4020 }
4021
4022 static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUSR, megasas_sysfs_show_dbg_lvl,
4023                 megasas_sysfs_set_dbg_lvl);
4024
4025 static ssize_t
4026 megasas_sysfs_show_poll_mode_io(struct device_driver *dd, char *buf)
4027 {
4028         return sprintf(buf, "%u\n", poll_mode_io);
4029 }
4030
4031 static ssize_t
4032 megasas_sysfs_set_poll_mode_io(struct device_driver *dd,
4033                                 const char *buf, size_t count)
4034 {
4035         int retval = count;
4036         int tmp = poll_mode_io;
4037         int i;
4038         struct megasas_instance *instance;
4039
4040         if (sscanf(buf, "%u", &poll_mode_io) < 1) {
4041                 printk(KERN_ERR "megasas: could not set poll_mode_io\n");
4042                 retval = -EINVAL;
4043         }
4044
4045         /*
4046          * Check if poll_mode_io is already set or is same as previous value
4047          */
4048         if ((tmp && poll_mode_io) || (tmp == poll_mode_io))
4049                 goto out;
4050
4051         if (poll_mode_io) {
4052                 /*
4053                  * Start timers for all adapters
4054                  */
4055                 for (i = 0; i < megasas_mgmt_info.max_index; i++) {
4056                         instance = megasas_mgmt_info.instance[i];
4057                         if (instance) {
4058                                 megasas_start_timer(instance,
4059                                         &instance->io_completion_timer,
4060                                         megasas_io_completion_timer,
4061                                         MEGASAS_COMPLETION_TIMER_INTERVAL);
4062                         }
4063                 }
4064         } else {
4065                 /*
4066                  * Delete timers for all adapters
4067                  */
4068                 for (i = 0; i < megasas_mgmt_info.max_index; i++) {
4069                         instance = megasas_mgmt_info.instance[i];
4070                         if (instance)
4071                                 del_timer_sync(&instance->io_completion_timer);
4072                 }
4073         }
4074
4075 out:
4076         return retval;
4077 }
4078
4079 static void
4080 megasas_aen_polling(struct work_struct *work)
4081 {
4082         struct megasas_aen_event *ev =
4083                 container_of(work, struct megasas_aen_event, hotplug_work);
4084         struct megasas_instance *instance = ev->instance;
4085         union megasas_evt_class_locale class_locale;
4086         struct  Scsi_Host *host;
4087         struct  scsi_device *sdev1;
4088         u16     pd_index = 0;
4089         u16     ld_index = 0;
4090         int     i, j, doscan = 0;
4091         u32 seq_num;
4092         int error;
4093
4094         if (!instance) {
4095                 printk(KERN_ERR "invalid instance!\n");
4096                 kfree(ev);
4097                 return;
4098         }
4099         instance->ev = NULL;
4100         host = instance->host;
4101         if (instance->evt_detail) {
4102
4103                 switch (instance->evt_detail->code) {
4104                 case MR_EVT_PD_INSERTED:
4105                         if (megasas_get_pd_list(instance) == 0) {
4106                         for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
4107                                 for (j = 0;
4108                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
4109                                 j++) {
4110
4111                                 pd_index =
4112                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
4113
4114                                 sdev1 =
4115                                 scsi_device_lookup(host, i, j, 0);
4116
4117                                 if (instance->pd_list[pd_index].driveState
4118                                                 == MR_PD_STATE_SYSTEM) {
4119                                                 if (!sdev1) {
4120                                                 scsi_add_device(host, i, j, 0);
4121                                                 }
4122
4123                                         if (sdev1)
4124                                                 scsi_device_put(sdev1);
4125                                         }
4126                                 }
4127                         }
4128                         }
4129                         doscan = 0;
4130                         break;
4131
4132                 case MR_EVT_PD_REMOVED:
4133                         if (megasas_get_pd_list(instance) == 0) {
4134                         megasas_get_pd_list(instance);
4135                         for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
4136                                 for (j = 0;
4137                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
4138                                 j++) {
4139
4140                                 pd_index =
4141                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
4142
4143                                 sdev1 =
4144                                 scsi_device_lookup(host, i, j, 0);
4145
4146                                 if (instance->pd_list[pd_index].driveState
4147                                         == MR_PD_STATE_SYSTEM) {
4148                                         if (sdev1) {
4149                                                 scsi_device_put(sdev1);
4150                                         }
4151                                 } else {
4152                                         if (sdev1) {
4153                                                 scsi_remove_device(sdev1);
4154                                                 scsi_device_put(sdev1);
4155                                         }
4156                                 }
4157                                 }
4158                         }
4159                         }
4160                         doscan = 0;
4161                         break;
4162
4163                 case MR_EVT_LD_OFFLINE:
4164                 case MR_EVT_LD_DELETED:
4165                         megasas_get_ld_list(instance);
4166                         for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
4167                                 for (j = 0;
4168                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
4169                                 j++) {
4170
4171                                 ld_index =
4172                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
4173
4174                                 sdev1 = scsi_device_lookup(host,
4175                                         i + MEGASAS_MAX_LD_CHANNELS,
4176                                         j,
4177                                         0);
4178
4179                                 if (instance->ld_ids[ld_index] != 0xff) {
4180                                         if (sdev1) {
4181                                                 scsi_device_put(sdev1);
4182                                         }
4183                                 } else {
4184                                         if (sdev1) {
4185                                                 scsi_remove_device(sdev1);
4186                                                 scsi_device_put(sdev1);
4187                                         }
4188                                 }
4189                                 }
4190                         }
4191                         doscan = 0;
4192                         break;
4193                 case MR_EVT_LD_CREATED:
4194                         megasas_get_ld_list(instance);
4195                         for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
4196                                 for (j = 0;
4197                                         j < MEGASAS_MAX_DEV_PER_CHANNEL;
4198                                         j++) {
4199                                         ld_index =
4200                                         (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
4201
4202                                         sdev1 = scsi_device_lookup(host,
4203                                                 i+MEGASAS_MAX_LD_CHANNELS,
4204                                                 j, 0);
4205
4206                                         if (instance->ld_ids[ld_index] !=
4207                                                                 0xff) {
4208                                                 if (!sdev1) {
4209                                                         scsi_add_device(host,
4210                                                                 i + 2,
4211                                                                 j, 0);
4212                                                 }
4213                                         }
4214                                         if (sdev1) {
4215                                                 scsi_device_put(sdev1);
4216                                         }
4217                                 }
4218                         }
4219                         doscan = 0;
4220                         break;
4221                 case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
4222                 case MR_EVT_FOREIGN_CFG_IMPORTED:
4223                         doscan = 1;
4224                         break;
4225                 default:
4226                         doscan = 0;
4227                         break;
4228                 }
4229         } else {
4230                 printk(KERN_ERR "invalid evt_detail!\n");
4231                 kfree(ev);
4232                 return;
4233         }
4234
4235         if (doscan) {
4236                 printk(KERN_INFO "scanning ...\n");
4237                 megasas_get_pd_list(instance);
4238                 for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
4239                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
4240                                 pd_index = i*MEGASAS_MAX_DEV_PER_CHANNEL + j;
4241                                 sdev1 = scsi_device_lookup(host, i, j, 0);
4242                                 if (instance->pd_list[pd_index].driveState ==
4243                                                         MR_PD_STATE_SYSTEM) {
4244                                         if (!sdev1) {
4245                                                 scsi_add_device(host, i, j, 0);
4246                                         }
4247                                         if (sdev1)
4248                                                 scsi_device_put(sdev1);
4249                                 } else {
4250                                         if (sdev1) {
4251                                                 scsi_remove_device(sdev1);
4252                                                 scsi_device_put(sdev1);
4253                                         }
4254                                 }
4255                         }
4256                 }
4257
4258                 megasas_get_ld_list(instance);
4259                 for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
4260                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
4261                                 ld_index =
4262                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
4263
4264                                 sdev1 = scsi_device_lookup(host,
4265                                         i+MEGASAS_MAX_LD_CHANNELS, j, 0);
4266                                 if (instance->ld_ids[ld_index] != 0xff) {
4267                                         if (!sdev1) {
4268                                                 scsi_add_device(host,
4269                                                                 i+2,
4270                                                                 j, 0);
4271                                         } else {
4272                                                 scsi_device_put(sdev1);
4273                                         }
4274                                 } else {
4275                                         if (sdev1) {
4276                                                 scsi_remove_device(sdev1);
4277                                                 scsi_device_put(sdev1);
4278                                         }
4279                                 }
4280                         }
4281                 }
4282         }
4283
4284         if ( instance->aen_cmd != NULL ) {
4285                 kfree(ev);
4286                 return ;
4287         }
4288
4289         seq_num = instance->evt_detail->seq_num + 1;
4290
4291         /* Register AEN with FW for latest sequence number plus 1 */
4292         class_locale.members.reserved = 0;
4293         class_locale.members.locale = MR_EVT_LOCALE_ALL;
4294         class_locale.members.class = MR_EVT_CLASS_DEBUG;
4295         mutex_lock(&instance->aen_mutex);
4296         error = megasas_register_aen(instance, seq_num,
4297                                         class_locale.word);
4298         mutex_unlock(&instance->aen_mutex);
4299
4300         if (error)
4301                 printk(KERN_ERR "register aen failed error %x\n", error);
4302
4303         kfree(ev);
4304 }
4305
4306
4307 static DRIVER_ATTR(poll_mode_io, S_IRUGO|S_IWUSR,
4308                 megasas_sysfs_show_poll_mode_io,
4309                 megasas_sysfs_set_poll_mode_io);
4310
4311 /**
4312  * megasas_init - Driver load entry point
4313  */
4314 static int __init megasas_init(void)
4315 {
4316         int rval;
4317
4318         /*
4319          * Announce driver version and other information
4320          */
4321         printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
4322                MEGASAS_EXT_VERSION);
4323
4324         support_poll_for_event = 2;
4325
4326         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
4327
4328         /*
4329          * Register character device node
4330          */
4331         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
4332
4333         if (rval < 0) {
4334                 printk(KERN_DEBUG "megasas: failed to open device node\n");
4335                 return rval;
4336         }
4337
4338         megasas_mgmt_majorno = rval;
4339
4340         /*
4341          * Register ourselves as PCI hotplug module
4342          */
4343         rval = pci_register_driver(&megasas_pci_driver);
4344
4345         if (rval) {
4346                 printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
4347                 goto err_pcidrv;
4348         }
4349
4350         rval = driver_create_file(&megasas_pci_driver.driver,
4351                                   &driver_attr_version);
4352         if (rval)
4353                 goto err_dcf_attr_ver;
4354         rval = driver_create_file(&megasas_pci_driver.driver,
4355                                   &driver_attr_release_date);
4356         if (rval)
4357                 goto err_dcf_rel_date;
4358
4359         rval = driver_create_file(&megasas_pci_driver.driver,
4360                                 &driver_attr_support_poll_for_event);
4361         if (rval)
4362                 goto err_dcf_support_poll_for_event;
4363
4364         rval = driver_create_file(&megasas_pci_driver.driver,
4365                                   &driver_attr_dbg_lvl);
4366         if (rval)
4367                 goto err_dcf_dbg_lvl;
4368         rval = driver_create_file(&megasas_pci_driver.driver,
4369                                   &driver_attr_poll_mode_io);
4370         if (rval)
4371                 goto err_dcf_poll_mode_io;
4372
4373         return rval;
4374
4375 err_dcf_poll_mode_io:
4376         driver_remove_file(&megasas_pci_driver.driver,
4377                            &driver_attr_dbg_lvl);
4378 err_dcf_dbg_lvl:
4379         driver_remove_file(&megasas_pci_driver.driver,
4380                         &driver_attr_support_poll_for_event);
4381
4382 err_dcf_support_poll_for_event:
4383         driver_remove_file(&megasas_pci_driver.driver,
4384                            &driver_attr_release_date);
4385
4386 err_dcf_rel_date:
4387         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
4388 err_dcf_attr_ver:
4389         pci_unregister_driver(&megasas_pci_driver);
4390 err_pcidrv:
4391         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
4392         return rval;
4393 }
4394
4395 /**
4396  * megasas_exit - Driver unload entry point
4397  */
4398 static void __exit megasas_exit(void)
4399 {
4400         driver_remove_file(&megasas_pci_driver.driver,
4401                            &driver_attr_poll_mode_io);
4402         driver_remove_file(&megasas_pci_driver.driver,
4403                            &driver_attr_dbg_lvl);
4404         driver_remove_file(&megasas_pci_driver.driver,
4405                            &driver_attr_release_date);
4406         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
4407
4408         pci_unregister_driver(&megasas_pci_driver);
4409         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
4410 }
4411
4412 module_init(megasas_init);
4413 module_exit(megasas_exit);