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