]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/scsi/megaraid/megaraid_sas_base.c
1bc0c5af4f91b23d6859bb4e61cfa36ff98f1dfa
[karo-tx-linux.git] / drivers / scsi / megaraid / megaraid_sas_base.c
1 /*
2  *  Linux MegaRAID driver for SAS based RAID controllers
3  *
4  *  Copyright (c) 2003-2013  LSI Corporation
5  *  Copyright (c) 2013-2014  Avago Technologies
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 2
10  *  of the License, or (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  *  Authors: Avago Technologies
21  *           Sreenivas Bagalkote
22  *           Sumant Patro
23  *           Bo Yang
24  *           Adam Radford
25  *           Kashyap Desai <kashyap.desai@avagotech.com>
26  *           Sumit Saxena <sumit.saxena@avagotech.com>
27  *
28  *  Send feedback to: megaraidlinux.pdl@avagotech.com
29  *
30  *  Mail to: Avago Technologies, 350 West Trimble Road, Building 90,
31  *  San Jose, California 95131
32  */
33
34 #include <linux/kernel.h>
35 #include <linux/types.h>
36 #include <linux/pci.h>
37 #include <linux/list.h>
38 #include <linux/moduleparam.h>
39 #include <linux/module.h>
40 #include <linux/spinlock.h>
41 #include <linux/interrupt.h>
42 #include <linux/delay.h>
43 #include <linux/uio.h>
44 #include <linux/slab.h>
45 #include <asm/uaccess.h>
46 #include <linux/fs.h>
47 #include <linux/compat.h>
48 #include <linux/blkdev.h>
49 #include <linux/mutex.h>
50 #include <linux/poll.h>
51
52 #include <scsi/scsi.h>
53 #include <scsi/scsi_cmnd.h>
54 #include <scsi/scsi_device.h>
55 #include <scsi/scsi_host.h>
56 #include <scsi/scsi_tcq.h>
57 #include "megaraid_sas_fusion.h"
58 #include "megaraid_sas.h"
59
60 /*
61  * Number of sectors per IO command
62  * Will be set in megasas_init_mfi if user does not provide
63  */
64 static unsigned int max_sectors;
65 module_param_named(max_sectors, max_sectors, int, 0);
66 MODULE_PARM_DESC(max_sectors,
67         "Maximum number of sectors per IO command");
68
69 static int msix_disable;
70 module_param(msix_disable, int, S_IRUGO);
71 MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0");
72
73 static unsigned int msix_vectors;
74 module_param(msix_vectors, int, S_IRUGO);
75 MODULE_PARM_DESC(msix_vectors, "MSI-X max vector count. Default: Set by FW");
76
77 static int allow_vf_ioctls;
78 module_param(allow_vf_ioctls, int, S_IRUGO);
79 MODULE_PARM_DESC(allow_vf_ioctls, "Allow ioctls in SR-IOV VF mode. Default: 0");
80
81 static unsigned int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH;
82 module_param(throttlequeuedepth, int, S_IRUGO);
83 MODULE_PARM_DESC(throttlequeuedepth,
84         "Adapter queue depth when throttled due to I/O timeout. Default: 16");
85
86 int resetwaittime = MEGASAS_RESET_WAIT_TIME;
87 module_param(resetwaittime, int, S_IRUGO);
88 MODULE_PARM_DESC(resetwaittime, "Wait time in seconds after I/O timeout "
89                  "before resetting adapter. Default: 180");
90
91 int smp_affinity_enable = 1;
92 module_param(smp_affinity_enable, int, S_IRUGO);
93 MODULE_PARM_DESC(smp_affinity_enable, "SMP affinity feature enable/disbale Default: enable(1)");
94
95 MODULE_LICENSE("GPL");
96 MODULE_VERSION(MEGASAS_VERSION);
97 MODULE_AUTHOR("megaraidlinux.pdl@avagotech.com");
98 MODULE_DESCRIPTION("Avago MegaRAID SAS Driver");
99
100 int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
101 static int megasas_get_pd_list(struct megasas_instance *instance);
102 static int megasas_ld_list_query(struct megasas_instance *instance,
103                                  u8 query_type);
104 static int megasas_issue_init_mfi(struct megasas_instance *instance);
105 static int megasas_register_aen(struct megasas_instance *instance,
106                                 u32 seq_num, u32 class_locale_word);
107 /*
108  * PCI ID table for all supported controllers
109  */
110 static struct pci_device_id megasas_pci_table[] = {
111
112         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
113         /* xscale IOP */
114         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
115         /* ppc IOP */
116         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
117         /* ppc IOP */
118         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
119         /* gen2*/
120         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
121         /* gen2*/
122         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)},
123         /* skinny*/
124         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)},
125         /* skinny*/
126         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
127         /* xscale IOP, vega */
128         {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
129         /* xscale IOP */
130         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)},
131         /* Fusion */
132         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_PLASMA)},
133         /* Plasma */
134         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)},
135         /* Invader */
136         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FURY)},
137         /* Fury */
138         {}
139 };
140
141 MODULE_DEVICE_TABLE(pci, megasas_pci_table);
142
143 static int megasas_mgmt_majorno;
144 struct megasas_mgmt_info megasas_mgmt_info;
145 static struct fasync_struct *megasas_async_queue;
146 static DEFINE_MUTEX(megasas_async_queue_mutex);
147
148 static int megasas_poll_wait_aen;
149 static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait);
150 static u32 support_poll_for_event;
151 u32 megasas_dbg_lvl;
152 static u32 support_device_change;
153
154 /* define lock for aen poll */
155 spinlock_t poll_aen_lock;
156
157 void
158 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
159                      u8 alt_status);
160 static u32
161 megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs);
162 static int
163 megasas_adp_reset_gen2(struct megasas_instance *instance,
164                        struct megasas_register_set __iomem *reg_set);
165 static irqreturn_t megasas_isr(int irq, void *devp);
166 static u32
167 megasas_init_adapter_mfi(struct megasas_instance *instance);
168 u32
169 megasas_build_and_issue_cmd(struct megasas_instance *instance,
170                             struct scsi_cmnd *scmd);
171 static void megasas_complete_cmd_dpc(unsigned long instance_addr);
172 void
173 megasas_release_fusion(struct megasas_instance *instance);
174 int
175 megasas_ioc_init_fusion(struct megasas_instance *instance);
176 void
177 megasas_free_cmds_fusion(struct megasas_instance *instance);
178 u8
179 megasas_get_map_info(struct megasas_instance *instance);
180 int
181 megasas_sync_map_info(struct megasas_instance *instance);
182 int
183 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
184         int seconds);
185 void megasas_reset_reply_desc(struct megasas_instance *instance);
186 int megasas_reset_fusion(struct Scsi_Host *shost, int iotimeout);
187 void megasas_fusion_ocr_wq(struct work_struct *work);
188 static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
189                                          int initial);
190 int megasas_check_mpio_paths(struct megasas_instance *instance,
191                              struct scsi_cmnd *scmd);
192
193 void
194 megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
195 {
196         instance->instancet->fire_cmd(instance,
197                 cmd->frame_phys_addr, 0, instance->reg_set);
198 }
199
200 /**
201  * megasas_get_cmd -    Get a command from the free pool
202  * @instance:           Adapter soft state
203  *
204  * Returns a free command from the pool
205  */
206 struct megasas_cmd *megasas_get_cmd(struct megasas_instance
207                                                   *instance)
208 {
209         unsigned long flags;
210         struct megasas_cmd *cmd = NULL;
211
212         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
213
214         if (!list_empty(&instance->cmd_pool)) {
215                 cmd = list_entry((&instance->cmd_pool)->next,
216                                  struct megasas_cmd, list);
217                 list_del_init(&cmd->list);
218         } else {
219                 printk(KERN_ERR "megasas: Command pool empty!\n");
220         }
221
222         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
223         return cmd;
224 }
225
226 /**
227  * megasas_return_cmd - Return a cmd to free command pool
228  * @instance:           Adapter soft state
229  * @cmd:                Command packet to be returned to free command pool
230  */
231 inline void
232 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
233 {
234         unsigned long flags;
235         u32 blk_tags;
236         struct megasas_cmd_fusion *cmd_fusion;
237         struct fusion_context *fusion = instance->ctrl_context;
238
239         /* This flag is used only for fusion adapter.
240          * Wait for Interrupt for Polled mode DCMD
241          */
242         if (cmd->flags & DRV_DCMD_POLLED_MODE)
243                 return;
244
245         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
246
247         if (fusion) {
248                 blk_tags = instance->max_scsi_cmds + cmd->index;
249                 cmd_fusion = fusion->cmd_list[blk_tags];
250                 megasas_return_cmd_fusion(instance, cmd_fusion);
251         }
252         cmd->scmd = NULL;
253         cmd->frame_count = 0;
254         cmd->flags = 0;
255         if (!fusion && reset_devices)
256                 cmd->frame->hdr.cmd = MFI_CMD_INVALID;
257         list_add(&cmd->list, (&instance->cmd_pool)->next);
258
259         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
260
261 }
262
263 /**
264 *       The following functions are defined for xscale
265 *       (deviceid : 1064R, PERC5) controllers
266 */
267
268 /**
269  * megasas_enable_intr_xscale - Enables interrupts
270  * @regs:                       MFI register set
271  */
272 static inline void
273 megasas_enable_intr_xscale(struct megasas_instance *instance)
274 {
275         struct megasas_register_set __iomem *regs;
276         regs = instance->reg_set;
277         writel(0, &(regs)->outbound_intr_mask);
278
279         /* Dummy readl to force pci flush */
280         readl(&regs->outbound_intr_mask);
281 }
282
283 /**
284  * megasas_disable_intr_xscale -Disables interrupt
285  * @regs:                       MFI register set
286  */
287 static inline void
288 megasas_disable_intr_xscale(struct megasas_instance *instance)
289 {
290         struct megasas_register_set __iomem *regs;
291         u32 mask = 0x1f;
292         regs = instance->reg_set;
293         writel(mask, &regs->outbound_intr_mask);
294         /* Dummy readl to force pci flush */
295         readl(&regs->outbound_intr_mask);
296 }
297
298 /**
299  * megasas_read_fw_status_reg_xscale - returns the current FW status value
300  * @regs:                       MFI register set
301  */
302 static u32
303 megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs)
304 {
305         return readl(&(regs)->outbound_msg_0);
306 }
307 /**
308  * megasas_clear_interrupt_xscale -     Check & clear interrupt
309  * @regs:                               MFI register set
310  */
311 static int
312 megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs)
313 {
314         u32 status;
315         u32 mfiStatus = 0;
316         /*
317          * Check if it is our interrupt
318          */
319         status = readl(&regs->outbound_intr_status);
320
321         if (status & MFI_OB_INTR_STATUS_MASK)
322                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
323         if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT)
324                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
325
326         /*
327          * Clear the interrupt by writing back the same value
328          */
329         if (mfiStatus)
330                 writel(status, &regs->outbound_intr_status);
331
332         /* Dummy readl to force pci flush */
333         readl(&regs->outbound_intr_status);
334
335         return mfiStatus;
336 }
337
338 /**
339  * megasas_fire_cmd_xscale -    Sends command to the FW
340  * @frame_phys_addr :           Physical address of cmd
341  * @frame_count :               Number of frames for the command
342  * @regs :                      MFI register set
343  */
344 static inline void
345 megasas_fire_cmd_xscale(struct megasas_instance *instance,
346                 dma_addr_t frame_phys_addr,
347                 u32 frame_count,
348                 struct megasas_register_set __iomem *regs)
349 {
350         unsigned long flags;
351         spin_lock_irqsave(&instance->hba_lock, flags);
352         writel((frame_phys_addr >> 3)|(frame_count),
353                &(regs)->inbound_queue_port);
354         spin_unlock_irqrestore(&instance->hba_lock, flags);
355 }
356
357 /**
358  * megasas_adp_reset_xscale -  For controller reset
359  * @regs:                              MFI register set
360  */
361 static int
362 megasas_adp_reset_xscale(struct megasas_instance *instance,
363         struct megasas_register_set __iomem *regs)
364 {
365         u32 i;
366         u32 pcidata;
367         writel(MFI_ADP_RESET, &regs->inbound_doorbell);
368
369         for (i = 0; i < 3; i++)
370                 msleep(1000); /* sleep for 3 secs */
371         pcidata  = 0;
372         pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata);
373         printk(KERN_NOTICE "pcidata = %x\n", pcidata);
374         if (pcidata & 0x2) {
375                 printk(KERN_NOTICE "mfi 1068 offset read=%x\n", pcidata);
376                 pcidata &= ~0x2;
377                 pci_write_config_dword(instance->pdev,
378                                 MFI_1068_PCSR_OFFSET, pcidata);
379
380                 for (i = 0; i < 2; i++)
381                         msleep(1000); /* need to wait 2 secs again */
382
383                 pcidata  = 0;
384                 pci_read_config_dword(instance->pdev,
385                                 MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata);
386                 printk(KERN_NOTICE "1068 offset handshake read=%x\n", pcidata);
387                 if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) {
388                         printk(KERN_NOTICE "1068 offset pcidt=%x\n", pcidata);
389                         pcidata = 0;
390                         pci_write_config_dword(instance->pdev,
391                                 MFI_1068_FW_HANDSHAKE_OFFSET, pcidata);
392                 }
393         }
394         return 0;
395 }
396
397 /**
398  * megasas_check_reset_xscale - For controller reset check
399  * @regs:                               MFI register set
400  */
401 static int
402 megasas_check_reset_xscale(struct megasas_instance *instance,
403                 struct megasas_register_set __iomem *regs)
404 {
405
406         if ((instance->adprecovery != MEGASAS_HBA_OPERATIONAL) &&
407             (le32_to_cpu(*instance->consumer) ==
408                 MEGASAS_ADPRESET_INPROG_SIGN))
409                 return 1;
410         return 0;
411 }
412
413 static struct megasas_instance_template megasas_instance_template_xscale = {
414
415         .fire_cmd = megasas_fire_cmd_xscale,
416         .enable_intr = megasas_enable_intr_xscale,
417         .disable_intr = megasas_disable_intr_xscale,
418         .clear_intr = megasas_clear_intr_xscale,
419         .read_fw_status_reg = megasas_read_fw_status_reg_xscale,
420         .adp_reset = megasas_adp_reset_xscale,
421         .check_reset = megasas_check_reset_xscale,
422         .service_isr = megasas_isr,
423         .tasklet = megasas_complete_cmd_dpc,
424         .init_adapter = megasas_init_adapter_mfi,
425         .build_and_issue_cmd = megasas_build_and_issue_cmd,
426         .issue_dcmd = megasas_issue_dcmd,
427 };
428
429 /**
430 *       This is the end of set of functions & definitions specific
431 *       to xscale (deviceid : 1064R, PERC5) controllers
432 */
433
434 /**
435 *       The following functions are defined for ppc (deviceid : 0x60)
436 *       controllers
437 */
438
439 /**
440  * megasas_enable_intr_ppc -    Enables interrupts
441  * @regs:                       MFI register set
442  */
443 static inline void
444 megasas_enable_intr_ppc(struct megasas_instance *instance)
445 {
446         struct megasas_register_set __iomem *regs;
447         regs = instance->reg_set;
448         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
449
450         writel(~0x80000000, &(regs)->outbound_intr_mask);
451
452         /* Dummy readl to force pci flush */
453         readl(&regs->outbound_intr_mask);
454 }
455
456 /**
457  * megasas_disable_intr_ppc -   Disable interrupt
458  * @regs:                       MFI register set
459  */
460 static inline void
461 megasas_disable_intr_ppc(struct megasas_instance *instance)
462 {
463         struct megasas_register_set __iomem *regs;
464         u32 mask = 0xFFFFFFFF;
465         regs = instance->reg_set;
466         writel(mask, &regs->outbound_intr_mask);
467         /* Dummy readl to force pci flush */
468         readl(&regs->outbound_intr_mask);
469 }
470
471 /**
472  * megasas_read_fw_status_reg_ppc - returns the current FW status value
473  * @regs:                       MFI register set
474  */
475 static u32
476 megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs)
477 {
478         return readl(&(regs)->outbound_scratch_pad);
479 }
480
481 /**
482  * megasas_clear_interrupt_ppc -        Check & clear interrupt
483  * @regs:                               MFI register set
484  */
485 static int
486 megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs)
487 {
488         u32 status, mfiStatus = 0;
489
490         /*
491          * Check if it is our interrupt
492          */
493         status = readl(&regs->outbound_intr_status);
494
495         if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT)
496                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
497
498         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT)
499                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
500
501         /*
502          * Clear the interrupt by writing back the same value
503          */
504         writel(status, &regs->outbound_doorbell_clear);
505
506         /* Dummy readl to force pci flush */
507         readl(&regs->outbound_doorbell_clear);
508
509         return mfiStatus;
510 }
511
512 /**
513  * megasas_fire_cmd_ppc -       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_ppc(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((frame_phys_addr | (frame_count<<1))|1,
527                         &(regs)->inbound_queue_port);
528         spin_unlock_irqrestore(&instance->hba_lock, flags);
529 }
530
531 /**
532  * megasas_check_reset_ppc -    For controller reset check
533  * @regs:                               MFI register set
534  */
535 static int
536 megasas_check_reset_ppc(struct megasas_instance *instance,
537                         struct megasas_register_set __iomem *regs)
538 {
539         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
540                 return 1;
541
542         return 0;
543 }
544
545 static struct megasas_instance_template megasas_instance_template_ppc = {
546
547         .fire_cmd = megasas_fire_cmd_ppc,
548         .enable_intr = megasas_enable_intr_ppc,
549         .disable_intr = megasas_disable_intr_ppc,
550         .clear_intr = megasas_clear_intr_ppc,
551         .read_fw_status_reg = megasas_read_fw_status_reg_ppc,
552         .adp_reset = megasas_adp_reset_xscale,
553         .check_reset = megasas_check_reset_ppc,
554         .service_isr = megasas_isr,
555         .tasklet = megasas_complete_cmd_dpc,
556         .init_adapter = megasas_init_adapter_mfi,
557         .build_and_issue_cmd = megasas_build_and_issue_cmd,
558         .issue_dcmd = megasas_issue_dcmd,
559 };
560
561 /**
562  * megasas_enable_intr_skinny - Enables interrupts
563  * @regs:                       MFI register set
564  */
565 static inline void
566 megasas_enable_intr_skinny(struct megasas_instance *instance)
567 {
568         struct megasas_register_set __iomem *regs;
569         regs = instance->reg_set;
570         writel(0xFFFFFFFF, &(regs)->outbound_intr_mask);
571
572         writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
573
574         /* Dummy readl to force pci flush */
575         readl(&regs->outbound_intr_mask);
576 }
577
578 /**
579  * megasas_disable_intr_skinny -        Disables interrupt
580  * @regs:                       MFI register set
581  */
582 static inline void
583 megasas_disable_intr_skinny(struct megasas_instance *instance)
584 {
585         struct megasas_register_set __iomem *regs;
586         u32 mask = 0xFFFFFFFF;
587         regs = instance->reg_set;
588         writel(mask, &regs->outbound_intr_mask);
589         /* Dummy readl to force pci flush */
590         readl(&regs->outbound_intr_mask);
591 }
592
593 /**
594  * megasas_read_fw_status_reg_skinny - returns the current FW status value
595  * @regs:                       MFI register set
596  */
597 static u32
598 megasas_read_fw_status_reg_skinny(struct megasas_register_set __iomem *regs)
599 {
600         return readl(&(regs)->outbound_scratch_pad);
601 }
602
603 /**
604  * megasas_clear_interrupt_skinny -     Check & clear interrupt
605  * @regs:                               MFI register set
606  */
607 static int
608 megasas_clear_intr_skinny(struct megasas_register_set __iomem *regs)
609 {
610         u32 status;
611         u32 mfiStatus = 0;
612
613         /*
614          * Check if it is our interrupt
615          */
616         status = readl(&regs->outbound_intr_status);
617
618         if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) {
619                 return 0;
620         }
621
622         /*
623          * Check if it is our interrupt
624          */
625         if ((megasas_read_fw_status_reg_skinny(regs) & MFI_STATE_MASK) ==
626             MFI_STATE_FAULT) {
627                 mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
628         } else
629                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
630
631         /*
632          * Clear the interrupt by writing back the same value
633          */
634         writel(status, &regs->outbound_intr_status);
635
636         /*
637         * dummy read to flush PCI
638         */
639         readl(&regs->outbound_intr_status);
640
641         return mfiStatus;
642 }
643
644 /**
645  * megasas_fire_cmd_skinny -    Sends command to the FW
646  * @frame_phys_addr :           Physical address of cmd
647  * @frame_count :               Number of frames for the command
648  * @regs :                      MFI register set
649  */
650 static inline void
651 megasas_fire_cmd_skinny(struct megasas_instance *instance,
652                         dma_addr_t frame_phys_addr,
653                         u32 frame_count,
654                         struct megasas_register_set __iomem *regs)
655 {
656         unsigned long flags;
657         spin_lock_irqsave(&instance->hba_lock, flags);
658         writel(upper_32_bits(frame_phys_addr),
659                &(regs)->inbound_high_queue_port);
660         writel((lower_32_bits(frame_phys_addr) | (frame_count<<1))|1,
661                &(regs)->inbound_low_queue_port);
662         spin_unlock_irqrestore(&instance->hba_lock, flags);
663 }
664
665 /**
666  * megasas_check_reset_skinny - For controller reset check
667  * @regs:                               MFI register set
668  */
669 static int
670 megasas_check_reset_skinny(struct megasas_instance *instance,
671                                 struct megasas_register_set __iomem *regs)
672 {
673         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
674                 return 1;
675
676         return 0;
677 }
678
679 static struct megasas_instance_template megasas_instance_template_skinny = {
680
681         .fire_cmd = megasas_fire_cmd_skinny,
682         .enable_intr = megasas_enable_intr_skinny,
683         .disable_intr = megasas_disable_intr_skinny,
684         .clear_intr = megasas_clear_intr_skinny,
685         .read_fw_status_reg = megasas_read_fw_status_reg_skinny,
686         .adp_reset = megasas_adp_reset_gen2,
687         .check_reset = megasas_check_reset_skinny,
688         .service_isr = megasas_isr,
689         .tasklet = megasas_complete_cmd_dpc,
690         .init_adapter = megasas_init_adapter_mfi,
691         .build_and_issue_cmd = megasas_build_and_issue_cmd,
692         .issue_dcmd = megasas_issue_dcmd,
693 };
694
695
696 /**
697 *       The following functions are defined for gen2 (deviceid : 0x78 0x79)
698 *       controllers
699 */
700
701 /**
702  * megasas_enable_intr_gen2 -  Enables interrupts
703  * @regs:                      MFI register set
704  */
705 static inline void
706 megasas_enable_intr_gen2(struct megasas_instance *instance)
707 {
708         struct megasas_register_set __iomem *regs;
709         regs = instance->reg_set;
710         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
711
712         /* write ~0x00000005 (4 & 1) to the intr mask*/
713         writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
714
715         /* Dummy readl to force pci flush */
716         readl(&regs->outbound_intr_mask);
717 }
718
719 /**
720  * megasas_disable_intr_gen2 - Disables interrupt
721  * @regs:                      MFI register set
722  */
723 static inline void
724 megasas_disable_intr_gen2(struct megasas_instance *instance)
725 {
726         struct megasas_register_set __iomem *regs;
727         u32 mask = 0xFFFFFFFF;
728         regs = instance->reg_set;
729         writel(mask, &regs->outbound_intr_mask);
730         /* Dummy readl to force pci flush */
731         readl(&regs->outbound_intr_mask);
732 }
733
734 /**
735  * megasas_read_fw_status_reg_gen2 - returns the current FW status value
736  * @regs:                      MFI register set
737  */
738 static u32
739 megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs)
740 {
741         return readl(&(regs)->outbound_scratch_pad);
742 }
743
744 /**
745  * megasas_clear_interrupt_gen2 -      Check & clear interrupt
746  * @regs:                              MFI register set
747  */
748 static int
749 megasas_clear_intr_gen2(struct megasas_register_set __iomem *regs)
750 {
751         u32 status;
752         u32 mfiStatus = 0;
753         /*
754          * Check if it is our interrupt
755          */
756         status = readl(&regs->outbound_intr_status);
757
758         if (status & MFI_INTR_FLAG_REPLY_MESSAGE) {
759                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
760         }
761         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) {
762                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
763         }
764
765         /*
766          * Clear the interrupt by writing back the same value
767          */
768         if (mfiStatus)
769                 writel(status, &regs->outbound_doorbell_clear);
770
771         /* Dummy readl to force pci flush */
772         readl(&regs->outbound_intr_status);
773
774         return mfiStatus;
775 }
776 /**
777  * megasas_fire_cmd_gen2 -     Sends command to the FW
778  * @frame_phys_addr :          Physical address of cmd
779  * @frame_count :              Number of frames for the command
780  * @regs :                     MFI register set
781  */
782 static inline void
783 megasas_fire_cmd_gen2(struct megasas_instance *instance,
784                         dma_addr_t frame_phys_addr,
785                         u32 frame_count,
786                         struct megasas_register_set __iomem *regs)
787 {
788         unsigned long flags;
789         spin_lock_irqsave(&instance->hba_lock, flags);
790         writel((frame_phys_addr | (frame_count<<1))|1,
791                         &(regs)->inbound_queue_port);
792         spin_unlock_irqrestore(&instance->hba_lock, flags);
793 }
794
795 /**
796  * megasas_adp_reset_gen2 -     For controller reset
797  * @regs:                               MFI register set
798  */
799 static int
800 megasas_adp_reset_gen2(struct megasas_instance *instance,
801                         struct megasas_register_set __iomem *reg_set)
802 {
803         u32                     retry = 0 ;
804         u32                     HostDiag;
805         u32 __iomem             *seq_offset = &reg_set->seq_offset;
806         u32 __iomem             *hostdiag_offset = &reg_set->host_diag;
807
808         if (instance->instancet == &megasas_instance_template_skinny) {
809                 seq_offset = &reg_set->fusion_seq_offset;
810                 hostdiag_offset = &reg_set->fusion_host_diag;
811         }
812
813         writel(0, seq_offset);
814         writel(4, seq_offset);
815         writel(0xb, seq_offset);
816         writel(2, seq_offset);
817         writel(7, seq_offset);
818         writel(0xd, seq_offset);
819
820         msleep(1000);
821
822         HostDiag = (u32)readl(hostdiag_offset);
823
824         while ( !( HostDiag & DIAG_WRITE_ENABLE) ) {
825                 msleep(100);
826                 HostDiag = (u32)readl(hostdiag_offset);
827                 printk(KERN_NOTICE "RESETGEN2: retry=%x, hostdiag=%x\n",
828                                         retry, HostDiag);
829
830                 if (retry++ >= 100)
831                         return 1;
832
833         }
834
835         printk(KERN_NOTICE "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag);
836
837         writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset);
838
839         ssleep(10);
840
841         HostDiag = (u32)readl(hostdiag_offset);
842         while ( ( HostDiag & DIAG_RESET_ADAPTER) ) {
843                 msleep(100);
844                 HostDiag = (u32)readl(hostdiag_offset);
845                 printk(KERN_NOTICE "RESET_GEN2: retry=%x, hostdiag=%x\n",
846                                 retry, HostDiag);
847
848                 if (retry++ >= 1000)
849                         return 1;
850
851         }
852         return 0;
853 }
854
855 /**
856  * megasas_check_reset_gen2 -   For controller reset check
857  * @regs:                               MFI register set
858  */
859 static int
860 megasas_check_reset_gen2(struct megasas_instance *instance,
861                 struct megasas_register_set __iomem *regs)
862 {
863         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
864                 return 1;
865         }
866
867         return 0;
868 }
869
870 static struct megasas_instance_template megasas_instance_template_gen2 = {
871
872         .fire_cmd = megasas_fire_cmd_gen2,
873         .enable_intr = megasas_enable_intr_gen2,
874         .disable_intr = megasas_disable_intr_gen2,
875         .clear_intr = megasas_clear_intr_gen2,
876         .read_fw_status_reg = megasas_read_fw_status_reg_gen2,
877         .adp_reset = megasas_adp_reset_gen2,
878         .check_reset = megasas_check_reset_gen2,
879         .service_isr = megasas_isr,
880         .tasklet = megasas_complete_cmd_dpc,
881         .init_adapter = megasas_init_adapter_mfi,
882         .build_and_issue_cmd = megasas_build_and_issue_cmd,
883         .issue_dcmd = megasas_issue_dcmd,
884 };
885
886 /**
887 *       This is the end of set of functions & definitions
888 *       specific to gen2 (deviceid : 0x78, 0x79) controllers
889 */
890
891 /*
892  * Template added for TB (Fusion)
893  */
894 extern struct megasas_instance_template megasas_instance_template_fusion;
895
896 /**
897  * megasas_issue_polled -       Issues a polling command
898  * @instance:                   Adapter soft state
899  * @cmd:                        Command packet to be issued
900  *
901  * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
902  */
903 int
904 megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
905 {
906         int seconds;
907
908         struct megasas_header *frame_hdr = &cmd->frame->hdr;
909
910         frame_hdr->cmd_status = MFI_CMD_STATUS_POLL_MODE;
911         frame_hdr->flags |= cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE);
912
913         /*
914          * Issue the frame using inbound queue port
915          */
916         instance->instancet->issue_dcmd(instance, cmd);
917
918         /*
919          * Wait for cmd_status to change
920          */
921         if (instance->requestorId)
922                 seconds = MEGASAS_ROUTINE_WAIT_TIME_VF;
923         else
924                 seconds = MFI_POLL_TIMEOUT_SECS;
925         return wait_and_poll(instance, cmd, seconds);
926 }
927
928 /**
929  * megasas_issue_blocked_cmd -  Synchronous wrapper around regular FW cmds
930  * @instance:                   Adapter soft state
931  * @cmd:                        Command to be issued
932  * @timeout:                    Timeout in seconds
933  *
934  * This function waits on an event for the command to be returned from ISR.
935  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
936  * Used to issue ioctl commands.
937  */
938 int
939 megasas_issue_blocked_cmd(struct megasas_instance *instance,
940                           struct megasas_cmd *cmd, int timeout)
941 {
942         int ret = 0;
943         cmd->cmd_status = ENODATA;
944
945         instance->instancet->issue_dcmd(instance, cmd);
946         if (timeout) {
947                 ret = wait_event_timeout(instance->int_cmd_wait_q,
948                                 cmd->cmd_status != ENODATA, timeout * HZ);
949                 if (!ret)
950                         return 1;
951         } else
952                 wait_event(instance->int_cmd_wait_q,
953                                 cmd->cmd_status != ENODATA);
954
955         return 0;
956 }
957
958 /**
959  * megasas_issue_blocked_abort_cmd -    Aborts previously issued cmd
960  * @instance:                           Adapter soft state
961  * @cmd_to_abort:                       Previously issued cmd to be aborted
962  * @timeout:                            Timeout in seconds
963  *
964  * MFI firmware can abort previously issued AEN comamnd (automatic event
965  * notification). The megasas_issue_blocked_abort_cmd() issues such abort
966  * cmd and waits for return status.
967  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
968  */
969 static int
970 megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
971                                 struct megasas_cmd *cmd_to_abort, int timeout)
972 {
973         struct megasas_cmd *cmd;
974         struct megasas_abort_frame *abort_fr;
975         int ret = 0;
976
977         cmd = megasas_get_cmd(instance);
978
979         if (!cmd)
980                 return -1;
981
982         abort_fr = &cmd->frame->abort;
983
984         /*
985          * Prepare and issue the abort frame
986          */
987         abort_fr->cmd = MFI_CMD_ABORT;
988         abort_fr->cmd_status = 0xFF;
989         abort_fr->flags = cpu_to_le16(0);
990         abort_fr->abort_context = cpu_to_le32(cmd_to_abort->index);
991         abort_fr->abort_mfi_phys_addr_lo =
992                 cpu_to_le32(lower_32_bits(cmd_to_abort->frame_phys_addr));
993         abort_fr->abort_mfi_phys_addr_hi =
994                 cpu_to_le32(upper_32_bits(cmd_to_abort->frame_phys_addr));
995
996         cmd->sync_cmd = 1;
997         cmd->cmd_status = ENODATA;
998
999         instance->instancet->issue_dcmd(instance, cmd);
1000
1001         if (timeout) {
1002                 ret = wait_event_timeout(instance->abort_cmd_wait_q,
1003                                 cmd->cmd_status != ENODATA, timeout * HZ);
1004                 if (!ret) {
1005                         dev_err(&instance->pdev->dev, "Command timedout"
1006                                 "from %s\n", __func__);
1007                         return 1;
1008                 }
1009         } else
1010                 wait_event(instance->abort_cmd_wait_q,
1011                                 cmd->cmd_status != ENODATA);
1012
1013         cmd->sync_cmd = 0;
1014
1015         megasas_return_cmd(instance, cmd);
1016         return 0;
1017 }
1018
1019 /**
1020  * megasas_make_sgl32 - Prepares 32-bit SGL
1021  * @instance:           Adapter soft state
1022  * @scp:                SCSI command from the mid-layer
1023  * @mfi_sgl:            SGL to be filled in
1024  *
1025  * If successful, this function returns the number of SG elements. Otherwise,
1026  * it returnes -1.
1027  */
1028 static int
1029 megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
1030                    union megasas_sgl *mfi_sgl)
1031 {
1032         int i;
1033         int sge_count;
1034         struct scatterlist *os_sgl;
1035
1036         sge_count = scsi_dma_map(scp);
1037         BUG_ON(sge_count < 0);
1038
1039         if (sge_count) {
1040                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1041                         mfi_sgl->sge32[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1042                         mfi_sgl->sge32[i].phys_addr = cpu_to_le32(sg_dma_address(os_sgl));
1043                 }
1044         }
1045         return sge_count;
1046 }
1047
1048 /**
1049  * megasas_make_sgl64 - Prepares 64-bit SGL
1050  * @instance:           Adapter soft state
1051  * @scp:                SCSI command from the mid-layer
1052  * @mfi_sgl:            SGL to be filled in
1053  *
1054  * If successful, this function returns the number of SG elements. Otherwise,
1055  * it returnes -1.
1056  */
1057 static int
1058 megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
1059                    union megasas_sgl *mfi_sgl)
1060 {
1061         int i;
1062         int sge_count;
1063         struct scatterlist *os_sgl;
1064
1065         sge_count = scsi_dma_map(scp);
1066         BUG_ON(sge_count < 0);
1067
1068         if (sge_count) {
1069                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1070                         mfi_sgl->sge64[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1071                         mfi_sgl->sge64[i].phys_addr = cpu_to_le64(sg_dma_address(os_sgl));
1072                 }
1073         }
1074         return sge_count;
1075 }
1076
1077 /**
1078  * megasas_make_sgl_skinny - Prepares IEEE SGL
1079  * @instance:           Adapter soft state
1080  * @scp:                SCSI command from the mid-layer
1081  * @mfi_sgl:            SGL to be filled in
1082  *
1083  * If successful, this function returns the number of SG elements. Otherwise,
1084  * it returnes -1.
1085  */
1086 static int
1087 megasas_make_sgl_skinny(struct megasas_instance *instance,
1088                 struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl)
1089 {
1090         int i;
1091         int sge_count;
1092         struct scatterlist *os_sgl;
1093
1094         sge_count = scsi_dma_map(scp);
1095
1096         if (sge_count) {
1097                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1098                         mfi_sgl->sge_skinny[i].length =
1099                                 cpu_to_le32(sg_dma_len(os_sgl));
1100                         mfi_sgl->sge_skinny[i].phys_addr =
1101                                 cpu_to_le64(sg_dma_address(os_sgl));
1102                         mfi_sgl->sge_skinny[i].flag = cpu_to_le32(0);
1103                 }
1104         }
1105         return sge_count;
1106 }
1107
1108  /**
1109  * megasas_get_frame_count - Computes the number of frames
1110  * @frame_type          : type of frame- io or pthru frame
1111  * @sge_count           : number of sg elements
1112  *
1113  * Returns the number of frames required for numnber of sge's (sge_count)
1114  */
1115
1116 static u32 megasas_get_frame_count(struct megasas_instance *instance,
1117                         u8 sge_count, u8 frame_type)
1118 {
1119         int num_cnt;
1120         int sge_bytes;
1121         u32 sge_sz;
1122         u32 frame_count=0;
1123
1124         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1125             sizeof(struct megasas_sge32);
1126
1127         if (instance->flag_ieee) {
1128                 sge_sz = sizeof(struct megasas_sge_skinny);
1129         }
1130
1131         /*
1132          * Main frame can contain 2 SGEs for 64-bit SGLs and
1133          * 3 SGEs for 32-bit SGLs for ldio &
1134          * 1 SGEs for 64-bit SGLs and
1135          * 2 SGEs for 32-bit SGLs for pthru frame
1136          */
1137         if (unlikely(frame_type == PTHRU_FRAME)) {
1138                 if (instance->flag_ieee == 1) {
1139                         num_cnt = sge_count - 1;
1140                 } else if (IS_DMA64)
1141                         num_cnt = sge_count - 1;
1142                 else
1143                         num_cnt = sge_count - 2;
1144         } else {
1145                 if (instance->flag_ieee == 1) {
1146                         num_cnt = sge_count - 1;
1147                 } else if (IS_DMA64)
1148                         num_cnt = sge_count - 2;
1149                 else
1150                         num_cnt = sge_count - 3;
1151         }
1152
1153         if(num_cnt>0){
1154                 sge_bytes = sge_sz * num_cnt;
1155
1156                 frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
1157                     ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
1158         }
1159         /* Main frame */
1160         frame_count +=1;
1161
1162         if (frame_count > 7)
1163                 frame_count = 8;
1164         return frame_count;
1165 }
1166
1167 /**
1168  * megasas_build_dcdb - Prepares a direct cdb (DCDB) command
1169  * @instance:           Adapter soft state
1170  * @scp:                SCSI command
1171  * @cmd:                Command to be prepared in
1172  *
1173  * This function prepares CDB commands. These are typcially pass-through
1174  * commands to the devices.
1175  */
1176 static int
1177 megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
1178                    struct megasas_cmd *cmd)
1179 {
1180         u32 is_logical;
1181         u32 device_id;
1182         u16 flags = 0;
1183         struct megasas_pthru_frame *pthru;
1184
1185         is_logical = MEGASAS_IS_LOGICAL(scp);
1186         device_id = MEGASAS_DEV_INDEX(scp);
1187         pthru = (struct megasas_pthru_frame *)cmd->frame;
1188
1189         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
1190                 flags = MFI_FRAME_DIR_WRITE;
1191         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1192                 flags = MFI_FRAME_DIR_READ;
1193         else if (scp->sc_data_direction == PCI_DMA_NONE)
1194                 flags = MFI_FRAME_DIR_NONE;
1195
1196         if (instance->flag_ieee == 1) {
1197                 flags |= MFI_FRAME_IEEE;
1198         }
1199
1200         /*
1201          * Prepare the DCDB frame
1202          */
1203         pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
1204         pthru->cmd_status = 0x0;
1205         pthru->scsi_status = 0x0;
1206         pthru->target_id = device_id;
1207         pthru->lun = scp->device->lun;
1208         pthru->cdb_len = scp->cmd_len;
1209         pthru->timeout = 0;
1210         pthru->pad_0 = 0;
1211         pthru->flags = cpu_to_le16(flags);
1212         pthru->data_xfer_len = cpu_to_le32(scsi_bufflen(scp));
1213
1214         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
1215
1216         /*
1217         * If the command is for the tape device, set the
1218         * pthru timeout to the os layer timeout value.
1219         */
1220         if (scp->device->type == TYPE_TAPE) {
1221                 if ((scp->request->timeout / HZ) > 0xFFFF)
1222                         pthru->timeout = cpu_to_le16(0xFFFF);
1223                 else
1224                         pthru->timeout = cpu_to_le16(scp->request->timeout / HZ);
1225         }
1226
1227         /*
1228          * Construct SGL
1229          */
1230         if (instance->flag_ieee == 1) {
1231                 pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1232                 pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
1233                                                       &pthru->sgl);
1234         } else if (IS_DMA64) {
1235                 pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1236                 pthru->sge_count = megasas_make_sgl64(instance, scp,
1237                                                       &pthru->sgl);
1238         } else
1239                 pthru->sge_count = megasas_make_sgl32(instance, scp,
1240                                                       &pthru->sgl);
1241
1242         if (pthru->sge_count > instance->max_num_sge) {
1243                 printk(KERN_ERR "megasas: DCDB two many SGE NUM=%x\n",
1244                         pthru->sge_count);
1245                 return 0;
1246         }
1247
1248         /*
1249          * Sense info specific
1250          */
1251         pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
1252         pthru->sense_buf_phys_addr_hi =
1253                 cpu_to_le32(upper_32_bits(cmd->sense_phys_addr));
1254         pthru->sense_buf_phys_addr_lo =
1255                 cpu_to_le32(lower_32_bits(cmd->sense_phys_addr));
1256
1257         /*
1258          * Compute the total number of frames this command consumes. FW uses
1259          * this number to pull sufficient number of frames from host memory.
1260          */
1261         cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
1262                                                         PTHRU_FRAME);
1263
1264         return cmd->frame_count;
1265 }
1266
1267 /**
1268  * megasas_build_ldio - Prepares IOs to logical devices
1269  * @instance:           Adapter soft state
1270  * @scp:                SCSI command
1271  * @cmd:                Command to be prepared
1272  *
1273  * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
1274  */
1275 static int
1276 megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
1277                    struct megasas_cmd *cmd)
1278 {
1279         u32 device_id;
1280         u8 sc = scp->cmnd[0];
1281         u16 flags = 0;
1282         struct megasas_io_frame *ldio;
1283
1284         device_id = MEGASAS_DEV_INDEX(scp);
1285         ldio = (struct megasas_io_frame *)cmd->frame;
1286
1287         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
1288                 flags = MFI_FRAME_DIR_WRITE;
1289         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1290                 flags = MFI_FRAME_DIR_READ;
1291
1292         if (instance->flag_ieee == 1) {
1293                 flags |= MFI_FRAME_IEEE;
1294         }
1295
1296         /*
1297          * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
1298          */
1299         ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
1300         ldio->cmd_status = 0x0;
1301         ldio->scsi_status = 0x0;
1302         ldio->target_id = device_id;
1303         ldio->timeout = 0;
1304         ldio->reserved_0 = 0;
1305         ldio->pad_0 = 0;
1306         ldio->flags = cpu_to_le16(flags);
1307         ldio->start_lba_hi = 0;
1308         ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
1309
1310         /*
1311          * 6-byte READ(0x08) or WRITE(0x0A) cdb
1312          */
1313         if (scp->cmd_len == 6) {
1314                 ldio->lba_count = cpu_to_le32((u32) scp->cmnd[4]);
1315                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[1] << 16) |
1316                                                  ((u32) scp->cmnd[2] << 8) |
1317                                                  (u32) scp->cmnd[3]);
1318
1319                 ldio->start_lba_lo &= cpu_to_le32(0x1FFFFF);
1320         }
1321
1322         /*
1323          * 10-byte READ(0x28) or WRITE(0x2A) cdb
1324          */
1325         else if (scp->cmd_len == 10) {
1326                 ldio->lba_count = cpu_to_le32((u32) scp->cmnd[8] |
1327                                               ((u32) scp->cmnd[7] << 8));
1328                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1329                                                  ((u32) scp->cmnd[3] << 16) |
1330                                                  ((u32) scp->cmnd[4] << 8) |
1331                                                  (u32) scp->cmnd[5]);
1332         }
1333
1334         /*
1335          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1336          */
1337         else if (scp->cmd_len == 12) {
1338                 ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1339                                               ((u32) scp->cmnd[7] << 16) |
1340                                               ((u32) scp->cmnd[8] << 8) |
1341                                               (u32) scp->cmnd[9]);
1342
1343                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1344                                                  ((u32) scp->cmnd[3] << 16) |
1345                                                  ((u32) scp->cmnd[4] << 8) |
1346                                                  (u32) scp->cmnd[5]);
1347         }
1348
1349         /*
1350          * 16-byte READ(0x88) or WRITE(0x8A) cdb
1351          */
1352         else if (scp->cmd_len == 16) {
1353                 ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[10] << 24) |
1354                                               ((u32) scp->cmnd[11] << 16) |
1355                                               ((u32) scp->cmnd[12] << 8) |
1356                                               (u32) scp->cmnd[13]);
1357
1358                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1359                                                  ((u32) scp->cmnd[7] << 16) |
1360                                                  ((u32) scp->cmnd[8] << 8) |
1361                                                  (u32) scp->cmnd[9]);
1362
1363                 ldio->start_lba_hi = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1364                                                  ((u32) scp->cmnd[3] << 16) |
1365                                                  ((u32) scp->cmnd[4] << 8) |
1366                                                  (u32) scp->cmnd[5]);
1367
1368         }
1369
1370         /*
1371          * Construct SGL
1372          */
1373         if (instance->flag_ieee) {
1374                 ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1375                 ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
1376                                               &ldio->sgl);
1377         } else if (IS_DMA64) {
1378                 ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1379                 ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
1380         } else
1381                 ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
1382
1383         if (ldio->sge_count > instance->max_num_sge) {
1384                 printk(KERN_ERR "megasas: build_ld_io: sge_count = %x\n",
1385                         ldio->sge_count);
1386                 return 0;
1387         }
1388
1389         /*
1390          * Sense info specific
1391          */
1392         ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
1393         ldio->sense_buf_phys_addr_hi = 0;
1394         ldio->sense_buf_phys_addr_lo = cpu_to_le32(cmd->sense_phys_addr);
1395
1396         /*
1397          * Compute the total number of frames this command consumes. FW uses
1398          * this number to pull sufficient number of frames from host memory.
1399          */
1400         cmd->frame_count = megasas_get_frame_count(instance,
1401                         ldio->sge_count, IO_FRAME);
1402
1403         return cmd->frame_count;
1404 }
1405
1406 /**
1407  * megasas_cmd_type -           Checks if the cmd is for logical drive/sysPD
1408  *                              and whether it's RW or non RW
1409  * @scmd:                       SCSI command
1410  *
1411  */
1412 inline int megasas_cmd_type(struct scsi_cmnd *cmd)
1413 {
1414         int ret;
1415
1416         switch (cmd->cmnd[0]) {
1417         case READ_10:
1418         case WRITE_10:
1419         case READ_12:
1420         case WRITE_12:
1421         case READ_6:
1422         case WRITE_6:
1423         case READ_16:
1424         case WRITE_16:
1425                 ret = (MEGASAS_IS_LOGICAL(cmd)) ?
1426                         READ_WRITE_LDIO : READ_WRITE_SYSPDIO;
1427                 break;
1428         default:
1429                 ret = (MEGASAS_IS_LOGICAL(cmd)) ?
1430                         NON_READ_WRITE_LDIO : NON_READ_WRITE_SYSPDIO;
1431         }
1432         return ret;
1433 }
1434
1435  /**
1436  * megasas_dump_pending_frames -        Dumps the frame address of all pending cmds
1437  *                                      in FW
1438  * @instance:                           Adapter soft state
1439  */
1440 static inline void
1441 megasas_dump_pending_frames(struct megasas_instance *instance)
1442 {
1443         struct megasas_cmd *cmd;
1444         int i,n;
1445         union megasas_sgl *mfi_sgl;
1446         struct megasas_io_frame *ldio;
1447         struct megasas_pthru_frame *pthru;
1448         u32 sgcount;
1449         u32 max_cmd = instance->max_fw_cmds;
1450
1451         printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
1452         printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
1453         if (IS_DMA64)
1454                 printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
1455         else
1456                 printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
1457
1458         printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
1459         for (i = 0; i < max_cmd; i++) {
1460                 cmd = instance->cmd_list[i];
1461                 if(!cmd->scmd)
1462                         continue;
1463                 printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
1464                 if (megasas_cmd_type(cmd->scmd) == READ_WRITE_LDIO) {
1465                         ldio = (struct megasas_io_frame *)cmd->frame;
1466                         mfi_sgl = &ldio->sgl;
1467                         sgcount = ldio->sge_count;
1468                         printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x,"
1469                         " lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1470                         instance->host->host_no, cmd->frame_count, ldio->cmd, ldio->target_id,
1471                         le32_to_cpu(ldio->start_lba_lo), le32_to_cpu(ldio->start_lba_hi),
1472                         le32_to_cpu(ldio->sense_buf_phys_addr_lo), sgcount);
1473                 }
1474                 else {
1475                         pthru = (struct megasas_pthru_frame *) cmd->frame;
1476                         mfi_sgl = &pthru->sgl;
1477                         sgcount = pthru->sge_count;
1478                         printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, "
1479                         "lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1480                         instance->host->host_no, cmd->frame_count, pthru->cmd, pthru->target_id,
1481                         pthru->lun, pthru->cdb_len, le32_to_cpu(pthru->data_xfer_len),
1482                         le32_to_cpu(pthru->sense_buf_phys_addr_lo), sgcount);
1483                 }
1484         if(megasas_dbg_lvl & MEGASAS_DBG_LVL){
1485                 for (n = 0; n < sgcount; n++){
1486                         if (IS_DMA64)
1487                                 printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%llx ",
1488                                         le32_to_cpu(mfi_sgl->sge64[n].length),
1489                                         le64_to_cpu(mfi_sgl->sge64[n].phys_addr));
1490                         else
1491                                 printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",
1492                                         le32_to_cpu(mfi_sgl->sge32[n].length),
1493                                         le32_to_cpu(mfi_sgl->sge32[n].phys_addr));
1494                         }
1495                 }
1496                 printk(KERN_ERR "\n");
1497         } /*for max_cmd*/
1498         printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
1499         for (i = 0; i < max_cmd; i++) {
1500
1501                 cmd = instance->cmd_list[i];
1502
1503                 if(cmd->sync_cmd == 1){
1504                         printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
1505                 }
1506         }
1507         printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no);
1508 }
1509
1510 u32
1511 megasas_build_and_issue_cmd(struct megasas_instance *instance,
1512                             struct scsi_cmnd *scmd)
1513 {
1514         struct megasas_cmd *cmd;
1515         u32 frame_count;
1516
1517         cmd = megasas_get_cmd(instance);
1518         if (!cmd)
1519                 return SCSI_MLQUEUE_HOST_BUSY;
1520
1521         /*
1522          * Logical drive command
1523          */
1524         if (megasas_cmd_type(scmd) == READ_WRITE_LDIO)
1525                 frame_count = megasas_build_ldio(instance, scmd, cmd);
1526         else
1527                 frame_count = megasas_build_dcdb(instance, scmd, cmd);
1528
1529         if (!frame_count)
1530                 goto out_return_cmd;
1531
1532         cmd->scmd = scmd;
1533         scmd->SCp.ptr = (char *)cmd;
1534
1535         /*
1536          * Issue the command to the FW
1537          */
1538         atomic_inc(&instance->fw_outstanding);
1539
1540         instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
1541                                 cmd->frame_count-1, instance->reg_set);
1542
1543         return 0;
1544 out_return_cmd:
1545         megasas_return_cmd(instance, cmd);
1546         return 1;
1547 }
1548
1549
1550 /**
1551  * megasas_queue_command -      Queue entry point
1552  * @scmd:                       SCSI command to be queued
1553  * @done:                       Callback entry point
1554  */
1555 static int
1556 megasas_queue_command(struct Scsi_Host *shost, struct scsi_cmnd *scmd)
1557 {
1558         struct megasas_instance *instance;
1559         unsigned long flags;
1560
1561         instance = (struct megasas_instance *)
1562             scmd->device->host->hostdata;
1563
1564         if (instance->unload == 1) {
1565                 scmd->result = DID_NO_CONNECT << 16;
1566                 scmd->scsi_done(scmd);
1567                 return 0;
1568         }
1569
1570         if (instance->issuepend_done == 0)
1571                 return SCSI_MLQUEUE_HOST_BUSY;
1572
1573         spin_lock_irqsave(&instance->hba_lock, flags);
1574
1575         /* Check for an mpio path and adjust behavior */
1576         if (instance->adprecovery == MEGASAS_ADPRESET_SM_INFAULT) {
1577                 if (megasas_check_mpio_paths(instance, scmd) ==
1578                     (DID_RESET << 16)) {
1579                         spin_unlock_irqrestore(&instance->hba_lock, flags);
1580                         return SCSI_MLQUEUE_HOST_BUSY;
1581                 } else {
1582                         spin_unlock_irqrestore(&instance->hba_lock, flags);
1583                         scmd->result = DID_NO_CONNECT << 16;
1584                         scmd->scsi_done(scmd);
1585                         return 0;
1586                 }
1587         }
1588
1589         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
1590                 spin_unlock_irqrestore(&instance->hba_lock, flags);
1591                 scmd->result = DID_NO_CONNECT << 16;
1592                 scmd->scsi_done(scmd);
1593                 return 0;
1594         }
1595
1596         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
1597                 spin_unlock_irqrestore(&instance->hba_lock, flags);
1598                 return SCSI_MLQUEUE_HOST_BUSY;
1599         }
1600
1601         spin_unlock_irqrestore(&instance->hba_lock, flags);
1602
1603         scmd->result = 0;
1604
1605         if (MEGASAS_IS_LOGICAL(scmd) &&
1606             (scmd->device->id >= instance->fw_supported_vd_count ||
1607                 scmd->device->lun)) {
1608                 scmd->result = DID_BAD_TARGET << 16;
1609                 goto out_done;
1610         }
1611
1612         switch (scmd->cmnd[0]) {
1613         case SYNCHRONIZE_CACHE:
1614                 /*
1615                  * FW takes care of flush cache on its own
1616                  * No need to send it down
1617                  */
1618                 scmd->result = DID_OK << 16;
1619                 goto out_done;
1620         default:
1621                 break;
1622         }
1623
1624         if (instance->instancet->build_and_issue_cmd(instance, scmd)) {
1625                 printk(KERN_ERR "megasas: Err returned from build_and_issue_cmd\n");
1626                 return SCSI_MLQUEUE_HOST_BUSY;
1627         }
1628
1629         return 0;
1630
1631  out_done:
1632         scmd->scsi_done(scmd);
1633         return 0;
1634 }
1635
1636 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
1637 {
1638         int i;
1639
1640         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
1641
1642                 if ((megasas_mgmt_info.instance[i]) &&
1643                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
1644                         return megasas_mgmt_info.instance[i];
1645         }
1646
1647         return NULL;
1648 }
1649
1650 static int megasas_slave_configure(struct scsi_device *sdev)
1651 {
1652         /*
1653         * The RAID firmware may require extended timeouts.
1654         */
1655         blk_queue_rq_timeout(sdev->request_queue,
1656                 MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
1657
1658         return 0;
1659 }
1660
1661 static int megasas_slave_alloc(struct scsi_device *sdev)
1662 {
1663         u16             pd_index = 0;
1664         struct megasas_instance *instance ;
1665         instance = megasas_lookup_instance(sdev->host->host_no);
1666         if (sdev->channel < MEGASAS_MAX_PD_CHANNELS) {
1667                 /*
1668                  * Open the OS scan to the SYSTEM PD
1669                  */
1670                 pd_index =
1671                         (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1672                         sdev->id;
1673                 if (instance->pd_list[pd_index].driveState ==
1674                                         MR_PD_STATE_SYSTEM) {
1675                         return 0;
1676                 }
1677                 return -ENXIO;
1678         }
1679         return 0;
1680 }
1681
1682 /*
1683 * megasas_complete_outstanding_ioctls - Complete outstanding ioctls after a
1684 *                                       kill adapter
1685 * @instance:                            Adapter soft state
1686 *
1687 */
1688 static void megasas_complete_outstanding_ioctls(struct megasas_instance *instance)
1689 {
1690         int i;
1691         struct megasas_cmd *cmd_mfi;
1692         struct megasas_cmd_fusion *cmd_fusion;
1693         struct fusion_context *fusion = instance->ctrl_context;
1694
1695         /* Find all outstanding ioctls */
1696         if (fusion) {
1697                 for (i = 0; i < instance->max_fw_cmds; i++) {
1698                         cmd_fusion = fusion->cmd_list[i];
1699                         if (cmd_fusion->sync_cmd_idx != (u32)ULONG_MAX) {
1700                                 cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
1701                                 if (cmd_mfi->sync_cmd &&
1702                                         cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT)
1703                                         megasas_complete_cmd(instance,
1704                                                              cmd_mfi, DID_OK);
1705                         }
1706                 }
1707         } else {
1708                 for (i = 0; i < instance->max_fw_cmds; i++) {
1709                         cmd_mfi = instance->cmd_list[i];
1710                         if (cmd_mfi->sync_cmd && cmd_mfi->frame->hdr.cmd !=
1711                                 MFI_CMD_ABORT)
1712                                 megasas_complete_cmd(instance, cmd_mfi, DID_OK);
1713                 }
1714         }
1715 }
1716
1717
1718 void megaraid_sas_kill_hba(struct megasas_instance *instance)
1719 {
1720         /* Set critical error to block I/O & ioctls in case caller didn't */
1721         instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR;
1722         /* Wait 1 second to ensure IO or ioctls in build have posted */
1723         msleep(1000);
1724         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1725                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
1726                 (instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
1727                 (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
1728                 (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
1729                 (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY)) {
1730                 writel(MFI_STOP_ADP,
1731                         &instance->reg_set->doorbell);
1732                 /* Flush */
1733                 readl(&instance->reg_set->doorbell);
1734                 if (instance->mpio && instance->requestorId)
1735                         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
1736         } else {
1737                 writel(MFI_STOP_ADP,
1738                         &instance->reg_set->inbound_doorbell);
1739         }
1740         /* Complete outstanding ioctls when adapter is killed */
1741         megasas_complete_outstanding_ioctls(instance);
1742 }
1743
1744  /**
1745   * megasas_check_and_restore_queue_depth - Check if queue depth needs to be
1746   *                                     restored to max value
1747   * @instance:                  Adapter soft state
1748   *
1749   */
1750 void
1751 megasas_check_and_restore_queue_depth(struct megasas_instance *instance)
1752 {
1753         unsigned long flags;
1754
1755         if (instance->flag & MEGASAS_FW_BUSY
1756             && time_after(jiffies, instance->last_time + 5 * HZ)
1757             && atomic_read(&instance->fw_outstanding) <
1758             instance->throttlequeuedepth + 1) {
1759
1760                 spin_lock_irqsave(instance->host->host_lock, flags);
1761                 instance->flag &= ~MEGASAS_FW_BUSY;
1762
1763                 instance->host->can_queue = instance->max_scsi_cmds;
1764                 spin_unlock_irqrestore(instance->host->host_lock, flags);
1765         }
1766 }
1767
1768 /**
1769  * megasas_complete_cmd_dpc      -      Returns FW's controller structure
1770  * @instance_addr:                      Address of adapter soft state
1771  *
1772  * Tasklet to complete cmds
1773  */
1774 static void megasas_complete_cmd_dpc(unsigned long instance_addr)
1775 {
1776         u32 producer;
1777         u32 consumer;
1778         u32 context;
1779         struct megasas_cmd *cmd;
1780         struct megasas_instance *instance =
1781                                 (struct megasas_instance *)instance_addr;
1782         unsigned long flags;
1783
1784         /* If we have already declared adapter dead, donot complete cmds */
1785         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR )
1786                 return;
1787
1788         spin_lock_irqsave(&instance->completion_lock, flags);
1789
1790         producer = le32_to_cpu(*instance->producer);
1791         consumer = le32_to_cpu(*instance->consumer);
1792
1793         while (consumer != producer) {
1794                 context = le32_to_cpu(instance->reply_queue[consumer]);
1795                 if (context >= instance->max_fw_cmds) {
1796                         printk(KERN_ERR "Unexpected context value %x\n",
1797                                 context);
1798                         BUG();
1799                 }
1800
1801                 cmd = instance->cmd_list[context];
1802
1803                 megasas_complete_cmd(instance, cmd, DID_OK);
1804
1805                 consumer++;
1806                 if (consumer == (instance->max_fw_cmds + 1)) {
1807                         consumer = 0;
1808                 }
1809         }
1810
1811         *instance->consumer = cpu_to_le32(producer);
1812
1813         spin_unlock_irqrestore(&instance->completion_lock, flags);
1814
1815         /*
1816          * Check if we can restore can_queue
1817          */
1818         megasas_check_and_restore_queue_depth(instance);
1819 }
1820
1821 /**
1822  * megasas_start_timer - Initializes a timer object
1823  * @instance:           Adapter soft state
1824  * @timer:              timer object to be initialized
1825  * @fn:                 timer function
1826  * @interval:           time interval between timer function call
1827  *
1828  */
1829 void megasas_start_timer(struct megasas_instance *instance,
1830                         struct timer_list *timer,
1831                         void *fn, unsigned long interval)
1832 {
1833         init_timer(timer);
1834         timer->expires = jiffies + interval;
1835         timer->data = (unsigned long)instance;
1836         timer->function = fn;
1837         add_timer(timer);
1838 }
1839
1840 static void
1841 megasas_internal_reset_defer_cmds(struct megasas_instance *instance);
1842
1843 static void
1844 process_fw_state_change_wq(struct work_struct *work);
1845
1846 void megasas_do_ocr(struct megasas_instance *instance)
1847 {
1848         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
1849         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
1850         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
1851                 *instance->consumer = cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
1852         }
1853         instance->instancet->disable_intr(instance);
1854         instance->adprecovery   = MEGASAS_ADPRESET_SM_INFAULT;
1855         instance->issuepend_done = 0;
1856
1857         atomic_set(&instance->fw_outstanding, 0);
1858         megasas_internal_reset_defer_cmds(instance);
1859         process_fw_state_change_wq(&instance->work_init);
1860 }
1861
1862 static int megasas_get_ld_vf_affiliation_111(struct megasas_instance *instance,
1863                                             int initial)
1864 {
1865         struct megasas_cmd *cmd;
1866         struct megasas_dcmd_frame *dcmd;
1867         struct MR_LD_VF_AFFILIATION_111 *new_affiliation_111 = NULL;
1868         dma_addr_t new_affiliation_111_h;
1869         int ld, retval = 0;
1870         u8 thisVf;
1871
1872         cmd = megasas_get_cmd(instance);
1873
1874         if (!cmd) {
1875                 printk(KERN_DEBUG "megasas: megasas_get_ld_vf_affiliation_111:"
1876                        "Failed to get cmd for scsi%d.\n",
1877                         instance->host->host_no);
1878                 return -ENOMEM;
1879         }
1880
1881         dcmd = &cmd->frame->dcmd;
1882
1883         if (!instance->vf_affiliation_111) {
1884                 printk(KERN_WARNING "megasas: SR-IOV: Couldn't get LD/VF "
1885                        "affiliation for scsi%d.\n", instance->host->host_no);
1886                 megasas_return_cmd(instance, cmd);
1887                 return -ENOMEM;
1888         }
1889
1890         if (initial)
1891                         memset(instance->vf_affiliation_111, 0,
1892                                sizeof(struct MR_LD_VF_AFFILIATION_111));
1893         else {
1894                 new_affiliation_111 =
1895                         pci_alloc_consistent(instance->pdev,
1896                                              sizeof(struct MR_LD_VF_AFFILIATION_111),
1897                                              &new_affiliation_111_h);
1898                 if (!new_affiliation_111) {
1899                         printk(KERN_DEBUG "megasas: SR-IOV: Couldn't allocate "
1900                                "memory for new affiliation for scsi%d.\n",
1901                                instance->host->host_no);
1902                         megasas_return_cmd(instance, cmd);
1903                         return -ENOMEM;
1904                 }
1905                 memset(new_affiliation_111, 0,
1906                        sizeof(struct MR_LD_VF_AFFILIATION_111));
1907         }
1908
1909         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1910
1911         dcmd->cmd = MFI_CMD_DCMD;
1912         dcmd->cmd_status = 0xFF;
1913         dcmd->sge_count = 1;
1914         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
1915         dcmd->timeout = 0;
1916         dcmd->pad_0 = 0;
1917         dcmd->data_xfer_len =
1918                 cpu_to_le32(sizeof(struct MR_LD_VF_AFFILIATION_111));
1919         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS_111);
1920
1921         if (initial)
1922                 dcmd->sgl.sge32[0].phys_addr =
1923                         cpu_to_le32(instance->vf_affiliation_111_h);
1924         else
1925                 dcmd->sgl.sge32[0].phys_addr =
1926                         cpu_to_le32(new_affiliation_111_h);
1927
1928         dcmd->sgl.sge32[0].length = cpu_to_le32(
1929                 sizeof(struct MR_LD_VF_AFFILIATION_111));
1930
1931         printk(KERN_WARNING "megasas: SR-IOV: Getting LD/VF affiliation for "
1932                "scsi%d\n", instance->host->host_no);
1933
1934         megasas_issue_blocked_cmd(instance, cmd, 0);
1935
1936         if (dcmd->cmd_status) {
1937                 printk(KERN_WARNING "megasas: SR-IOV: LD/VF affiliation DCMD"
1938                        " failed with status 0x%x for scsi%d.\n",
1939                        dcmd->cmd_status, instance->host->host_no);
1940                 retval = 1; /* Do a scan if we couldn't get affiliation */
1941                 goto out;
1942         }
1943
1944         if (!initial) {
1945                 thisVf = new_affiliation_111->thisVf;
1946                 for (ld = 0 ; ld < new_affiliation_111->vdCount; ld++)
1947                         if (instance->vf_affiliation_111->map[ld].policy[thisVf] !=
1948                             new_affiliation_111->map[ld].policy[thisVf]) {
1949                                 printk(KERN_WARNING "megasas: SR-IOV: "
1950                                        "Got new LD/VF affiliation "
1951                                        "for scsi%d.\n",
1952                                        instance->host->host_no);
1953                                 memcpy(instance->vf_affiliation_111,
1954                                        new_affiliation_111,
1955                                        sizeof(struct MR_LD_VF_AFFILIATION_111));
1956                                 retval = 1;
1957                                 goto out;
1958                         }
1959         }
1960 out:
1961         if (new_affiliation_111) {
1962                 pci_free_consistent(instance->pdev,
1963                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
1964                                     new_affiliation_111,
1965                                     new_affiliation_111_h);
1966         }
1967
1968         megasas_return_cmd(instance, cmd);
1969
1970         return retval;
1971 }
1972
1973 static int megasas_get_ld_vf_affiliation_12(struct megasas_instance *instance,
1974                                             int initial)
1975 {
1976         struct megasas_cmd *cmd;
1977         struct megasas_dcmd_frame *dcmd;
1978         struct MR_LD_VF_AFFILIATION *new_affiliation = NULL;
1979         struct MR_LD_VF_MAP *newmap = NULL, *savedmap = NULL;
1980         dma_addr_t new_affiliation_h;
1981         int i, j, retval = 0, found = 0, doscan = 0;
1982         u8 thisVf;
1983
1984         cmd = megasas_get_cmd(instance);
1985
1986         if (!cmd) {
1987                 printk(KERN_DEBUG "megasas: megasas_get_ld_vf_affiliation12: "
1988                        "Failed to get cmd for scsi%d.\n",
1989                        instance->host->host_no);
1990                 return -ENOMEM;
1991         }
1992
1993         dcmd = &cmd->frame->dcmd;
1994
1995         if (!instance->vf_affiliation) {
1996                 printk(KERN_WARNING "megasas: SR-IOV: Couldn't get LD/VF "
1997                        "affiliation for scsi%d.\n", instance->host->host_no);
1998                 megasas_return_cmd(instance, cmd);
1999                 return -ENOMEM;
2000         }
2001
2002         if (initial)
2003                 memset(instance->vf_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) *
2004                        sizeof(struct MR_LD_VF_AFFILIATION));
2005         else {
2006                 new_affiliation =
2007                         pci_alloc_consistent(instance->pdev,
2008                                              (MAX_LOGICAL_DRIVES + 1) *
2009                                              sizeof(struct MR_LD_VF_AFFILIATION),
2010                                              &new_affiliation_h);
2011                 if (!new_affiliation) {
2012                         printk(KERN_DEBUG "megasas: SR-IOV: Couldn't allocate "
2013                                "memory for new affiliation for scsi%d.\n",
2014                                instance->host->host_no);
2015                         megasas_return_cmd(instance, cmd);
2016                         return -ENOMEM;
2017                 }
2018                 memset(new_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) *
2019                        sizeof(struct MR_LD_VF_AFFILIATION));
2020         }
2021
2022         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2023
2024         dcmd->cmd = MFI_CMD_DCMD;
2025         dcmd->cmd_status = 0xFF;
2026         dcmd->sge_count = 1;
2027         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2028         dcmd->timeout = 0;
2029         dcmd->pad_0 = 0;
2030         dcmd->data_xfer_len = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2031                 sizeof(struct MR_LD_VF_AFFILIATION));
2032         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS);
2033
2034         if (initial)
2035                 dcmd->sgl.sge32[0].phys_addr =
2036                         cpu_to_le32(instance->vf_affiliation_h);
2037         else
2038                 dcmd->sgl.sge32[0].phys_addr =
2039                         cpu_to_le32(new_affiliation_h);
2040
2041         dcmd->sgl.sge32[0].length = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2042                 sizeof(struct MR_LD_VF_AFFILIATION));
2043
2044         printk(KERN_WARNING "megasas: SR-IOV: Getting LD/VF affiliation for "
2045                "scsi%d\n", instance->host->host_no);
2046
2047         megasas_issue_blocked_cmd(instance, cmd, 0);
2048
2049         if (dcmd->cmd_status) {
2050                 printk(KERN_WARNING "megasas: SR-IOV: LD/VF affiliation DCMD"
2051                        " failed with status 0x%x for scsi%d.\n",
2052                        dcmd->cmd_status, instance->host->host_no);
2053                 retval = 1; /* Do a scan if we couldn't get affiliation */
2054                 goto out;
2055         }
2056
2057         if (!initial) {
2058                 if (!new_affiliation->ldCount) {
2059                         printk(KERN_WARNING "megasas: SR-IOV: Got new LD/VF "
2060                                "affiliation for passive path for scsi%d.\n",
2061                                instance->host->host_no);
2062                         retval = 1;
2063                         goto out;
2064                 }
2065                 newmap = new_affiliation->map;
2066                 savedmap = instance->vf_affiliation->map;
2067                 thisVf = new_affiliation->thisVf;
2068                 for (i = 0 ; i < new_affiliation->ldCount; i++) {
2069                         found = 0;
2070                         for (j = 0; j < instance->vf_affiliation->ldCount;
2071                              j++) {
2072                                 if (newmap->ref.targetId ==
2073                                     savedmap->ref.targetId) {
2074                                         found = 1;
2075                                         if (newmap->policy[thisVf] !=
2076                                             savedmap->policy[thisVf]) {
2077                                                 doscan = 1;
2078                                                 goto out;
2079                                         }
2080                                 }
2081                                 savedmap = (struct MR_LD_VF_MAP *)
2082                                         ((unsigned char *)savedmap +
2083                                          savedmap->size);
2084                         }
2085                         if (!found && newmap->policy[thisVf] !=
2086                             MR_LD_ACCESS_HIDDEN) {
2087                                 doscan = 1;
2088                                 goto out;
2089                         }
2090                         newmap = (struct MR_LD_VF_MAP *)
2091                                 ((unsigned char *)newmap + newmap->size);
2092                 }
2093
2094                 newmap = new_affiliation->map;
2095                 savedmap = instance->vf_affiliation->map;
2096
2097                 for (i = 0 ; i < instance->vf_affiliation->ldCount; i++) {
2098                         found = 0;
2099                         for (j = 0 ; j < new_affiliation->ldCount; j++) {
2100                                 if (savedmap->ref.targetId ==
2101                                     newmap->ref.targetId) {
2102                                         found = 1;
2103                                         if (savedmap->policy[thisVf] !=
2104                                             newmap->policy[thisVf]) {
2105                                                 doscan = 1;
2106                                                 goto out;
2107                                         }
2108                                 }
2109                                 newmap = (struct MR_LD_VF_MAP *)
2110                                         ((unsigned char *)newmap +
2111                                          newmap->size);
2112                         }
2113                         if (!found && savedmap->policy[thisVf] !=
2114                             MR_LD_ACCESS_HIDDEN) {
2115                                 doscan = 1;
2116                                 goto out;
2117                         }
2118                         savedmap = (struct MR_LD_VF_MAP *)
2119                                 ((unsigned char *)savedmap +
2120                                  savedmap->size);
2121                 }
2122         }
2123 out:
2124         if (doscan) {
2125                 printk(KERN_WARNING "megasas: SR-IOV: Got new LD/VF "
2126                        "affiliation for scsi%d.\n", instance->host->host_no);
2127                 memcpy(instance->vf_affiliation, new_affiliation,
2128                        new_affiliation->size);
2129                 retval = 1;
2130         }
2131
2132         if (new_affiliation)
2133                 pci_free_consistent(instance->pdev,
2134                                     (MAX_LOGICAL_DRIVES + 1) *
2135                                     sizeof(struct MR_LD_VF_AFFILIATION),
2136                                     new_affiliation, new_affiliation_h);
2137         megasas_return_cmd(instance, cmd);
2138
2139         return retval;
2140 }
2141
2142 /* This function will get the current SR-IOV LD/VF affiliation */
2143 static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
2144         int initial)
2145 {
2146         int retval;
2147
2148         if (instance->PlasmaFW111)
2149                 retval = megasas_get_ld_vf_affiliation_111(instance, initial);
2150         else
2151                 retval = megasas_get_ld_vf_affiliation_12(instance, initial);
2152         return retval;
2153 }
2154
2155 /* This function will tell FW to start the SR-IOV heartbeat */
2156 int megasas_sriov_start_heartbeat(struct megasas_instance *instance,
2157                                          int initial)
2158 {
2159         struct megasas_cmd *cmd;
2160         struct megasas_dcmd_frame *dcmd;
2161         int retval = 0;
2162
2163         cmd = megasas_get_cmd(instance);
2164
2165         if (!cmd) {
2166                 printk(KERN_DEBUG "megasas: megasas_sriov_start_heartbeat: "
2167                        "Failed to get cmd for scsi%d.\n",
2168                        instance->host->host_no);
2169                 return -ENOMEM;
2170         }
2171
2172         dcmd = &cmd->frame->dcmd;
2173
2174         if (initial) {
2175                 instance->hb_host_mem =
2176                         pci_zalloc_consistent(instance->pdev,
2177                                               sizeof(struct MR_CTRL_HB_HOST_MEM),
2178                                               &instance->hb_host_mem_h);
2179                 if (!instance->hb_host_mem) {
2180                         printk(KERN_DEBUG "megasas: SR-IOV: Couldn't allocate"
2181                                " memory for heartbeat host memory for "
2182                                "scsi%d.\n", instance->host->host_no);
2183                         retval = -ENOMEM;
2184                         goto out;
2185                 }
2186         }
2187
2188         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2189
2190         dcmd->mbox.s[0] = cpu_to_le16(sizeof(struct MR_CTRL_HB_HOST_MEM));
2191         dcmd->cmd = MFI_CMD_DCMD;
2192         dcmd->cmd_status = 0xFF;
2193         dcmd->sge_count = 1;
2194         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2195         dcmd->timeout = 0;
2196         dcmd->pad_0 = 0;
2197         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_CTRL_HB_HOST_MEM));
2198         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SHARED_HOST_MEM_ALLOC);
2199         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(instance->hb_host_mem_h);
2200         dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct MR_CTRL_HB_HOST_MEM));
2201
2202         printk(KERN_WARNING "megasas: SR-IOV: Starting heartbeat for scsi%d\n",
2203                instance->host->host_no);
2204
2205         if (instance->ctrl_context && !instance->mask_interrupts)
2206                 retval = megasas_issue_blocked_cmd(instance, cmd,
2207                         MEGASAS_ROUTINE_WAIT_TIME_VF);
2208         else
2209                 retval = megasas_issue_polled(instance, cmd);
2210
2211         if (retval) {
2212                 printk(KERN_WARNING "megasas: SR-IOV: MR_DCMD_CTRL_SHARED_HOST"
2213                        "_MEM_ALLOC DCMD timed out for scsi%d\n",
2214                        instance->host->host_no);
2215                 retval = 1;
2216                 goto out;
2217         }
2218
2219
2220         if (dcmd->cmd_status) {
2221                 printk(KERN_WARNING "megasas: SR-IOV: MR_DCMD_CTRL_SHARED_HOST"
2222                        "_MEM_ALLOC DCMD failed with status 0x%x for scsi%d\n",
2223                        dcmd->cmd_status,
2224                        instance->host->host_no);
2225                 retval = 1;
2226                 goto out;
2227         }
2228
2229 out:
2230         megasas_return_cmd(instance, cmd);
2231
2232         return retval;
2233 }
2234
2235 /* Handler for SR-IOV heartbeat */
2236 void megasas_sriov_heartbeat_handler(unsigned long instance_addr)
2237 {
2238         struct megasas_instance *instance =
2239                 (struct megasas_instance *)instance_addr;
2240
2241         if (instance->hb_host_mem->HB.fwCounter !=
2242             instance->hb_host_mem->HB.driverCounter) {
2243                 instance->hb_host_mem->HB.driverCounter =
2244                         instance->hb_host_mem->HB.fwCounter;
2245                 mod_timer(&instance->sriov_heartbeat_timer,
2246                           jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
2247         } else {
2248                 printk(KERN_WARNING "megasas: SR-IOV: Heartbeat never "
2249                        "completed for scsi%d\n", instance->host->host_no);
2250                 schedule_work(&instance->work_init);
2251         }
2252 }
2253
2254 /**
2255  * megasas_wait_for_outstanding -       Wait for all outstanding cmds
2256  * @instance:                           Adapter soft state
2257  *
2258  * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to
2259  * complete all its outstanding commands. Returns error if one or more IOs
2260  * are pending after this time period. It also marks the controller dead.
2261  */
2262 static int megasas_wait_for_outstanding(struct megasas_instance *instance)
2263 {
2264         int i;
2265         u32 reset_index;
2266         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
2267         u8 adprecovery;
2268         unsigned long flags;
2269         struct list_head clist_local;
2270         struct megasas_cmd *reset_cmd;
2271         u32 fw_state;
2272         u8 kill_adapter_flag;
2273
2274         spin_lock_irqsave(&instance->hba_lock, flags);
2275         adprecovery = instance->adprecovery;
2276         spin_unlock_irqrestore(&instance->hba_lock, flags);
2277
2278         if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
2279
2280                 INIT_LIST_HEAD(&clist_local);
2281                 spin_lock_irqsave(&instance->hba_lock, flags);
2282                 list_splice_init(&instance->internal_reset_pending_q,
2283                                 &clist_local);
2284                 spin_unlock_irqrestore(&instance->hba_lock, flags);
2285
2286                 printk(KERN_NOTICE "megasas: HBA reset wait ...\n");
2287                 for (i = 0; i < wait_time; i++) {
2288                         msleep(1000);
2289                         spin_lock_irqsave(&instance->hba_lock, flags);
2290                         adprecovery = instance->adprecovery;
2291                         spin_unlock_irqrestore(&instance->hba_lock, flags);
2292                         if (adprecovery == MEGASAS_HBA_OPERATIONAL)
2293                                 break;
2294                 }
2295
2296                 if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
2297                         printk(KERN_NOTICE "megasas: reset: Stopping HBA.\n");
2298                         spin_lock_irqsave(&instance->hba_lock, flags);
2299                         instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
2300                         spin_unlock_irqrestore(&instance->hba_lock, flags);
2301                         return FAILED;
2302                 }
2303
2304                 reset_index     = 0;
2305                 while (!list_empty(&clist_local)) {
2306                         reset_cmd       = list_entry((&clist_local)->next,
2307                                                 struct megasas_cmd, list);
2308                         list_del_init(&reset_cmd->list);
2309                         if (reset_cmd->scmd) {
2310                                 reset_cmd->scmd->result = DID_RESET << 16;
2311                                 printk(KERN_NOTICE "%d:%p reset [%02x]\n",
2312                                         reset_index, reset_cmd,
2313                                         reset_cmd->scmd->cmnd[0]);
2314
2315                                 reset_cmd->scmd->scsi_done(reset_cmd->scmd);
2316                                 megasas_return_cmd(instance, reset_cmd);
2317                         } else if (reset_cmd->sync_cmd) {
2318                                 printk(KERN_NOTICE "megasas:%p synch cmds"
2319                                                 "reset queue\n",
2320                                                 reset_cmd);
2321
2322                                 reset_cmd->cmd_status = ENODATA;
2323                                 instance->instancet->fire_cmd(instance,
2324                                                 reset_cmd->frame_phys_addr,
2325                                                 0, instance->reg_set);
2326                         } else {
2327                                 printk(KERN_NOTICE "megasas: %p unexpected"
2328                                         "cmds lst\n",
2329                                         reset_cmd);
2330                         }
2331                         reset_index++;
2332                 }
2333
2334                 return SUCCESS;
2335         }
2336
2337         for (i = 0; i < resetwaittime; i++) {
2338
2339                 int outstanding = atomic_read(&instance->fw_outstanding);
2340
2341                 if (!outstanding)
2342                         break;
2343
2344                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
2345                         printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
2346                                "commands to complete\n",i,outstanding);
2347                         /*
2348                          * Call cmd completion routine. Cmd to be
2349                          * be completed directly without depending on isr.
2350                          */
2351                         megasas_complete_cmd_dpc((unsigned long)instance);
2352                 }
2353
2354                 msleep(1000);
2355         }
2356
2357         i = 0;
2358         kill_adapter_flag = 0;
2359         do {
2360                 fw_state = instance->instancet->read_fw_status_reg(
2361                                         instance->reg_set) & MFI_STATE_MASK;
2362                 if ((fw_state == MFI_STATE_FAULT) &&
2363                         (instance->disableOnlineCtrlReset == 0)) {
2364                         if (i == 3) {
2365                                 kill_adapter_flag = 2;
2366                                 break;
2367                         }
2368                         megasas_do_ocr(instance);
2369                         kill_adapter_flag = 1;
2370
2371                         /* wait for 1 secs to let FW finish the pending cmds */
2372                         msleep(1000);
2373                 }
2374                 i++;
2375         } while (i <= 3);
2376
2377         if (atomic_read(&instance->fw_outstanding) &&
2378                                         !kill_adapter_flag) {
2379                 if (instance->disableOnlineCtrlReset == 0) {
2380
2381                         megasas_do_ocr(instance);
2382
2383                         /* wait for 5 secs to let FW finish the pending cmds */
2384                         for (i = 0; i < wait_time; i++) {
2385                                 int outstanding =
2386                                         atomic_read(&instance->fw_outstanding);
2387                                 if (!outstanding)
2388                                         return SUCCESS;
2389                                 msleep(1000);
2390                         }
2391                 }
2392         }
2393
2394         if (atomic_read(&instance->fw_outstanding) ||
2395                                         (kill_adapter_flag == 2)) {
2396                 printk(KERN_NOTICE "megaraid_sas: pending cmds after reset\n");
2397                 /*
2398                 * Send signal to FW to stop processing any pending cmds.
2399                 * The controller will be taken offline by the OS now.
2400                 */
2401                 if ((instance->pdev->device ==
2402                         PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2403                         (instance->pdev->device ==
2404                         PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
2405                         writel(MFI_STOP_ADP,
2406                                 &instance->reg_set->doorbell);
2407                 } else {
2408                         writel(MFI_STOP_ADP,
2409                                 &instance->reg_set->inbound_doorbell);
2410                 }
2411                 megasas_dump_pending_frames(instance);
2412                 spin_lock_irqsave(&instance->hba_lock, flags);
2413                 instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
2414                 spin_unlock_irqrestore(&instance->hba_lock, flags);
2415                 return FAILED;
2416         }
2417
2418         printk(KERN_NOTICE "megaraid_sas: no pending cmds after reset\n");
2419
2420         return SUCCESS;
2421 }
2422
2423 /**
2424  * megasas_generic_reset -      Generic reset routine
2425  * @scmd:                       Mid-layer SCSI command
2426  *
2427  * This routine implements a generic reset handler for device, bus and host
2428  * reset requests. Device, bus and host specific reset handlers can use this
2429  * function after they do their specific tasks.
2430  */
2431 static int megasas_generic_reset(struct scsi_cmnd *scmd)
2432 {
2433         int ret_val;
2434         struct megasas_instance *instance;
2435
2436         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2437
2438         scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n",
2439                  scmd->cmnd[0], scmd->retries);
2440
2441         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
2442                 printk(KERN_ERR "megasas: cannot recover from previous reset "
2443                        "failures\n");
2444                 return FAILED;
2445         }
2446
2447         ret_val = megasas_wait_for_outstanding(instance);
2448         if (ret_val == SUCCESS)
2449                 printk(KERN_NOTICE "megasas: reset successful \n");
2450         else
2451                 printk(KERN_ERR "megasas: failed to do reset\n");
2452
2453         return ret_val;
2454 }
2455
2456 /**
2457  * megasas_reset_timer - quiesce the adapter if required
2458  * @scmd:               scsi cmnd
2459  *
2460  * Sets the FW busy flag and reduces the host->can_queue if the
2461  * cmd has not been completed within the timeout period.
2462  */
2463 static enum
2464 blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
2465 {
2466         struct megasas_instance *instance;
2467         unsigned long flags;
2468
2469         if (time_after(jiffies, scmd->jiffies_at_alloc +
2470                                 (MEGASAS_DEFAULT_CMD_TIMEOUT * 2) * HZ)) {
2471                 return BLK_EH_NOT_HANDLED;
2472         }
2473
2474         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2475         if (!(instance->flag & MEGASAS_FW_BUSY)) {
2476                 /* FW is busy, throttle IO */
2477                 spin_lock_irqsave(instance->host->host_lock, flags);
2478
2479                 instance->host->can_queue = instance->throttlequeuedepth;
2480                 instance->last_time = jiffies;
2481                 instance->flag |= MEGASAS_FW_BUSY;
2482
2483                 spin_unlock_irqrestore(instance->host->host_lock, flags);
2484         }
2485         return BLK_EH_RESET_TIMER;
2486 }
2487
2488 /**
2489  * megasas_reset_device -       Device reset handler entry point
2490  */
2491 static int megasas_reset_device(struct scsi_cmnd *scmd)
2492 {
2493         int ret;
2494
2495         /*
2496          * First wait for all commands to complete
2497          */
2498         ret = megasas_generic_reset(scmd);
2499
2500         return ret;
2501 }
2502
2503 /**
2504  * megasas_reset_bus_host -     Bus & host reset handler entry point
2505  */
2506 static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
2507 {
2508         int ret;
2509         struct megasas_instance *instance;
2510         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2511
2512         /*
2513          * First wait for all commands to complete
2514          */
2515         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
2516             (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
2517             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
2518             (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY))
2519                 ret = megasas_reset_fusion(scmd->device->host, 1);
2520         else
2521                 ret = megasas_generic_reset(scmd);
2522
2523         return ret;
2524 }
2525
2526 /**
2527  * megasas_bios_param - Returns disk geometry for a disk
2528  * @sdev:               device handle
2529  * @bdev:               block device
2530  * @capacity:           drive capacity
2531  * @geom:               geometry parameters
2532  */
2533 static int
2534 megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
2535                  sector_t capacity, int geom[])
2536 {
2537         int heads;
2538         int sectors;
2539         sector_t cylinders;
2540         unsigned long tmp;
2541         /* Default heads (64) & sectors (32) */
2542         heads = 64;
2543         sectors = 32;
2544
2545         tmp = heads * sectors;
2546         cylinders = capacity;
2547
2548         sector_div(cylinders, tmp);
2549
2550         /*
2551          * Handle extended translation size for logical drives > 1Gb
2552          */
2553
2554         if (capacity >= 0x200000) {
2555                 heads = 255;
2556                 sectors = 63;
2557                 tmp = heads*sectors;
2558                 cylinders = capacity;
2559                 sector_div(cylinders, tmp);
2560         }
2561
2562         geom[0] = heads;
2563         geom[1] = sectors;
2564         geom[2] = cylinders;
2565
2566         return 0;
2567 }
2568
2569 static void megasas_aen_polling(struct work_struct *work);
2570
2571 /**
2572  * megasas_service_aen -        Processes an event notification
2573  * @instance:                   Adapter soft state
2574  * @cmd:                        AEN command completed by the ISR
2575  *
2576  * For AEN, driver sends a command down to FW that is held by the FW till an
2577  * event occurs. When an event of interest occurs, FW completes the command
2578  * that it was previously holding.
2579  *
2580  * This routines sends SIGIO signal to processes that have registered with the
2581  * driver for AEN.
2582  */
2583 static void
2584 megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
2585 {
2586         unsigned long flags;
2587         /*
2588          * Don't signal app if it is just an aborted previously registered aen
2589          */
2590         if ((!cmd->abort_aen) && (instance->unload == 0)) {
2591                 spin_lock_irqsave(&poll_aen_lock, flags);
2592                 megasas_poll_wait_aen = 1;
2593                 spin_unlock_irqrestore(&poll_aen_lock, flags);
2594                 wake_up(&megasas_poll_wait);
2595                 kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
2596         }
2597         else
2598                 cmd->abort_aen = 0;
2599
2600         instance->aen_cmd = NULL;
2601
2602         megasas_return_cmd(instance, cmd);
2603
2604         if ((instance->unload == 0) &&
2605                 ((instance->issuepend_done == 1))) {
2606                 struct megasas_aen_event *ev;
2607                 ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
2608                 if (!ev) {
2609                         printk(KERN_ERR "megasas_service_aen: out of memory\n");
2610                 } else {
2611                         ev->instance = instance;
2612                         instance->ev = ev;
2613                         INIT_DELAYED_WORK(&ev->hotplug_work,
2614                                           megasas_aen_polling);
2615                         schedule_delayed_work(&ev->hotplug_work, 0);
2616                 }
2617         }
2618 }
2619
2620 static ssize_t
2621 megasas_fw_crash_buffer_store(struct device *cdev,
2622         struct device_attribute *attr, const char *buf, size_t count)
2623 {
2624         struct Scsi_Host *shost = class_to_shost(cdev);
2625         struct megasas_instance *instance =
2626                 (struct megasas_instance *) shost->hostdata;
2627         int val = 0;
2628         unsigned long flags;
2629
2630         if (kstrtoint(buf, 0, &val) != 0)
2631                 return -EINVAL;
2632
2633         spin_lock_irqsave(&instance->crashdump_lock, flags);
2634         instance->fw_crash_buffer_offset = val;
2635         spin_unlock_irqrestore(&instance->crashdump_lock, flags);
2636         return strlen(buf);
2637 }
2638
2639 static ssize_t
2640 megasas_fw_crash_buffer_show(struct device *cdev,
2641         struct device_attribute *attr, char *buf)
2642 {
2643         struct Scsi_Host *shost = class_to_shost(cdev);
2644         struct megasas_instance *instance =
2645                 (struct megasas_instance *) shost->hostdata;
2646         u32 size;
2647         unsigned long buff_addr;
2648         unsigned long dmachunk = CRASH_DMA_BUF_SIZE;
2649         unsigned long src_addr;
2650         unsigned long flags;
2651         u32 buff_offset;
2652
2653         spin_lock_irqsave(&instance->crashdump_lock, flags);
2654         buff_offset = instance->fw_crash_buffer_offset;
2655         if (!instance->crash_dump_buf &&
2656                 !((instance->fw_crash_state == AVAILABLE) ||
2657                 (instance->fw_crash_state == COPYING))) {
2658                 dev_err(&instance->pdev->dev,
2659                         "Firmware crash dump is not available\n");
2660                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
2661                 return -EINVAL;
2662         }
2663
2664         buff_addr = (unsigned long) buf;
2665
2666         if (buff_offset >
2667                 (instance->fw_crash_buffer_size * dmachunk)) {
2668                 dev_err(&instance->pdev->dev,
2669                         "Firmware crash dump offset is out of range\n");
2670                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
2671                 return 0;
2672         }
2673
2674         size = (instance->fw_crash_buffer_size * dmachunk) - buff_offset;
2675         size = (size >= PAGE_SIZE) ? (PAGE_SIZE - 1) : size;
2676
2677         src_addr = (unsigned long)instance->crash_buf[buff_offset / dmachunk] +
2678                 (buff_offset % dmachunk);
2679         memcpy(buf, (void *)src_addr,  size);
2680         spin_unlock_irqrestore(&instance->crashdump_lock, flags);
2681
2682         return size;
2683 }
2684
2685 static ssize_t
2686 megasas_fw_crash_buffer_size_show(struct device *cdev,
2687         struct device_attribute *attr, char *buf)
2688 {
2689         struct Scsi_Host *shost = class_to_shost(cdev);
2690         struct megasas_instance *instance =
2691                 (struct megasas_instance *) shost->hostdata;
2692
2693         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)
2694                 ((instance->fw_crash_buffer_size) * 1024 * 1024)/PAGE_SIZE);
2695 }
2696
2697 static ssize_t
2698 megasas_fw_crash_state_store(struct device *cdev,
2699         struct device_attribute *attr, const char *buf, size_t count)
2700 {
2701         struct Scsi_Host *shost = class_to_shost(cdev);
2702         struct megasas_instance *instance =
2703                 (struct megasas_instance *) shost->hostdata;
2704         int val = 0;
2705         unsigned long flags;
2706
2707         if (kstrtoint(buf, 0, &val) != 0)
2708                 return -EINVAL;
2709
2710         if ((val <= AVAILABLE || val > COPY_ERROR)) {
2711                 dev_err(&instance->pdev->dev, "application updates invalid "
2712                         "firmware crash state\n");
2713                 return -EINVAL;
2714         }
2715
2716         instance->fw_crash_state = val;
2717
2718         if ((val == COPIED) || (val == COPY_ERROR)) {
2719                 spin_lock_irqsave(&instance->crashdump_lock, flags);
2720                 megasas_free_host_crash_buffer(instance);
2721                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
2722                 if (val == COPY_ERROR)
2723                         dev_info(&instance->pdev->dev, "application failed to "
2724                                 "copy Firmware crash dump\n");
2725                 else
2726                         dev_info(&instance->pdev->dev, "Firmware crash dump "
2727                                 "copied successfully\n");
2728         }
2729         return strlen(buf);
2730 }
2731
2732 static ssize_t
2733 megasas_fw_crash_state_show(struct device *cdev,
2734         struct device_attribute *attr, char *buf)
2735 {
2736         struct Scsi_Host *shost = class_to_shost(cdev);
2737         struct megasas_instance *instance =
2738                 (struct megasas_instance *) shost->hostdata;
2739         return snprintf(buf, PAGE_SIZE, "%d\n", instance->fw_crash_state);
2740 }
2741
2742 static ssize_t
2743 megasas_page_size_show(struct device *cdev,
2744         struct device_attribute *attr, char *buf)
2745 {
2746         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)PAGE_SIZE - 1);
2747 }
2748
2749 static DEVICE_ATTR(fw_crash_buffer, S_IRUGO | S_IWUSR,
2750         megasas_fw_crash_buffer_show, megasas_fw_crash_buffer_store);
2751 static DEVICE_ATTR(fw_crash_buffer_size, S_IRUGO,
2752         megasas_fw_crash_buffer_size_show, NULL);
2753 static DEVICE_ATTR(fw_crash_state, S_IRUGO | S_IWUSR,
2754         megasas_fw_crash_state_show, megasas_fw_crash_state_store);
2755 static DEVICE_ATTR(page_size, S_IRUGO,
2756         megasas_page_size_show, NULL);
2757
2758 struct device_attribute *megaraid_host_attrs[] = {
2759         &dev_attr_fw_crash_buffer_size,
2760         &dev_attr_fw_crash_buffer,
2761         &dev_attr_fw_crash_state,
2762         &dev_attr_page_size,
2763         NULL,
2764 };
2765
2766 /*
2767  * Scsi host template for megaraid_sas driver
2768  */
2769 static struct scsi_host_template megasas_template = {
2770
2771         .module = THIS_MODULE,
2772         .name = "Avago SAS based MegaRAID driver",
2773         .proc_name = "megaraid_sas",
2774         .slave_configure = megasas_slave_configure,
2775         .slave_alloc = megasas_slave_alloc,
2776         .queuecommand = megasas_queue_command,
2777         .eh_device_reset_handler = megasas_reset_device,
2778         .eh_bus_reset_handler = megasas_reset_bus_host,
2779         .eh_host_reset_handler = megasas_reset_bus_host,
2780         .eh_timed_out = megasas_reset_timer,
2781         .shost_attrs = megaraid_host_attrs,
2782         .bios_param = megasas_bios_param,
2783         .use_clustering = ENABLE_CLUSTERING,
2784         .change_queue_depth = scsi_change_queue_depth,
2785         .no_write_same = 1,
2786 };
2787
2788 /**
2789  * megasas_complete_int_cmd -   Completes an internal command
2790  * @instance:                   Adapter soft state
2791  * @cmd:                        Command to be completed
2792  *
2793  * The megasas_issue_blocked_cmd() function waits for a command to complete
2794  * after it issues a command. This function wakes up that waiting routine by
2795  * calling wake_up() on the wait queue.
2796  */
2797 static void
2798 megasas_complete_int_cmd(struct megasas_instance *instance,
2799                          struct megasas_cmd *cmd)
2800 {
2801         cmd->cmd_status = cmd->frame->io.cmd_status;
2802
2803         if (cmd->cmd_status == ENODATA) {
2804                 cmd->cmd_status = 0;
2805         }
2806         wake_up(&instance->int_cmd_wait_q);
2807 }
2808
2809 /**
2810  * megasas_complete_abort -     Completes aborting a command
2811  * @instance:                   Adapter soft state
2812  * @cmd:                        Cmd that was issued to abort another cmd
2813  *
2814  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
2815  * after it issues an abort on a previously issued command. This function
2816  * wakes up all functions waiting on the same wait queue.
2817  */
2818 static void
2819 megasas_complete_abort(struct megasas_instance *instance,
2820                        struct megasas_cmd *cmd)
2821 {
2822         if (cmd->sync_cmd) {
2823                 cmd->sync_cmd = 0;
2824                 cmd->cmd_status = 0;
2825                 wake_up(&instance->abort_cmd_wait_q);
2826         }
2827
2828         return;
2829 }
2830
2831 /**
2832  * megasas_complete_cmd -       Completes a command
2833  * @instance:                   Adapter soft state
2834  * @cmd:                        Command to be completed
2835  * @alt_status:                 If non-zero, use this value as status to
2836  *                              SCSI mid-layer instead of the value returned
2837  *                              by the FW. This should be used if caller wants
2838  *                              an alternate status (as in the case of aborted
2839  *                              commands)
2840  */
2841 void
2842 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
2843                      u8 alt_status)
2844 {
2845         int exception = 0;
2846         struct megasas_header *hdr = &cmd->frame->hdr;
2847         unsigned long flags;
2848         struct fusion_context *fusion = instance->ctrl_context;
2849         u32 opcode;
2850
2851         /* flag for the retry reset */
2852         cmd->retry_for_fw_reset = 0;
2853
2854         if (cmd->scmd)
2855                 cmd->scmd->SCp.ptr = NULL;
2856
2857         switch (hdr->cmd) {
2858         case MFI_CMD_INVALID:
2859                 /* Some older 1068 controller FW may keep a pended
2860                    MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
2861                    when booting the kdump kernel.  Ignore this command to
2862                    prevent a kernel panic on shutdown of the kdump kernel. */
2863                 printk(KERN_WARNING "megaraid_sas: MFI_CMD_INVALID command "
2864                        "completed.\n");
2865                 printk(KERN_WARNING "megaraid_sas: If you have a controller "
2866                        "other than PERC5, please upgrade your firmware.\n");
2867                 break;
2868         case MFI_CMD_PD_SCSI_IO:
2869         case MFI_CMD_LD_SCSI_IO:
2870
2871                 /*
2872                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
2873                  * issued either through an IO path or an IOCTL path. If it
2874                  * was via IOCTL, we will send it to internal completion.
2875                  */
2876                 if (cmd->sync_cmd) {
2877                         cmd->sync_cmd = 0;
2878                         megasas_complete_int_cmd(instance, cmd);
2879                         break;
2880                 }
2881
2882         case MFI_CMD_LD_READ:
2883         case MFI_CMD_LD_WRITE:
2884
2885                 if (alt_status) {
2886                         cmd->scmd->result = alt_status << 16;
2887                         exception = 1;
2888                 }
2889
2890                 if (exception) {
2891
2892                         atomic_dec(&instance->fw_outstanding);
2893
2894                         scsi_dma_unmap(cmd->scmd);
2895                         cmd->scmd->scsi_done(cmd->scmd);
2896                         megasas_return_cmd(instance, cmd);
2897
2898                         break;
2899                 }
2900
2901                 switch (hdr->cmd_status) {
2902
2903                 case MFI_STAT_OK:
2904                         cmd->scmd->result = DID_OK << 16;
2905                         break;
2906
2907                 case MFI_STAT_SCSI_IO_FAILED:
2908                 case MFI_STAT_LD_INIT_IN_PROGRESS:
2909                         cmd->scmd->result =
2910                             (DID_ERROR << 16) | hdr->scsi_status;
2911                         break;
2912
2913                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
2914
2915                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
2916
2917                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
2918                                 memset(cmd->scmd->sense_buffer, 0,
2919                                        SCSI_SENSE_BUFFERSIZE);
2920                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
2921                                        hdr->sense_len);
2922
2923                                 cmd->scmd->result |= DRIVER_SENSE << 24;
2924                         }
2925
2926                         break;
2927
2928                 case MFI_STAT_LD_OFFLINE:
2929                 case MFI_STAT_DEVICE_NOT_FOUND:
2930                         cmd->scmd->result = DID_BAD_TARGET << 16;
2931                         break;
2932
2933                 default:
2934                         printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
2935                                hdr->cmd_status);
2936                         cmd->scmd->result = DID_ERROR << 16;
2937                         break;
2938                 }
2939
2940                 atomic_dec(&instance->fw_outstanding);
2941
2942                 scsi_dma_unmap(cmd->scmd);
2943                 cmd->scmd->scsi_done(cmd->scmd);
2944                 megasas_return_cmd(instance, cmd);
2945
2946                 break;
2947
2948         case MFI_CMD_SMP:
2949         case MFI_CMD_STP:
2950         case MFI_CMD_DCMD:
2951                 opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
2952                 /* Check for LD map update */
2953                 if ((opcode == MR_DCMD_LD_MAP_GET_INFO)
2954                         && (cmd->frame->dcmd.mbox.b[1] == 1)) {
2955                         fusion->fast_path_io = 0;
2956                         spin_lock_irqsave(instance->host->host_lock, flags);
2957                         if (cmd->frame->hdr.cmd_status != 0) {
2958                                 if (cmd->frame->hdr.cmd_status !=
2959                                     MFI_STAT_NOT_FOUND)
2960                                         printk(KERN_WARNING "megasas: map sync"
2961                                                "failed, status = 0x%x.\n",
2962                                                cmd->frame->hdr.cmd_status);
2963                                 else {
2964                                         megasas_return_cmd(instance, cmd);
2965                                         spin_unlock_irqrestore(
2966                                                 instance->host->host_lock,
2967                                                 flags);
2968                                         break;
2969                                 }
2970                         } else
2971                                 instance->map_id++;
2972                         megasas_return_cmd(instance, cmd);
2973
2974                         /*
2975                          * Set fast path IO to ZERO.
2976                          * Validate Map will set proper value.
2977                          * Meanwhile all IOs will go as LD IO.
2978                          */
2979                         if (MR_ValidateMapInfo(instance))
2980                                 fusion->fast_path_io = 1;
2981                         else
2982                                 fusion->fast_path_io = 0;
2983                         megasas_sync_map_info(instance);
2984                         spin_unlock_irqrestore(instance->host->host_lock,
2985                                                flags);
2986                         break;
2987                 }
2988                 if (opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
2989                     opcode == MR_DCMD_CTRL_EVENT_GET) {
2990                         spin_lock_irqsave(&poll_aen_lock, flags);
2991                         megasas_poll_wait_aen = 0;
2992                         spin_unlock_irqrestore(&poll_aen_lock, flags);
2993                 }
2994
2995                 /*
2996                  * See if got an event notification
2997                  */
2998                 if (opcode == MR_DCMD_CTRL_EVENT_WAIT)
2999                         megasas_service_aen(instance, cmd);
3000                 else
3001                         megasas_complete_int_cmd(instance, cmd);
3002
3003                 break;
3004
3005         case MFI_CMD_ABORT:
3006                 /*
3007                  * Cmd issued to abort another cmd returned
3008                  */
3009                 megasas_complete_abort(instance, cmd);
3010                 break;
3011
3012         default:
3013                 printk("megasas: Unknown command completed! [0x%X]\n",
3014                        hdr->cmd);
3015                 break;
3016         }
3017 }
3018
3019 /**
3020  * megasas_issue_pending_cmds_again -   issue all pending cmds
3021  *                                      in FW again because of the fw reset
3022  * @instance:                           Adapter soft state
3023  */
3024 static inline void
3025 megasas_issue_pending_cmds_again(struct megasas_instance *instance)
3026 {
3027         struct megasas_cmd *cmd;
3028         struct list_head clist_local;
3029         union megasas_evt_class_locale class_locale;
3030         unsigned long flags;
3031         u32 seq_num;
3032
3033         INIT_LIST_HEAD(&clist_local);
3034         spin_lock_irqsave(&instance->hba_lock, flags);
3035         list_splice_init(&instance->internal_reset_pending_q, &clist_local);
3036         spin_unlock_irqrestore(&instance->hba_lock, flags);
3037
3038         while (!list_empty(&clist_local)) {
3039                 cmd     = list_entry((&clist_local)->next,
3040                                         struct megasas_cmd, list);
3041                 list_del_init(&cmd->list);
3042
3043                 if (cmd->sync_cmd || cmd->scmd) {
3044                         printk(KERN_NOTICE "megaraid_sas: command %p, %p:%d"
3045                                 "detected to be pending while HBA reset.\n",
3046                                         cmd, cmd->scmd, cmd->sync_cmd);
3047
3048                         cmd->retry_for_fw_reset++;
3049
3050                         if (cmd->retry_for_fw_reset == 3) {
3051                                 printk(KERN_NOTICE "megaraid_sas: cmd %p, %p:%d"
3052                                         "was tried multiple times during reset."
3053                                         "Shutting down the HBA\n",
3054                                         cmd, cmd->scmd, cmd->sync_cmd);
3055                                 instance->instancet->disable_intr(instance);
3056                                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3057                                 megaraid_sas_kill_hba(instance);
3058                                 return;
3059                         }
3060                 }
3061
3062                 if (cmd->sync_cmd == 1) {
3063                         if (cmd->scmd) {
3064                                 printk(KERN_NOTICE "megaraid_sas: unexpected"
3065                                         "cmd attached to internal command!\n");
3066                         }
3067                         printk(KERN_NOTICE "megasas: %p synchronous cmd"
3068                                                 "on the internal reset queue,"
3069                                                 "issue it again.\n", cmd);
3070                         cmd->cmd_status = ENODATA;
3071                         instance->instancet->fire_cmd(instance,
3072                                                         cmd->frame_phys_addr ,
3073                                                         0, instance->reg_set);
3074                 } else if (cmd->scmd) {
3075                         printk(KERN_NOTICE "megasas: %p scsi cmd [%02x]"
3076                         "detected on the internal queue, issue again.\n",
3077                         cmd, cmd->scmd->cmnd[0]);
3078
3079                         atomic_inc(&instance->fw_outstanding);
3080                         instance->instancet->fire_cmd(instance,
3081                                         cmd->frame_phys_addr,
3082                                         cmd->frame_count-1, instance->reg_set);
3083                 } else {
3084                         printk(KERN_NOTICE "megasas: %p unexpected cmd on the"
3085                                 "internal reset defer list while re-issue!!\n",
3086                                 cmd);
3087                 }
3088         }
3089
3090         if (instance->aen_cmd) {
3091                 printk(KERN_NOTICE "megaraid_sas: aen_cmd in def process\n");
3092                 megasas_return_cmd(instance, instance->aen_cmd);
3093
3094                 instance->aen_cmd       = NULL;
3095         }
3096
3097         /*
3098         * Initiate AEN (Asynchronous Event Notification)
3099         */
3100         seq_num = instance->last_seq_num;
3101         class_locale.members.reserved = 0;
3102         class_locale.members.locale = MR_EVT_LOCALE_ALL;
3103         class_locale.members.class = MR_EVT_CLASS_DEBUG;
3104
3105         megasas_register_aen(instance, seq_num, class_locale.word);
3106 }
3107
3108 /**
3109  * Move the internal reset pending commands to a deferred queue.
3110  *
3111  * We move the commands pending at internal reset time to a
3112  * pending queue. This queue would be flushed after successful
3113  * completion of the internal reset sequence. if the internal reset
3114  * did not complete in time, the kernel reset handler would flush
3115  * these commands.
3116  **/
3117 static void
3118 megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
3119 {
3120         struct megasas_cmd *cmd;
3121         int i;
3122         u32 max_cmd = instance->max_fw_cmds;
3123         u32 defer_index;
3124         unsigned long flags;
3125
3126         defer_index     = 0;
3127         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
3128         for (i = 0; i < max_cmd; i++) {
3129                 cmd = instance->cmd_list[i];
3130                 if (cmd->sync_cmd == 1 || cmd->scmd) {
3131                         printk(KERN_NOTICE "megasas: moving cmd[%d]:%p:%d:%p"
3132                                         "on the defer queue as internal\n",
3133                                 defer_index, cmd, cmd->sync_cmd, cmd->scmd);
3134
3135                         if (!list_empty(&cmd->list)) {
3136                                 printk(KERN_NOTICE "megaraid_sas: ERROR while"
3137                                         " moving this cmd:%p, %d %p, it was"
3138                                         "discovered on some list?\n",
3139                                         cmd, cmd->sync_cmd, cmd->scmd);
3140
3141                                 list_del_init(&cmd->list);
3142                         }
3143                         defer_index++;
3144                         list_add_tail(&cmd->list,
3145                                 &instance->internal_reset_pending_q);
3146                 }
3147         }
3148         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
3149 }
3150
3151
3152 static void
3153 process_fw_state_change_wq(struct work_struct *work)
3154 {
3155         struct megasas_instance *instance =
3156                 container_of(work, struct megasas_instance, work_init);
3157         u32 wait;
3158         unsigned long flags;
3159
3160         if (instance->adprecovery != MEGASAS_ADPRESET_SM_INFAULT) {
3161                 printk(KERN_NOTICE "megaraid_sas: error, recovery st %x \n",
3162                                 instance->adprecovery);
3163                 return ;
3164         }
3165
3166         if (instance->adprecovery == MEGASAS_ADPRESET_SM_INFAULT) {
3167                 printk(KERN_NOTICE "megaraid_sas: FW detected to be in fault"
3168                                         "state, restarting it...\n");
3169
3170                 instance->instancet->disable_intr(instance);
3171                 atomic_set(&instance->fw_outstanding, 0);
3172
3173                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3174                 instance->instancet->adp_reset(instance, instance->reg_set);
3175                 atomic_set(&instance->fw_reset_no_pci_access, 0 );
3176
3177                 printk(KERN_NOTICE "megaraid_sas: FW restarted successfully,"
3178                                         "initiating next stage...\n");
3179
3180                 printk(KERN_NOTICE "megaraid_sas: HBA recovery state machine,"
3181                                         "state 2 starting...\n");
3182
3183                 /*waitting for about 20 second before start the second init*/
3184                 for (wait = 0; wait < 30; wait++) {
3185                         msleep(1000);
3186                 }
3187
3188                 if (megasas_transition_to_ready(instance, 1)) {
3189                         printk(KERN_NOTICE "megaraid_sas:adapter not ready\n");
3190
3191                         atomic_set(&instance->fw_reset_no_pci_access, 1);
3192                         megaraid_sas_kill_hba(instance);
3193                         return ;
3194                 }
3195
3196                 if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
3197                         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
3198                         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
3199                         ) {
3200                         *instance->consumer = *instance->producer;
3201                 } else {
3202                         *instance->consumer = 0;
3203                         *instance->producer = 0;
3204                 }
3205
3206                 megasas_issue_init_mfi(instance);
3207
3208                 spin_lock_irqsave(&instance->hba_lock, flags);
3209                 instance->adprecovery   = MEGASAS_HBA_OPERATIONAL;
3210                 spin_unlock_irqrestore(&instance->hba_lock, flags);
3211                 instance->instancet->enable_intr(instance);
3212
3213                 megasas_issue_pending_cmds_again(instance);
3214                 instance->issuepend_done = 1;
3215         }
3216         return ;
3217 }
3218
3219 /**
3220  * megasas_deplete_reply_queue -        Processes all completed commands
3221  * @instance:                           Adapter soft state
3222  * @alt_status:                         Alternate status to be returned to
3223  *                                      SCSI mid-layer instead of the status
3224  *                                      returned by the FW
3225  * Note: this must be called with hba lock held
3226  */
3227 static int
3228 megasas_deplete_reply_queue(struct megasas_instance *instance,
3229                                         u8 alt_status)
3230 {
3231         u32 mfiStatus;
3232         u32 fw_state;
3233
3234         if ((mfiStatus = instance->instancet->check_reset(instance,
3235                                         instance->reg_set)) == 1) {
3236                 return IRQ_HANDLED;
3237         }
3238
3239         if ((mfiStatus = instance->instancet->clear_intr(
3240                                                 instance->reg_set)
3241                                                 ) == 0) {
3242                 /* Hardware may not set outbound_intr_status in MSI-X mode */
3243                 if (!instance->msix_vectors)
3244                         return IRQ_NONE;
3245         }
3246
3247         instance->mfiStatus = mfiStatus;
3248
3249         if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
3250                 fw_state = instance->instancet->read_fw_status_reg(
3251                                 instance->reg_set) & MFI_STATE_MASK;
3252
3253                 if (fw_state != MFI_STATE_FAULT) {
3254                         printk(KERN_NOTICE "megaraid_sas: fw state:%x\n",
3255                                                 fw_state);
3256                 }
3257
3258                 if ((fw_state == MFI_STATE_FAULT) &&
3259                                 (instance->disableOnlineCtrlReset == 0)) {
3260                         printk(KERN_NOTICE "megaraid_sas: wait adp restart\n");
3261
3262                         if ((instance->pdev->device ==
3263                                         PCI_DEVICE_ID_LSI_SAS1064R) ||
3264                                 (instance->pdev->device ==
3265                                         PCI_DEVICE_ID_DELL_PERC5) ||
3266                                 (instance->pdev->device ==
3267                                         PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
3268
3269                                 *instance->consumer =
3270                                         cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
3271                         }
3272
3273
3274                         instance->instancet->disable_intr(instance);
3275                         instance->adprecovery   = MEGASAS_ADPRESET_SM_INFAULT;
3276                         instance->issuepend_done = 0;
3277
3278                         atomic_set(&instance->fw_outstanding, 0);
3279                         megasas_internal_reset_defer_cmds(instance);
3280
3281                         printk(KERN_NOTICE "megasas: fwState=%x, stage:%d\n",
3282                                         fw_state, instance->adprecovery);
3283
3284                         schedule_work(&instance->work_init);
3285                         return IRQ_HANDLED;
3286
3287                 } else {
3288                         printk(KERN_NOTICE "megasas: fwstate:%x, dis_OCR=%x\n",
3289                                 fw_state, instance->disableOnlineCtrlReset);
3290                 }
3291         }
3292
3293         tasklet_schedule(&instance->isr_tasklet);
3294         return IRQ_HANDLED;
3295 }
3296 /**
3297  * megasas_isr - isr entry point
3298  */
3299 static irqreturn_t megasas_isr(int irq, void *devp)
3300 {
3301         struct megasas_irq_context *irq_context = devp;
3302         struct megasas_instance *instance = irq_context->instance;
3303         unsigned long flags;
3304         irqreturn_t     rc;
3305
3306         if (atomic_read(&instance->fw_reset_no_pci_access))
3307                 return IRQ_HANDLED;
3308
3309         spin_lock_irqsave(&instance->hba_lock, flags);
3310         rc =  megasas_deplete_reply_queue(instance, DID_OK);
3311         spin_unlock_irqrestore(&instance->hba_lock, flags);
3312
3313         return rc;
3314 }
3315
3316 /**
3317  * megasas_transition_to_ready -        Move the FW to READY state
3318  * @instance:                           Adapter soft state
3319  *
3320  * During the initialization, FW passes can potentially be in any one of
3321  * several possible states. If the FW in operational, waiting-for-handshake
3322  * states, driver must take steps to bring it to ready state. Otherwise, it
3323  * has to wait for the ready state.
3324  */
3325 int
3326 megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
3327 {
3328         int i;
3329         u8 max_wait;
3330         u32 fw_state;
3331         u32 cur_state;
3332         u32 abs_state, curr_abs_state;
3333
3334         abs_state = instance->instancet->read_fw_status_reg(instance->reg_set);
3335         fw_state = abs_state & MFI_STATE_MASK;
3336
3337         if (fw_state != MFI_STATE_READY)
3338                 printk(KERN_INFO "megasas: Waiting for FW to come to ready"
3339                        " state\n");
3340
3341         while (fw_state != MFI_STATE_READY) {
3342
3343                 switch (fw_state) {
3344
3345                 case MFI_STATE_FAULT:
3346                         printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
3347                         if (ocr) {
3348                                 max_wait = MEGASAS_RESET_WAIT_TIME;
3349                                 cur_state = MFI_STATE_FAULT;
3350                                 break;
3351                         } else
3352                                 return -ENODEV;
3353
3354                 case MFI_STATE_WAIT_HANDSHAKE:
3355                         /*
3356                          * Set the CLR bit in inbound doorbell
3357                          */
3358                         if ((instance->pdev->device ==
3359                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3360                                 (instance->pdev->device ==
3361                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
3362                                 (instance->pdev->device ==
3363                                 PCI_DEVICE_ID_LSI_FUSION) ||
3364                                 (instance->pdev->device ==
3365                                 PCI_DEVICE_ID_LSI_PLASMA) ||
3366                                 (instance->pdev->device ==
3367                                 PCI_DEVICE_ID_LSI_INVADER) ||
3368                                 (instance->pdev->device ==
3369                                 PCI_DEVICE_ID_LSI_FURY)) {
3370                                 writel(
3371                                   MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
3372                                   &instance->reg_set->doorbell);
3373                         } else {
3374                                 writel(
3375                                     MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
3376                                         &instance->reg_set->inbound_doorbell);
3377                         }
3378
3379                         max_wait = MEGASAS_RESET_WAIT_TIME;
3380                         cur_state = MFI_STATE_WAIT_HANDSHAKE;
3381                         break;
3382
3383                 case MFI_STATE_BOOT_MESSAGE_PENDING:
3384                         if ((instance->pdev->device ==
3385                              PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3386                                 (instance->pdev->device ==
3387                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
3388                             (instance->pdev->device ==
3389                              PCI_DEVICE_ID_LSI_FUSION) ||
3390                             (instance->pdev->device ==
3391                              PCI_DEVICE_ID_LSI_PLASMA) ||
3392                             (instance->pdev->device ==
3393                              PCI_DEVICE_ID_LSI_INVADER) ||
3394                             (instance->pdev->device ==
3395                              PCI_DEVICE_ID_LSI_FURY)) {
3396                                 writel(MFI_INIT_HOTPLUG,
3397                                        &instance->reg_set->doorbell);
3398                         } else
3399                                 writel(MFI_INIT_HOTPLUG,
3400                                         &instance->reg_set->inbound_doorbell);
3401
3402                         max_wait = MEGASAS_RESET_WAIT_TIME;
3403                         cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
3404                         break;
3405
3406                 case MFI_STATE_OPERATIONAL:
3407                         /*
3408                          * Bring it to READY state; assuming max wait 10 secs
3409                          */
3410                         instance->instancet->disable_intr(instance);
3411                         if ((instance->pdev->device ==
3412                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3413                                 (instance->pdev->device ==
3414                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)  ||
3415                                 (instance->pdev->device
3416                                         == PCI_DEVICE_ID_LSI_FUSION) ||
3417                                 (instance->pdev->device
3418                                         == PCI_DEVICE_ID_LSI_PLASMA) ||
3419                                 (instance->pdev->device
3420                                         == PCI_DEVICE_ID_LSI_INVADER) ||
3421                                 (instance->pdev->device
3422                                         == PCI_DEVICE_ID_LSI_FURY)) {
3423                                 writel(MFI_RESET_FLAGS,
3424                                         &instance->reg_set->doorbell);
3425                                 if ((instance->pdev->device ==
3426                                         PCI_DEVICE_ID_LSI_FUSION) ||
3427                                         (instance->pdev->device ==
3428                                         PCI_DEVICE_ID_LSI_PLASMA) ||
3429                                         (instance->pdev->device ==
3430                                         PCI_DEVICE_ID_LSI_INVADER) ||
3431                                         (instance->pdev->device ==
3432                                         PCI_DEVICE_ID_LSI_FURY)) {
3433                                         for (i = 0; i < (10 * 1000); i += 20) {
3434                                                 if (readl(
3435                                                             &instance->
3436                                                             reg_set->
3437                                                             doorbell) & 1)
3438                                                         msleep(20);
3439                                                 else
3440                                                         break;
3441                                         }
3442                                 }
3443                         } else
3444                                 writel(MFI_RESET_FLAGS,
3445                                         &instance->reg_set->inbound_doorbell);
3446
3447                         max_wait = MEGASAS_RESET_WAIT_TIME;
3448                         cur_state = MFI_STATE_OPERATIONAL;
3449                         break;
3450
3451                 case MFI_STATE_UNDEFINED:
3452                         /*
3453                          * This state should not last for more than 2 seconds
3454                          */
3455                         max_wait = MEGASAS_RESET_WAIT_TIME;
3456                         cur_state = MFI_STATE_UNDEFINED;
3457                         break;
3458
3459                 case MFI_STATE_BB_INIT:
3460                         max_wait = MEGASAS_RESET_WAIT_TIME;
3461                         cur_state = MFI_STATE_BB_INIT;
3462                         break;
3463
3464                 case MFI_STATE_FW_INIT:
3465                         max_wait = MEGASAS_RESET_WAIT_TIME;
3466                         cur_state = MFI_STATE_FW_INIT;
3467                         break;
3468
3469                 case MFI_STATE_FW_INIT_2:
3470                         max_wait = MEGASAS_RESET_WAIT_TIME;
3471                         cur_state = MFI_STATE_FW_INIT_2;
3472                         break;
3473
3474                 case MFI_STATE_DEVICE_SCAN:
3475                         max_wait = MEGASAS_RESET_WAIT_TIME;
3476                         cur_state = MFI_STATE_DEVICE_SCAN;
3477                         break;
3478
3479                 case MFI_STATE_FLUSH_CACHE:
3480                         max_wait = MEGASAS_RESET_WAIT_TIME;
3481                         cur_state = MFI_STATE_FLUSH_CACHE;
3482                         break;
3483
3484                 default:
3485                         printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
3486                                fw_state);
3487                         return -ENODEV;
3488                 }
3489
3490                 /*
3491                  * The cur_state should not last for more than max_wait secs
3492                  */
3493                 for (i = 0; i < (max_wait * 1000); i++) {
3494                         curr_abs_state = instance->instancet->
3495                                 read_fw_status_reg(instance->reg_set);
3496
3497                         if (abs_state == curr_abs_state) {
3498                                 msleep(1);
3499                         } else
3500                                 break;
3501                 }
3502
3503                 /*
3504                  * Return error if fw_state hasn't changed after max_wait
3505                  */
3506                 if (curr_abs_state == abs_state) {
3507                         printk(KERN_DEBUG "FW state [%d] hasn't changed "
3508                                "in %d secs\n", fw_state, max_wait);
3509                         return -ENODEV;
3510                 }
3511
3512                 abs_state = curr_abs_state;
3513                 fw_state = curr_abs_state & MFI_STATE_MASK;
3514         }
3515         printk(KERN_INFO "megasas: FW now in Ready state\n");
3516
3517         return 0;
3518 }
3519
3520 /**
3521  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
3522  * @instance:                           Adapter soft state
3523  */
3524 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
3525 {
3526         int i;
3527         u32 max_cmd = instance->max_mfi_cmds;
3528         struct megasas_cmd *cmd;
3529
3530         if (!instance->frame_dma_pool)
3531                 return;
3532
3533         /*
3534          * Return all frames to pool
3535          */
3536         for (i = 0; i < max_cmd; i++) {
3537
3538                 cmd = instance->cmd_list[i];
3539
3540                 if (cmd->frame)
3541                         pci_pool_free(instance->frame_dma_pool, cmd->frame,
3542                                       cmd->frame_phys_addr);
3543
3544                 if (cmd->sense)
3545                         pci_pool_free(instance->sense_dma_pool, cmd->sense,
3546                                       cmd->sense_phys_addr);
3547         }
3548
3549         /*
3550          * Now destroy the pool itself
3551          */
3552         pci_pool_destroy(instance->frame_dma_pool);
3553         pci_pool_destroy(instance->sense_dma_pool);
3554
3555         instance->frame_dma_pool = NULL;
3556         instance->sense_dma_pool = NULL;
3557 }
3558
3559 /**
3560  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
3561  * @instance:                   Adapter soft state
3562  *
3563  * Each command packet has an embedded DMA memory buffer that is used for
3564  * filling MFI frame and the SG list that immediately follows the frame. This
3565  * function creates those DMA memory buffers for each command packet by using
3566  * PCI pool facility.
3567  */
3568 static int megasas_create_frame_pool(struct megasas_instance *instance)
3569 {
3570         int i;
3571         u32 max_cmd;
3572         u32 sge_sz;
3573         u32 total_sz;
3574         u32 frame_count;
3575         struct megasas_cmd *cmd;
3576
3577         max_cmd = instance->max_mfi_cmds;
3578
3579         /*
3580          * Size of our frame is 64 bytes for MFI frame, followed by max SG
3581          * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
3582          */
3583         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
3584             sizeof(struct megasas_sge32);
3585
3586         if (instance->flag_ieee) {
3587                 sge_sz = sizeof(struct megasas_sge_skinny);
3588         }
3589
3590         /*
3591          * For MFI controllers.
3592          * max_num_sge = 60
3593          * max_sge_sz  = 16 byte (sizeof megasas_sge_skinny)
3594          * Total 960 byte (15 MFI frame of 64 byte)
3595          *
3596          * Fusion adapter require only 3 extra frame.
3597          * max_num_sge = 16 (defined as MAX_IOCTL_SGE)
3598          * max_sge_sz  = 12 byte (sizeof  megasas_sge64)
3599          * Total 192 byte (3 MFI frame of 64 byte)
3600          */
3601         frame_count = instance->ctrl_context ? (3 + 1) : (15 + 1);
3602         total_sz = MEGAMFI_FRAME_SIZE * frame_count;
3603         /*
3604          * Use DMA pool facility provided by PCI layer
3605          */
3606         instance->frame_dma_pool = pci_pool_create("megasas frame pool",
3607                                         instance->pdev, total_sz, 256, 0);
3608
3609         if (!instance->frame_dma_pool) {
3610                 printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
3611                 return -ENOMEM;
3612         }
3613
3614         instance->sense_dma_pool = pci_pool_create("megasas sense pool",
3615                                                    instance->pdev, 128, 4, 0);
3616
3617         if (!instance->sense_dma_pool) {
3618                 printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
3619
3620                 pci_pool_destroy(instance->frame_dma_pool);
3621                 instance->frame_dma_pool = NULL;
3622
3623                 return -ENOMEM;
3624         }
3625
3626         /*
3627          * Allocate and attach a frame to each of the commands in cmd_list.
3628          * By making cmd->index as the context instead of the &cmd, we can
3629          * always use 32bit context regardless of the architecture
3630          */
3631         for (i = 0; i < max_cmd; i++) {
3632
3633                 cmd = instance->cmd_list[i];
3634
3635                 cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
3636                                             GFP_KERNEL, &cmd->frame_phys_addr);
3637
3638                 cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
3639                                             GFP_KERNEL, &cmd->sense_phys_addr);
3640
3641                 /*
3642                  * megasas_teardown_frame_pool() takes care of freeing
3643                  * whatever has been allocated
3644                  */
3645                 if (!cmd->frame || !cmd->sense) {
3646                         printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
3647                         megasas_teardown_frame_pool(instance);
3648                         return -ENOMEM;
3649                 }
3650
3651                 memset(cmd->frame, 0, total_sz);
3652                 cmd->frame->io.context = cpu_to_le32(cmd->index);
3653                 cmd->frame->io.pad_0 = 0;
3654                 if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) &&
3655                     (instance->pdev->device != PCI_DEVICE_ID_LSI_PLASMA) &&
3656                     (instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) &&
3657                         (instance->pdev->device != PCI_DEVICE_ID_LSI_FURY) &&
3658                     (reset_devices))
3659                         cmd->frame->hdr.cmd = MFI_CMD_INVALID;
3660         }
3661
3662         return 0;
3663 }
3664
3665 /**
3666  * megasas_free_cmds -  Free all the cmds in the free cmd pool
3667  * @instance:           Adapter soft state
3668  */
3669 void megasas_free_cmds(struct megasas_instance *instance)
3670 {
3671         int i;
3672         /* First free the MFI frame pool */
3673         megasas_teardown_frame_pool(instance);
3674
3675         /* Free all the commands in the cmd_list */
3676         for (i = 0; i < instance->max_mfi_cmds; i++)
3677
3678                 kfree(instance->cmd_list[i]);
3679
3680         /* Free the cmd_list buffer itself */
3681         kfree(instance->cmd_list);
3682         instance->cmd_list = NULL;
3683
3684         INIT_LIST_HEAD(&instance->cmd_pool);
3685 }
3686
3687 /**
3688  * megasas_alloc_cmds - Allocates the command packets
3689  * @instance:           Adapter soft state
3690  *
3691  * Each command that is issued to the FW, whether IO commands from the OS or
3692  * internal commands like IOCTLs, are wrapped in local data structure called
3693  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
3694  * the FW.
3695  *
3696  * Each frame has a 32-bit field called context (tag). This context is used
3697  * to get back the megasas_cmd from the frame when a frame gets completed in
3698  * the ISR. Typically the address of the megasas_cmd itself would be used as
3699  * the context. But we wanted to keep the differences between 32 and 64 bit
3700  * systems to the mininum. We always use 32 bit integers for the context. In
3701  * this driver, the 32 bit values are the indices into an array cmd_list.
3702  * This array is used only to look up the megasas_cmd given the context. The
3703  * free commands themselves are maintained in a linked list called cmd_pool.
3704  */
3705 int megasas_alloc_cmds(struct megasas_instance *instance)
3706 {
3707         int i;
3708         int j;
3709         u32 max_cmd;
3710         struct megasas_cmd *cmd;
3711         struct fusion_context *fusion;
3712
3713         fusion = instance->ctrl_context;
3714         max_cmd = instance->max_mfi_cmds;
3715
3716         /*
3717          * instance->cmd_list is an array of struct megasas_cmd pointers.
3718          * Allocate the dynamic array first and then allocate individual
3719          * commands.
3720          */
3721         instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
3722
3723         if (!instance->cmd_list) {
3724                 printk(KERN_DEBUG "megasas: out of memory\n");
3725                 return -ENOMEM;
3726         }
3727
3728         memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
3729
3730         for (i = 0; i < max_cmd; i++) {
3731                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
3732                                                 GFP_KERNEL);
3733
3734                 if (!instance->cmd_list[i]) {
3735
3736                         for (j = 0; j < i; j++)
3737                                 kfree(instance->cmd_list[j]);
3738
3739                         kfree(instance->cmd_list);
3740                         instance->cmd_list = NULL;
3741
3742                         return -ENOMEM;
3743                 }
3744         }
3745
3746         for (i = 0; i < max_cmd; i++) {
3747                 cmd = instance->cmd_list[i];
3748                 memset(cmd, 0, sizeof(struct megasas_cmd));
3749                 cmd->index = i;
3750                 cmd->scmd = NULL;
3751                 cmd->instance = instance;
3752
3753                 list_add_tail(&cmd->list, &instance->cmd_pool);
3754         }
3755
3756         /*
3757          * Create a frame pool and assign one frame to each cmd
3758          */
3759         if (megasas_create_frame_pool(instance)) {
3760                 printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
3761                 megasas_free_cmds(instance);
3762         }
3763
3764         return 0;
3765 }
3766
3767 /*
3768  * megasas_get_pd_list_info -   Returns FW's pd_list structure
3769  * @instance:                           Adapter soft state
3770  * @pd_list:                            pd_list structure
3771  *
3772  * Issues an internal command (DCMD) to get the FW's controller PD
3773  * list structure.  This information is mainly used to find out SYSTEM
3774  * supported by the FW.
3775  */
3776 static int
3777 megasas_get_pd_list(struct megasas_instance *instance)
3778 {
3779         int ret = 0, pd_index = 0;
3780         struct megasas_cmd *cmd;
3781         struct megasas_dcmd_frame *dcmd;
3782         struct MR_PD_LIST *ci;
3783         struct MR_PD_ADDRESS *pd_addr;
3784         dma_addr_t ci_h = 0;
3785
3786         cmd = megasas_get_cmd(instance);
3787
3788         if (!cmd) {
3789                 printk(KERN_DEBUG "megasas (get_pd_list): Failed to get cmd\n");
3790                 return -ENOMEM;
3791         }
3792
3793         dcmd = &cmd->frame->dcmd;
3794
3795         ci = pci_alloc_consistent(instance->pdev,
3796                   MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), &ci_h);
3797
3798         if (!ci) {
3799                 printk(KERN_DEBUG "Failed to alloc mem for pd_list\n");
3800                 megasas_return_cmd(instance, cmd);
3801                 return -ENOMEM;
3802         }
3803
3804         memset(ci, 0, sizeof(*ci));
3805         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3806
3807         dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
3808         dcmd->mbox.b[1] = 0;
3809         dcmd->cmd = MFI_CMD_DCMD;
3810         dcmd->cmd_status = 0xFF;
3811         dcmd->sge_count = 1;
3812         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
3813         dcmd->timeout = 0;
3814         dcmd->pad_0 = 0;
3815         dcmd->data_xfer_len = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
3816         dcmd->opcode = cpu_to_le32(MR_DCMD_PD_LIST_QUERY);
3817         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
3818         dcmd->sgl.sge32[0].length = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
3819
3820         if (instance->ctrl_context && !instance->mask_interrupts)
3821                 ret = megasas_issue_blocked_cmd(instance, cmd,
3822                         MEGASAS_BLOCKED_CMD_TIMEOUT);
3823         else
3824                 ret = megasas_issue_polled(instance, cmd);
3825
3826         /*
3827         * the following function will get the instance PD LIST.
3828         */
3829
3830         pd_addr = ci->addr;
3831
3832         if ( ret == 0 &&
3833              (le32_to_cpu(ci->count) <
3834                   (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL))) {
3835
3836                 memset(instance->local_pd_list, 0,
3837                         MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
3838
3839                 for (pd_index = 0; pd_index < le32_to_cpu(ci->count); pd_index++) {
3840
3841                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].tid     =
3842                                 le16_to_cpu(pd_addr->deviceId);
3843                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveType       =
3844                                                         pd_addr->scsiDevType;
3845                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveState      =
3846                                                         MR_PD_STATE_SYSTEM;
3847                         pd_addr++;
3848                 }
3849                 memcpy(instance->pd_list, instance->local_pd_list,
3850                         sizeof(instance->pd_list));
3851         }
3852
3853         pci_free_consistent(instance->pdev,
3854                                 MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
3855                                 ci, ci_h);
3856
3857         megasas_return_cmd(instance, cmd);
3858
3859         return ret;
3860 }
3861
3862 /*
3863  * megasas_get_ld_list_info -   Returns FW's ld_list structure
3864  * @instance:                           Adapter soft state
3865  * @ld_list:                            ld_list structure
3866  *
3867  * Issues an internal command (DCMD) to get the FW's controller PD
3868  * list structure.  This information is mainly used to find out SYSTEM
3869  * supported by the FW.
3870  */
3871 static int
3872 megasas_get_ld_list(struct megasas_instance *instance)
3873 {
3874         int ret = 0, ld_index = 0, ids = 0;
3875         struct megasas_cmd *cmd;
3876         struct megasas_dcmd_frame *dcmd;
3877         struct MR_LD_LIST *ci;
3878         dma_addr_t ci_h = 0;
3879         u32 ld_count;
3880
3881         cmd = megasas_get_cmd(instance);
3882
3883         if (!cmd) {
3884                 printk(KERN_DEBUG "megasas_get_ld_list: Failed to get cmd\n");
3885                 return -ENOMEM;
3886         }
3887
3888         dcmd = &cmd->frame->dcmd;
3889
3890         ci = pci_alloc_consistent(instance->pdev,
3891                                 sizeof(struct MR_LD_LIST),
3892                                 &ci_h);
3893
3894         if (!ci) {
3895                 printk(KERN_DEBUG "Failed to alloc mem in get_ld_list\n");
3896                 megasas_return_cmd(instance, cmd);
3897                 return -ENOMEM;
3898         }
3899
3900         memset(ci, 0, sizeof(*ci));
3901         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3902
3903         if (instance->supportmax256vd)
3904                 dcmd->mbox.b[0] = 1;
3905         dcmd->cmd = MFI_CMD_DCMD;
3906         dcmd->cmd_status = 0xFF;
3907         dcmd->sge_count = 1;
3908         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
3909         dcmd->timeout = 0;
3910         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_LIST));
3911         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_GET_LIST);
3912         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
3913         dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct MR_LD_LIST));
3914         dcmd->pad_0  = 0;
3915
3916         if (instance->ctrl_context && !instance->mask_interrupts)
3917                 ret = megasas_issue_blocked_cmd(instance, cmd,
3918                         MEGASAS_BLOCKED_CMD_TIMEOUT);
3919         else
3920                 ret = megasas_issue_polled(instance, cmd);
3921
3922
3923         ld_count = le32_to_cpu(ci->ldCount);
3924
3925         /* the following function will get the instance PD LIST */
3926
3927         if ((ret == 0) && (ld_count <= instance->fw_supported_vd_count)) {
3928                 memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
3929
3930                 for (ld_index = 0; ld_index < ld_count; ld_index++) {
3931                         if (ci->ldList[ld_index].state != 0) {
3932                                 ids = ci->ldList[ld_index].ref.targetId;
3933                                 instance->ld_ids[ids] =
3934                                         ci->ldList[ld_index].ref.targetId;
3935                         }
3936                 }
3937         }
3938
3939         pci_free_consistent(instance->pdev,
3940                                 sizeof(struct MR_LD_LIST),
3941                                 ci,
3942                                 ci_h);
3943
3944         megasas_return_cmd(instance, cmd);
3945         return ret;
3946 }
3947
3948 /**
3949  * megasas_ld_list_query -      Returns FW's ld_list structure
3950  * @instance:                           Adapter soft state
3951  * @ld_list:                            ld_list structure
3952  *
3953  * Issues an internal command (DCMD) to get the FW's controller PD
3954  * list structure.  This information is mainly used to find out SYSTEM
3955  * supported by the FW.
3956  */
3957 static int
3958 megasas_ld_list_query(struct megasas_instance *instance, u8 query_type)
3959 {
3960         int ret = 0, ld_index = 0, ids = 0;
3961         struct megasas_cmd *cmd;
3962         struct megasas_dcmd_frame *dcmd;
3963         struct MR_LD_TARGETID_LIST *ci;
3964         dma_addr_t ci_h = 0;
3965         u32 tgtid_count;
3966
3967         cmd = megasas_get_cmd(instance);
3968
3969         if (!cmd) {
3970                 printk(KERN_WARNING
3971                        "megasas:(megasas_ld_list_query): Failed to get cmd\n");
3972                 return -ENOMEM;
3973         }
3974
3975         dcmd = &cmd->frame->dcmd;
3976
3977         ci = pci_alloc_consistent(instance->pdev,
3978                                   sizeof(struct MR_LD_TARGETID_LIST), &ci_h);
3979
3980         if (!ci) {
3981                 printk(KERN_WARNING
3982                        "megasas: Failed to alloc mem for ld_list_query\n");
3983                 megasas_return_cmd(instance, cmd);
3984                 return -ENOMEM;
3985         }
3986
3987         memset(ci, 0, sizeof(*ci));
3988         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3989
3990         dcmd->mbox.b[0] = query_type;
3991         if (instance->supportmax256vd)
3992                 dcmd->mbox.b[2] = 1;
3993
3994         dcmd->cmd = MFI_CMD_DCMD;
3995         dcmd->cmd_status = 0xFF;
3996         dcmd->sge_count = 1;
3997         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
3998         dcmd->timeout = 0;
3999         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
4000         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_LIST_QUERY);
4001         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
4002         dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
4003         dcmd->pad_0  = 0;
4004
4005         if (instance->ctrl_context && !instance->mask_interrupts)
4006                 ret = megasas_issue_blocked_cmd(instance, cmd,
4007                         MEGASAS_BLOCKED_CMD_TIMEOUT);
4008         else
4009                 ret = megasas_issue_polled(instance, cmd);
4010
4011         tgtid_count = le32_to_cpu(ci->count);
4012
4013         if ((ret == 0) && (tgtid_count <= (instance->fw_supported_vd_count))) {
4014                 memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
4015                 for (ld_index = 0; ld_index < tgtid_count; ld_index++) {
4016                         ids = ci->targetId[ld_index];
4017                         instance->ld_ids[ids] = ci->targetId[ld_index];
4018                 }
4019
4020         }
4021
4022         pci_free_consistent(instance->pdev, sizeof(struct MR_LD_TARGETID_LIST),
4023                             ci, ci_h);
4024
4025         megasas_return_cmd(instance, cmd);
4026
4027         return ret;
4028 }
4029
4030 /*
4031  * megasas_update_ext_vd_details : Update details w.r.t Extended VD
4032  * instance                      : Controller's instance
4033 */
4034 static void megasas_update_ext_vd_details(struct megasas_instance *instance)
4035 {
4036         struct fusion_context *fusion;
4037         u32 old_map_sz;
4038         u32 new_map_sz;
4039
4040         fusion = instance->ctrl_context;
4041         /* For MFI based controllers return dummy success */
4042         if (!fusion)
4043                 return;
4044
4045         instance->supportmax256vd =
4046                 instance->ctrl_info->adapterOperations3.supportMaxExtLDs;
4047         /* Below is additional check to address future FW enhancement */
4048         if (instance->ctrl_info->max_lds > 64)
4049                 instance->supportmax256vd = 1;
4050
4051         instance->drv_supported_vd_count = MEGASAS_MAX_LD_CHANNELS
4052                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
4053         instance->drv_supported_pd_count = MEGASAS_MAX_PD_CHANNELS
4054                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
4055         if (instance->supportmax256vd) {
4056                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES_EXT;
4057                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
4058         } else {
4059                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
4060                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
4061         }
4062
4063         dev_info(&instance->pdev->dev,
4064                 "firmware type\t: %s\n",
4065                 instance->supportmax256vd ? "Extended VD(240 VD)firmware" :
4066                 "Legacy(64 VD) firmware");
4067
4068         old_map_sz =  sizeof(struct MR_FW_RAID_MAP) +
4069                                 (sizeof(struct MR_LD_SPAN_MAP) *
4070                                 (instance->fw_supported_vd_count - 1));
4071         new_map_sz =  sizeof(struct MR_FW_RAID_MAP_EXT);
4072         fusion->drv_map_sz =  sizeof(struct MR_DRV_RAID_MAP) +
4073                                 (sizeof(struct MR_LD_SPAN_MAP) *
4074                                 (instance->drv_supported_vd_count - 1));
4075
4076         fusion->max_map_sz = max(old_map_sz, new_map_sz);
4077
4078
4079         if (instance->supportmax256vd)
4080                 fusion->current_map_sz = new_map_sz;
4081         else
4082                 fusion->current_map_sz = old_map_sz;
4083
4084 }
4085
4086 /**
4087  * megasas_get_controller_info -        Returns FW's controller structure
4088  * @instance:                           Adapter soft state
4089  *
4090  * Issues an internal command (DCMD) to get the FW's controller structure.
4091  * This information is mainly used to find out the maximum IO transfer per
4092  * command supported by the FW.
4093  */
4094 int
4095 megasas_get_ctrl_info(struct megasas_instance *instance)
4096 {
4097         int ret = 0;
4098         struct megasas_cmd *cmd;
4099         struct megasas_dcmd_frame *dcmd;
4100         struct megasas_ctrl_info *ci;
4101         struct megasas_ctrl_info *ctrl_info;
4102         dma_addr_t ci_h = 0;
4103
4104         ctrl_info = instance->ctrl_info;
4105
4106         cmd = megasas_get_cmd(instance);
4107
4108         if (!cmd) {
4109                 printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
4110                 return -ENOMEM;
4111         }
4112
4113         dcmd = &cmd->frame->dcmd;
4114
4115         ci = pci_alloc_consistent(instance->pdev,
4116                                   sizeof(struct megasas_ctrl_info), &ci_h);
4117
4118         if (!ci) {
4119                 printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
4120                 megasas_return_cmd(instance, cmd);
4121                 return -ENOMEM;
4122         }
4123
4124         memset(ci, 0, sizeof(*ci));
4125         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4126
4127         dcmd->cmd = MFI_CMD_DCMD;
4128         dcmd->cmd_status = 0xFF;
4129         dcmd->sge_count = 1;
4130         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
4131         dcmd->timeout = 0;
4132         dcmd->pad_0 = 0;
4133         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_ctrl_info));
4134         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_GET_INFO);
4135         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
4136         dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct megasas_ctrl_info));
4137         dcmd->mbox.b[0] = 1;
4138
4139         if (instance->ctrl_context && !instance->mask_interrupts)
4140                 ret = megasas_issue_blocked_cmd(instance, cmd,
4141                         MEGASAS_BLOCKED_CMD_TIMEOUT);
4142         else
4143                 ret = megasas_issue_polled(instance, cmd);
4144
4145         if (!ret) {
4146                 memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
4147                 le32_to_cpus((u32 *)&ctrl_info->properties.OnOffProperties);
4148                 le32_to_cpus((u32 *)&ctrl_info->adapterOperations2);
4149                 le32_to_cpus((u32 *)&ctrl_info->adapterOperations3);
4150                 megasas_update_ext_vd_details(instance);
4151                 instance->is_imr = (ctrl_info->memory_size ? 0 : 1);
4152                 dev_info(&instance->pdev->dev,
4153                                 "controller type\t: %s(%dMB)\n",
4154                                 instance->is_imr ? "iMR" : "MR",
4155                                 le16_to_cpu(ctrl_info->memory_size));
4156         }
4157
4158         pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
4159                             ci, ci_h);
4160
4161         megasas_return_cmd(instance, cmd);
4162         return ret;
4163 }
4164
4165 /*
4166  * megasas_set_crash_dump_params -      Sends address of crash dump DMA buffer
4167  *                                      to firmware
4168  *
4169  * @instance:                           Adapter soft state
4170  * @crash_buf_state             -       tell FW to turn ON/OFF crash dump feature
4171                                         MR_CRASH_BUF_TURN_OFF = 0
4172                                         MR_CRASH_BUF_TURN_ON = 1
4173  * @return 0 on success non-zero on failure.
4174  * Issues an internal command (DCMD) to set parameters for crash dump feature.
4175  * Driver will send address of crash dump DMA buffer and set mbox to tell FW
4176  * that driver supports crash dump feature. This DCMD will be sent only if
4177  * crash dump feature is supported by the FW.
4178  *
4179  */
4180 int megasas_set_crash_dump_params(struct megasas_instance *instance,
4181         u8 crash_buf_state)
4182 {
4183         int ret = 0;
4184         struct megasas_cmd *cmd;
4185         struct megasas_dcmd_frame *dcmd;
4186
4187         cmd = megasas_get_cmd(instance);
4188
4189         if (!cmd) {
4190                 dev_err(&instance->pdev->dev, "Failed to get a free cmd\n");
4191                 return -ENOMEM;
4192         }
4193
4194
4195         dcmd = &cmd->frame->dcmd;
4196
4197         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4198         dcmd->mbox.b[0] = crash_buf_state;
4199         dcmd->cmd = MFI_CMD_DCMD;
4200         dcmd->cmd_status = 0xFF;
4201         dcmd->sge_count = 1;
4202         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
4203         dcmd->timeout = 0;
4204         dcmd->pad_0 = 0;
4205         dcmd->data_xfer_len = cpu_to_le32(CRASH_DMA_BUF_SIZE);
4206         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SET_CRASH_DUMP_PARAMS);
4207         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(instance->crash_dump_h);
4208         dcmd->sgl.sge32[0].length = cpu_to_le32(CRASH_DMA_BUF_SIZE);
4209
4210         if (instance->ctrl_context && !instance->mask_interrupts)
4211                 ret = megasas_issue_blocked_cmd(instance, cmd,
4212                         MEGASAS_BLOCKED_CMD_TIMEOUT);
4213         else
4214                 ret = megasas_issue_polled(instance, cmd);
4215
4216         megasas_return_cmd(instance, cmd);
4217         return ret;
4218 }
4219
4220 /**
4221  * megasas_issue_init_mfi -     Initializes the FW
4222  * @instance:           Adapter soft state
4223  *
4224  * Issues the INIT MFI cmd
4225  */
4226 static int
4227 megasas_issue_init_mfi(struct megasas_instance *instance)
4228 {
4229         __le32 context;
4230
4231         struct megasas_cmd *cmd;
4232
4233         struct megasas_init_frame *init_frame;
4234         struct megasas_init_queue_info *initq_info;
4235         dma_addr_t init_frame_h;
4236         dma_addr_t initq_info_h;
4237
4238         /*
4239          * Prepare a init frame. Note the init frame points to queue info
4240          * structure. Each frame has SGL allocated after first 64 bytes. For
4241          * this frame - since we don't need any SGL - we use SGL's space as
4242          * queue info structure
4243          *
4244          * We will not get a NULL command below. We just created the pool.
4245          */
4246         cmd = megasas_get_cmd(instance);
4247
4248         init_frame = (struct megasas_init_frame *)cmd->frame;
4249         initq_info = (struct megasas_init_queue_info *)
4250                 ((unsigned long)init_frame + 64);
4251
4252         init_frame_h = cmd->frame_phys_addr;
4253         initq_info_h = init_frame_h + 64;
4254
4255         context = init_frame->context;
4256         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
4257         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
4258         init_frame->context = context;
4259
4260         initq_info->reply_queue_entries = cpu_to_le32(instance->max_fw_cmds + 1);
4261         initq_info->reply_queue_start_phys_addr_lo = cpu_to_le32(instance->reply_queue_h);
4262
4263         initq_info->producer_index_phys_addr_lo = cpu_to_le32(instance->producer_h);
4264         initq_info->consumer_index_phys_addr_lo = cpu_to_le32(instance->consumer_h);
4265
4266         init_frame->cmd = MFI_CMD_INIT;
4267         init_frame->cmd_status = 0xFF;
4268         init_frame->queue_info_new_phys_addr_lo =
4269                 cpu_to_le32(lower_32_bits(initq_info_h));
4270         init_frame->queue_info_new_phys_addr_hi =
4271                 cpu_to_le32(upper_32_bits(initq_info_h));
4272
4273         init_frame->data_xfer_len = cpu_to_le32(sizeof(struct megasas_init_queue_info));
4274
4275         /*
4276          * disable the intr before firing the init frame to FW
4277          */
4278         instance->instancet->disable_intr(instance);
4279
4280         /*
4281          * Issue the init frame in polled mode
4282          */
4283
4284         if (megasas_issue_polled(instance, cmd)) {
4285                 printk(KERN_ERR "megasas: Failed to init firmware\n");
4286                 megasas_return_cmd(instance, cmd);
4287                 goto fail_fw_init;
4288         }
4289
4290         megasas_return_cmd(instance, cmd);
4291
4292         return 0;
4293
4294 fail_fw_init:
4295         return -EINVAL;
4296 }
4297
4298 static u32
4299 megasas_init_adapter_mfi(struct megasas_instance *instance)
4300 {
4301         struct megasas_register_set __iomem *reg_set;
4302         u32 context_sz;
4303         u32 reply_q_sz;
4304
4305         reg_set = instance->reg_set;
4306
4307         /*
4308          * Get various operational parameters from status register
4309          */
4310         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
4311         /*
4312          * Reduce the max supported cmds by 1. This is to ensure that the
4313          * reply_q_sz (1 more than the max cmd that driver may send)
4314          * does not exceed max cmds that the FW can support
4315          */
4316         instance->max_fw_cmds = instance->max_fw_cmds-1;
4317         instance->max_mfi_cmds = instance->max_fw_cmds;
4318         instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >>
4319                                         0x10;
4320         /*
4321          * For MFI skinny adapters, MEGASAS_SKINNY_INT_CMDS commands
4322          * are reserved for IOCTL + driver's internal DCMDs.
4323          */
4324         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4325                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
4326                 instance->max_scsi_cmds = (instance->max_fw_cmds -
4327                         MEGASAS_SKINNY_INT_CMDS);
4328                 sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
4329         } else {
4330                 instance->max_scsi_cmds = (instance->max_fw_cmds -
4331                         MEGASAS_INT_CMDS);
4332                 sema_init(&instance->ioctl_sem, (MEGASAS_MFI_IOCTL_CMDS));
4333         }
4334
4335         /*
4336          * Create a pool of commands
4337          */
4338         if (megasas_alloc_cmds(instance))
4339                 goto fail_alloc_cmds;
4340
4341         /*
4342          * Allocate memory for reply queue. Length of reply queue should
4343          * be _one_ more than the maximum commands handled by the firmware.
4344          *
4345          * Note: When FW completes commands, it places corresponding contex
4346          * values in this circular reply queue. This circular queue is a fairly
4347          * typical producer-consumer queue. FW is the producer (of completed
4348          * commands) and the driver is the consumer.
4349          */
4350         context_sz = sizeof(u32);
4351         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
4352
4353         instance->reply_queue = pci_alloc_consistent(instance->pdev,
4354                                                      reply_q_sz,
4355                                                      &instance->reply_queue_h);
4356
4357         if (!instance->reply_queue) {
4358                 printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
4359                 goto fail_reply_queue;
4360         }
4361
4362         if (megasas_issue_init_mfi(instance))
4363                 goto fail_fw_init;
4364
4365         if (megasas_get_ctrl_info(instance)) {
4366                 dev_err(&instance->pdev->dev, "(%d): Could get controller info "
4367                         "Fail from %s %d\n", instance->unique_id,
4368                         __func__, __LINE__);
4369                 goto fail_fw_init;
4370         }
4371
4372         instance->fw_support_ieee = 0;
4373         instance->fw_support_ieee =
4374                 (instance->instancet->read_fw_status_reg(reg_set) &
4375                 0x04000000);
4376
4377         printk(KERN_NOTICE "megasas_init_mfi: fw_support_ieee=%d",
4378                         instance->fw_support_ieee);
4379
4380         if (instance->fw_support_ieee)
4381                 instance->flag_ieee = 1;
4382
4383         return 0;
4384
4385 fail_fw_init:
4386
4387         pci_free_consistent(instance->pdev, reply_q_sz,
4388                             instance->reply_queue, instance->reply_queue_h);
4389 fail_reply_queue:
4390         megasas_free_cmds(instance);
4391
4392 fail_alloc_cmds:
4393         return 1;
4394 }
4395
4396 /*
4397  * megasas_setup_irqs_msix -            register legacy interrupts.
4398  * @instance:                           Adapter soft state
4399  *
4400  * Do not enable interrupt, only setup ISRs.
4401  *
4402  * Return 0 on success.
4403  */
4404 static int
4405 megasas_setup_irqs_ioapic(struct megasas_instance *instance)
4406 {
4407         struct pci_dev *pdev;
4408
4409         pdev = instance->pdev;
4410         instance->irq_context[0].instance = instance;
4411         instance->irq_context[0].MSIxIndex = 0;
4412         if (request_irq(pdev->irq, instance->instancet->service_isr,
4413                 IRQF_SHARED, "megasas", &instance->irq_context[0])) {
4414                 dev_err(&instance->pdev->dev,
4415                                 "Failed to register IRQ from %s %d\n",
4416                                 __func__, __LINE__);
4417                 return -1;
4418         }
4419         return 0;
4420 }
4421
4422 /**
4423  * megasas_setup_irqs_msix -            register MSI-x interrupts.
4424  * @instance:                           Adapter soft state
4425  * @is_probe:                           Driver probe check
4426  *
4427  * Do not enable interrupt, only setup ISRs.
4428  *
4429  * Return 0 on success.
4430  */
4431 static int
4432 megasas_setup_irqs_msix(struct megasas_instance *instance, u8 is_probe)
4433 {
4434         int i, j, cpu;
4435         struct pci_dev *pdev;
4436
4437         pdev = instance->pdev;
4438
4439         /* Try MSI-x */
4440         cpu = cpumask_first(cpu_online_mask);
4441         for (i = 0; i < instance->msix_vectors; i++) {
4442                 instance->irq_context[i].instance = instance;
4443                 instance->irq_context[i].MSIxIndex = i;
4444                 if (request_irq(instance->msixentry[i].vector,
4445                         instance->instancet->service_isr, 0, "megasas",
4446                         &instance->irq_context[i])) {
4447                         dev_err(&instance->pdev->dev,
4448                                 "Failed to register IRQ for vector %d.\n", i);
4449                         for (j = 0; j < i; j++) {
4450                                 if (smp_affinity_enable)
4451                                         irq_set_affinity_hint(
4452                                                 instance->msixentry[j].vector, NULL);
4453                                 free_irq(instance->msixentry[j].vector,
4454                                         &instance->irq_context[j]);
4455                         }
4456                         /* Retry irq register for IO_APIC*/
4457                         instance->msix_vectors = 0;
4458                         if (is_probe)
4459                                 return megasas_setup_irqs_ioapic(instance);
4460                         else
4461                                 return -1;
4462                 }
4463                 if (smp_affinity_enable) {
4464                         if (irq_set_affinity_hint(instance->msixentry[i].vector,
4465                                 get_cpu_mask(cpu)))
4466                                 dev_err(&instance->pdev->dev,
4467                                         "Failed to set affinity hint"
4468                                         " for cpu %d\n", cpu);
4469                         cpu = cpumask_next(cpu, cpu_online_mask);
4470                 }
4471         }
4472         return 0;
4473 }
4474
4475 /*
4476  * megasas_destroy_irqs-                unregister interrupts.
4477  * @instance:                           Adapter soft state
4478  * return:                              void
4479  */
4480 static void
4481 megasas_destroy_irqs(struct megasas_instance *instance) {
4482
4483         int i;
4484
4485         if (instance->msix_vectors)
4486                 for (i = 0; i < instance->msix_vectors; i++) {
4487                         if (smp_affinity_enable)
4488                                 irq_set_affinity_hint(
4489                                         instance->msixentry[i].vector, NULL);
4490                         free_irq(instance->msixentry[i].vector,
4491                                  &instance->irq_context[i]);
4492                 }
4493         else
4494                 free_irq(instance->pdev->irq, &instance->irq_context[0]);
4495 }
4496
4497 /**
4498  * megasas_init_fw -    Initializes the FW
4499  * @instance:           Adapter soft state
4500  *
4501  * This is the main function for initializing firmware
4502  */
4503
4504 static int megasas_init_fw(struct megasas_instance *instance)
4505 {
4506         u32 max_sectors_1;
4507         u32 max_sectors_2;
4508         u32 tmp_sectors, msix_enable, scratch_pad_2;
4509         resource_size_t base_addr;
4510         struct megasas_register_set __iomem *reg_set;
4511         struct megasas_ctrl_info *ctrl_info = NULL;
4512         unsigned long bar_list;
4513         int i, loop, fw_msix_count = 0;
4514         struct IOV_111 *iovPtr;
4515
4516         /* Find first memory bar */
4517         bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
4518         instance->bar = find_first_bit(&bar_list, sizeof(unsigned long));
4519         if (pci_request_selected_regions(instance->pdev, instance->bar,
4520                                          "megasas: LSI")) {
4521                 printk(KERN_DEBUG "megasas: IO memory region busy!\n");
4522                 return -EBUSY;
4523         }
4524
4525         base_addr = pci_resource_start(instance->pdev, instance->bar);
4526         instance->reg_set = ioremap_nocache(base_addr, 8192);
4527
4528         if (!instance->reg_set) {
4529                 printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
4530                 goto fail_ioremap;
4531         }
4532
4533         reg_set = instance->reg_set;
4534
4535         switch (instance->pdev->device) {
4536         case PCI_DEVICE_ID_LSI_FUSION:
4537         case PCI_DEVICE_ID_LSI_PLASMA:
4538         case PCI_DEVICE_ID_LSI_INVADER:
4539         case PCI_DEVICE_ID_LSI_FURY:
4540                 instance->instancet = &megasas_instance_template_fusion;
4541                 break;
4542         case PCI_DEVICE_ID_LSI_SAS1078R:
4543         case PCI_DEVICE_ID_LSI_SAS1078DE:
4544                 instance->instancet = &megasas_instance_template_ppc;
4545                 break;
4546         case PCI_DEVICE_ID_LSI_SAS1078GEN2:
4547         case PCI_DEVICE_ID_LSI_SAS0079GEN2:
4548                 instance->instancet = &megasas_instance_template_gen2;
4549                 break;
4550         case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
4551         case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
4552                 instance->instancet = &megasas_instance_template_skinny;
4553                 break;
4554         case PCI_DEVICE_ID_LSI_SAS1064R:
4555         case PCI_DEVICE_ID_DELL_PERC5:
4556         default:
4557                 instance->instancet = &megasas_instance_template_xscale;
4558                 break;
4559         }
4560
4561         if (megasas_transition_to_ready(instance, 0)) {
4562                 atomic_set(&instance->fw_reset_no_pci_access, 1);
4563                 instance->instancet->adp_reset
4564                         (instance, instance->reg_set);
4565                 atomic_set(&instance->fw_reset_no_pci_access, 0);
4566                 dev_info(&instance->pdev->dev,
4567                         "megasas: FW restarted successfully from %s!\n",
4568                         __func__);
4569
4570                 /*waitting for about 30 second before retry*/
4571                 ssleep(30);
4572
4573                 if (megasas_transition_to_ready(instance, 0))
4574                         goto fail_ready_state;
4575         }
4576
4577         /*
4578          * MSI-X host index 0 is common for all adapter.
4579          * It is used for all MPT based Adapters.
4580          */
4581         instance->reply_post_host_index_addr[0] =
4582                 (u32 __iomem *)((u8 __iomem *)instance->reg_set +
4583                 MPI2_REPLY_POST_HOST_INDEX_OFFSET);
4584
4585         /* Check if MSI-X is supported while in ready state */
4586         msix_enable = (instance->instancet->read_fw_status_reg(reg_set) &
4587                        0x4000000) >> 0x1a;
4588         if (msix_enable && !msix_disable) {
4589                 scratch_pad_2 = readl
4590                         (&instance->reg_set->outbound_scratch_pad_2);
4591                 /* Check max MSI-X vectors */
4592                 if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
4593                     (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA)) {
4594                         instance->msix_vectors = (scratch_pad_2
4595                                 & MR_MAX_REPLY_QUEUES_OFFSET) + 1;
4596                         fw_msix_count = instance->msix_vectors;
4597                         if (msix_vectors)
4598                                 instance->msix_vectors =
4599                                         min(msix_vectors,
4600                                             instance->msix_vectors);
4601                 } else if ((instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)
4602                         || (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY)) {
4603                         /* Invader/Fury supports more than 8 MSI-X */
4604                         instance->msix_vectors = ((scratch_pad_2
4605                                 & MR_MAX_REPLY_QUEUES_EXT_OFFSET)
4606                                 >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1;
4607                         fw_msix_count = instance->msix_vectors;
4608                         /* Save 1-15 reply post index address to local memory
4609                          * Index 0 is already saved from reg offset
4610                          * MPI2_REPLY_POST_HOST_INDEX_OFFSET
4611                          */
4612                         for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) {
4613                                 instance->reply_post_host_index_addr[loop] =
4614                                         (u32 __iomem *)
4615                                         ((u8 __iomem *)instance->reg_set +
4616                                         MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET
4617                                         + (loop * 0x10));
4618                         }
4619                         if (msix_vectors)
4620                                 instance->msix_vectors = min(msix_vectors,
4621                                         instance->msix_vectors);
4622                 } else
4623                         instance->msix_vectors = 1;
4624                 /* Don't bother allocating more MSI-X vectors than cpus */
4625                 instance->msix_vectors = min(instance->msix_vectors,
4626                                              (unsigned int)num_online_cpus());
4627                 for (i = 0; i < instance->msix_vectors; i++)
4628                         instance->msixentry[i].entry = i;
4629                 i = pci_enable_msix_range(instance->pdev, instance->msixentry,
4630                                           1, instance->msix_vectors);
4631                 if (i > 0)
4632                         instance->msix_vectors = i;
4633                 else
4634                         instance->msix_vectors = 0;
4635
4636                 dev_info(&instance->pdev->dev,
4637                         "firmware supports msix\t: (%d)", fw_msix_count);
4638                 dev_info(&instance->pdev->dev,
4639                         "current msix/online cpus\t: (%d/%d)\n",
4640                         instance->msix_vectors, (unsigned int)num_online_cpus());
4641
4642                 if (instance->msix_vectors ?
4643                                 megasas_setup_irqs_msix(instance, 1) :
4644                                 megasas_setup_irqs_ioapic(instance))
4645                         goto fail_setup_irqs;
4646         }
4647
4648         instance->ctrl_info = kzalloc(sizeof(struct megasas_ctrl_info),
4649                                 GFP_KERNEL);
4650         if (instance->ctrl_info == NULL)
4651                 goto fail_init_adapter;
4652
4653         /*
4654          * Below are default value for legacy Firmware.
4655          * non-fusion based controllers
4656          */
4657         instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
4658         instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
4659         /* Get operational params, sge flags, send init cmd to controller */
4660         if (instance->instancet->init_adapter(instance))
4661                 goto fail_init_adapter;
4662         instance->instancet->enable_intr(instance);
4663
4664         printk(KERN_ERR "megasas: INIT adapter done\n");
4665
4666         /** for passthrough
4667         * the following function will get the PD LIST.
4668         */
4669
4670         memset(instance->pd_list, 0 ,
4671                 (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
4672         if (megasas_get_pd_list(instance) < 0) {
4673                 printk(KERN_ERR "megasas: failed to get PD list\n");
4674                 goto fail_get_pd_list;
4675         }
4676
4677         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
4678         if (megasas_ld_list_query(instance,
4679                                   MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
4680                 megasas_get_ld_list(instance);
4681
4682         /*
4683          * Compute the max allowed sectors per IO: The controller info has two
4684          * limits on max sectors. Driver should use the minimum of these two.
4685          *
4686          * 1 << stripe_sz_ops.min = max sectors per strip
4687          *
4688          * Note that older firmwares ( < FW ver 30) didn't report information
4689          * to calculate max_sectors_1. So the number ended up as zero always.
4690          */
4691         tmp_sectors = 0;
4692         ctrl_info = instance->ctrl_info;
4693
4694         max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
4695                 le16_to_cpu(ctrl_info->max_strips_per_io);
4696         max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size);
4697
4698         tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2);
4699
4700         instance->disableOnlineCtrlReset =
4701         ctrl_info->properties.OnOffProperties.disableOnlineCtrlReset;
4702         instance->mpio = ctrl_info->adapterOperations2.mpio;
4703         instance->UnevenSpanSupport =
4704                 ctrl_info->adapterOperations2.supportUnevenSpans;
4705         if (instance->UnevenSpanSupport) {
4706                 struct fusion_context *fusion = instance->ctrl_context;
4707                 if (MR_ValidateMapInfo(instance))
4708                         fusion->fast_path_io = 1;
4709                 else
4710                         fusion->fast_path_io = 0;
4711
4712         }
4713         if (ctrl_info->host_interface.SRIOV) {
4714                 if (!ctrl_info->adapterOperations2.activePassive)
4715                         instance->PlasmaFW111 = 1;
4716
4717                 if (!instance->PlasmaFW111)
4718                         instance->requestorId =
4719                                 ctrl_info->iov.requestorId;
4720                 else {
4721                         iovPtr = (struct IOV_111 *)((unsigned char *)ctrl_info + IOV_111_OFFSET);
4722                         instance->requestorId = iovPtr->requestorId;
4723                 }
4724                 dev_warn(&instance->pdev->dev, "I am VF "
4725                        "requestorId %d\n", instance->requestorId);
4726         }
4727
4728         instance->crash_dump_fw_support =
4729                 ctrl_info->adapterOperations3.supportCrashDump;
4730         instance->crash_dump_drv_support =
4731                 (instance->crash_dump_fw_support &&
4732                 instance->crash_dump_buf);
4733         if (instance->crash_dump_drv_support)
4734                 megasas_set_crash_dump_params(instance,
4735                         MR_CRASH_BUF_TURN_OFF);
4736
4737         else {
4738                 if (instance->crash_dump_buf)
4739                         pci_free_consistent(instance->pdev,
4740                                 CRASH_DMA_BUF_SIZE,
4741                                 instance->crash_dump_buf,
4742                                 instance->crash_dump_h);
4743                 instance->crash_dump_buf = NULL;
4744         }
4745
4746         instance->secure_jbod_support =
4747                 ctrl_info->adapterOperations3.supportSecurityonJBOD;
4748
4749         dev_info(&instance->pdev->dev,
4750                 "pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n",
4751                 le16_to_cpu(ctrl_info->pci.vendor_id),
4752                 le16_to_cpu(ctrl_info->pci.device_id),
4753                 le16_to_cpu(ctrl_info->pci.sub_vendor_id),
4754                 le16_to_cpu(ctrl_info->pci.sub_device_id));
4755         dev_info(&instance->pdev->dev, "unevenspan support      : %s\n",
4756                 instance->UnevenSpanSupport ? "yes" : "no");
4757         dev_info(&instance->pdev->dev, "disable ocr             : %s\n",
4758                 instance->disableOnlineCtrlReset ? "yes" : "no");
4759         dev_info(&instance->pdev->dev, "firmware crash dump     : %s\n",
4760                 instance->crash_dump_drv_support ? "yes" : "no");
4761         dev_info(&instance->pdev->dev, "secure jbod             : %s\n",
4762                 instance->secure_jbod_support ? "yes" : "no");
4763
4764
4765         instance->max_sectors_per_req = instance->max_num_sge *
4766                                                 PAGE_SIZE / 512;
4767         if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
4768                 instance->max_sectors_per_req = tmp_sectors;
4769
4770         /* Check for valid throttlequeuedepth module parameter */
4771         if (throttlequeuedepth &&
4772                         throttlequeuedepth <= instance->max_scsi_cmds)
4773                 instance->throttlequeuedepth = throttlequeuedepth;
4774         else
4775                 instance->throttlequeuedepth =
4776                                 MEGASAS_THROTTLE_QUEUE_DEPTH;
4777
4778         /*
4779         * Setup tasklet for cmd completion
4780         */
4781
4782         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
4783                 (unsigned long)instance);
4784
4785         /* Launch SR-IOV heartbeat timer */
4786         if (instance->requestorId) {
4787                 if (!megasas_sriov_start_heartbeat(instance, 1))
4788                         megasas_start_timer(instance,
4789                                             &instance->sriov_heartbeat_timer,
4790                                             megasas_sriov_heartbeat_handler,
4791                                             MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
4792                 else
4793                         instance->skip_heartbeat_timer_del = 1;
4794         }
4795
4796         return 0;
4797
4798 fail_get_pd_list:
4799         instance->instancet->disable_intr(instance);
4800 fail_init_adapter:
4801         megasas_destroy_irqs(instance);
4802 fail_setup_irqs:
4803         if (instance->msix_vectors)
4804                 pci_disable_msix(instance->pdev);
4805         instance->msix_vectors = 0;
4806 fail_ready_state:
4807         kfree(instance->ctrl_info);
4808         instance->ctrl_info = NULL;
4809         iounmap(instance->reg_set);
4810
4811       fail_ioremap:
4812         pci_release_selected_regions(instance->pdev, instance->bar);
4813
4814         return -EINVAL;
4815 }
4816
4817 /**
4818  * megasas_release_mfi -        Reverses the FW initialization
4819  * @intance:                    Adapter soft state
4820  */
4821 static void megasas_release_mfi(struct megasas_instance *instance)
4822 {
4823         u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
4824
4825         if (instance->reply_queue)
4826                 pci_free_consistent(instance->pdev, reply_q_sz,
4827                             instance->reply_queue, instance->reply_queue_h);
4828
4829         megasas_free_cmds(instance);
4830
4831         iounmap(instance->reg_set);
4832
4833         pci_release_selected_regions(instance->pdev, instance->bar);
4834 }
4835
4836 /**
4837  * megasas_get_seq_num -        Gets latest event sequence numbers
4838  * @instance:                   Adapter soft state
4839  * @eli:                        FW event log sequence numbers information
4840  *
4841  * FW maintains a log of all events in a non-volatile area. Upper layers would
4842  * usually find out the latest sequence number of the events, the seq number at
4843  * the boot etc. They would "read" all the events below the latest seq number
4844  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
4845  * number), they would subsribe to AEN (asynchronous event notification) and
4846  * wait for the events to happen.
4847  */
4848 static int
4849 megasas_get_seq_num(struct megasas_instance *instance,
4850                     struct megasas_evt_log_info *eli)
4851 {
4852         struct megasas_cmd *cmd;
4853         struct megasas_dcmd_frame *dcmd;
4854         struct megasas_evt_log_info *el_info;
4855         dma_addr_t el_info_h = 0;
4856
4857         cmd = megasas_get_cmd(instance);
4858
4859         if (!cmd) {
4860                 return -ENOMEM;
4861         }
4862
4863         dcmd = &cmd->frame->dcmd;
4864         el_info = pci_alloc_consistent(instance->pdev,
4865                                        sizeof(struct megasas_evt_log_info),
4866                                        &el_info_h);
4867
4868         if (!el_info) {
4869                 megasas_return_cmd(instance, cmd);
4870                 return -ENOMEM;
4871         }
4872
4873         memset(el_info, 0, sizeof(*el_info));
4874         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4875
4876         dcmd->cmd = MFI_CMD_DCMD;
4877         dcmd->cmd_status = 0x0;
4878         dcmd->sge_count = 1;
4879         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
4880         dcmd->timeout = 0;
4881         dcmd->pad_0 = 0;
4882         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_log_info));
4883         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_GET_INFO);
4884         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(el_info_h);
4885         dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct megasas_evt_log_info));
4886
4887         if (megasas_issue_blocked_cmd(instance, cmd, 30))
4888                 dev_err(&instance->pdev->dev, "Command timedout"
4889                         "from %s\n", __func__);
4890         else {
4891                 /*
4892                  * Copy the data back into callers buffer
4893                  */
4894                 eli->newest_seq_num = el_info->newest_seq_num;
4895                 eli->oldest_seq_num = el_info->oldest_seq_num;
4896                 eli->clear_seq_num = el_info->clear_seq_num;
4897                 eli->shutdown_seq_num = el_info->shutdown_seq_num;
4898                 eli->boot_seq_num = el_info->boot_seq_num;
4899         }
4900
4901         pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
4902                             el_info, el_info_h);
4903
4904         megasas_return_cmd(instance, cmd);
4905
4906         return 0;
4907 }
4908
4909 /**
4910  * megasas_register_aen -       Registers for asynchronous event notification
4911  * @instance:                   Adapter soft state
4912  * @seq_num:                    The starting sequence number
4913  * @class_locale:               Class of the event
4914  *
4915  * This function subscribes for AEN for events beyond the @seq_num. It requests
4916  * to be notified if and only if the event is of type @class_locale
4917  */
4918 static int
4919 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
4920                      u32 class_locale_word)
4921 {
4922         int ret_val;
4923         struct megasas_cmd *cmd;
4924         struct megasas_dcmd_frame *dcmd;
4925         union megasas_evt_class_locale curr_aen;
4926         union megasas_evt_class_locale prev_aen;
4927
4928         /*
4929          * If there an AEN pending already (aen_cmd), check if the
4930          * class_locale of that pending AEN is inclusive of the new
4931          * AEN request we currently have. If it is, then we don't have
4932          * to do anything. In other words, whichever events the current
4933          * AEN request is subscribing to, have already been subscribed
4934          * to.
4935          *
4936          * If the old_cmd is _not_ inclusive, then we have to abort
4937          * that command, form a class_locale that is superset of both
4938          * old and current and re-issue to the FW
4939          */
4940
4941         curr_aen.word = class_locale_word;
4942
4943         if (instance->aen_cmd) {
4944
4945                 prev_aen.word =
4946                         le32_to_cpu(instance->aen_cmd->frame->dcmd.mbox.w[1]);
4947
4948                 /*
4949                  * A class whose enum value is smaller is inclusive of all
4950                  * higher values. If a PROGRESS (= -1) was previously
4951                  * registered, then a new registration requests for higher
4952                  * classes need not be sent to FW. They are automatically
4953                  * included.
4954                  *
4955                  * Locale numbers don't have such hierarchy. They are bitmap
4956                  * values
4957                  */
4958                 if ((prev_aen.members.class <= curr_aen.members.class) &&
4959                     !((prev_aen.members.locale & curr_aen.members.locale) ^
4960                       curr_aen.members.locale)) {
4961                         /*
4962                          * Previously issued event registration includes
4963                          * current request. Nothing to do.
4964                          */
4965                         return 0;
4966                 } else {
4967                         curr_aen.members.locale |= prev_aen.members.locale;
4968
4969                         if (prev_aen.members.class < curr_aen.members.class)
4970                                 curr_aen.members.class = prev_aen.members.class;
4971
4972                         instance->aen_cmd->abort_aen = 1;
4973                         ret_val = megasas_issue_blocked_abort_cmd(instance,
4974                                                                   instance->
4975                                                                   aen_cmd, 30);
4976
4977                         if (ret_val) {
4978                                 printk(KERN_DEBUG "megasas: Failed to abort "
4979                                        "previous AEN command\n");
4980                                 return ret_val;
4981                         }
4982                 }
4983         }
4984
4985         cmd = megasas_get_cmd(instance);
4986
4987         if (!cmd)
4988                 return -ENOMEM;
4989
4990         dcmd = &cmd->frame->dcmd;
4991
4992         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
4993
4994         /*
4995          * Prepare DCMD for aen registration
4996          */
4997         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4998
4999         dcmd->cmd = MFI_CMD_DCMD;
5000         dcmd->cmd_status = 0x0;
5001         dcmd->sge_count = 1;
5002         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
5003         dcmd->timeout = 0;
5004         dcmd->pad_0 = 0;
5005         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_detail));
5006         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_WAIT);
5007         dcmd->mbox.w[0] = cpu_to_le32(seq_num);
5008         instance->last_seq_num = seq_num;
5009         dcmd->mbox.w[1] = cpu_to_le32(curr_aen.word);
5010         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(instance->evt_detail_h);
5011         dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct megasas_evt_detail));
5012
5013         if (instance->aen_cmd != NULL) {
5014                 megasas_return_cmd(instance, cmd);
5015                 return 0;
5016         }
5017
5018         /*
5019          * Store reference to the cmd used to register for AEN. When an
5020          * application wants us to register for AEN, we have to abort this
5021          * cmd and re-register with a new EVENT LOCALE supplied by that app
5022          */
5023         instance->aen_cmd = cmd;
5024
5025         /*
5026          * Issue the aen registration frame
5027          */
5028         instance->instancet->issue_dcmd(instance, cmd);
5029
5030         return 0;
5031 }
5032
5033 /**
5034  * megasas_start_aen -  Subscribes to AEN during driver load time
5035  * @instance:           Adapter soft state
5036  */
5037 static int megasas_start_aen(struct megasas_instance *instance)
5038 {
5039         struct megasas_evt_log_info eli;
5040         union megasas_evt_class_locale class_locale;
5041
5042         /*
5043          * Get the latest sequence number from FW
5044          */
5045         memset(&eli, 0, sizeof(eli));
5046
5047         if (megasas_get_seq_num(instance, &eli))
5048                 return -1;
5049
5050         /*
5051          * Register AEN with FW for latest sequence number plus 1
5052          */
5053         class_locale.members.reserved = 0;
5054         class_locale.members.locale = MR_EVT_LOCALE_ALL;
5055         class_locale.members.class = MR_EVT_CLASS_DEBUG;
5056
5057         return megasas_register_aen(instance,
5058                         le32_to_cpu(eli.newest_seq_num) + 1,
5059                         class_locale.word);
5060 }
5061
5062 /**
5063  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
5064  * @instance:           Adapter soft state
5065  */
5066 static int megasas_io_attach(struct megasas_instance *instance)
5067 {
5068         struct Scsi_Host *host = instance->host;
5069         u32             error;
5070
5071         /*
5072          * Export parameters required by SCSI mid-layer
5073          */
5074         host->irq = instance->pdev->irq;
5075         host->unique_id = instance->unique_id;
5076         host->can_queue = instance->max_scsi_cmds;
5077         host->this_id = instance->init_id;
5078         host->sg_tablesize = instance->max_num_sge;
5079
5080         if (instance->fw_support_ieee)
5081                 instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
5082
5083         /*
5084          * Check if the module parameter value for max_sectors can be used
5085          */
5086         if (max_sectors && max_sectors < instance->max_sectors_per_req)
5087                 instance->max_sectors_per_req = max_sectors;
5088         else {
5089                 if (max_sectors) {
5090                         if (((instance->pdev->device ==
5091                                 PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
5092                                 (instance->pdev->device ==
5093                                 PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
5094                                 (max_sectors <= MEGASAS_MAX_SECTORS)) {
5095                                 instance->max_sectors_per_req = max_sectors;
5096                         } else {
5097                         printk(KERN_INFO "megasas: max_sectors should be > 0"
5098                                 "and <= %d (or < 1MB for GEN2 controller)\n",
5099                                 instance->max_sectors_per_req);
5100                         }
5101                 }
5102         }
5103
5104         host->max_sectors = instance->max_sectors_per_req;
5105         host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
5106         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
5107         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
5108         host->max_lun = MEGASAS_MAX_LUN;
5109         host->max_cmd_len = 16;
5110
5111         /* Fusion only supports host reset */
5112         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
5113             (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
5114             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
5115             (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY)) {
5116                 host->hostt->eh_device_reset_handler = NULL;
5117                 host->hostt->eh_bus_reset_handler = NULL;
5118         }
5119         error = scsi_init_shared_tag_map(host, host->can_queue);
5120         if (error) {
5121                 dev_err(&instance->pdev->dev,
5122                         "Failed to shared tag from %s %d\n",
5123                         __func__, __LINE__);
5124                 return -ENODEV;
5125         }
5126
5127         /*
5128          * Notify the mid-layer about the new controller
5129          */
5130         if (scsi_add_host(host, &instance->pdev->dev)) {
5131                 dev_err(&instance->pdev->dev,
5132                         "Failed to add host from %s %d\n",
5133                         __func__, __LINE__);
5134                 return -ENODEV;
5135         }
5136
5137         return 0;
5138 }
5139
5140 static int
5141 megasas_set_dma_mask(struct pci_dev *pdev)
5142 {
5143         /*
5144          * All our contollers are capable of performing 64-bit DMA
5145          */
5146         if (IS_DMA64) {
5147                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) {
5148
5149                         if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
5150                                 goto fail_set_dma_mask;
5151                 }
5152         } else {
5153                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
5154                         goto fail_set_dma_mask;
5155         }
5156         /*
5157          * Ensure that all data structures are allocated in 32-bit
5158          * memory.
5159          */
5160         if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)) != 0) {
5161                 /* Try 32bit DMA mask and 32 bit Consistent dma mask */
5162                 if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
5163                         && !pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))
5164                         dev_info(&pdev->dev, "set 32bit DMA mask"
5165                                 "and 32 bit consistent mask\n");
5166                 else
5167                         goto fail_set_dma_mask;
5168         }
5169
5170         return 0;
5171
5172 fail_set_dma_mask:
5173         return 1;
5174 }
5175
5176 /**
5177  * megasas_probe_one -  PCI hotplug entry point
5178  * @pdev:               PCI device structure
5179  * @id:                 PCI ids of supported hotplugged adapter
5180  */
5181 static int megasas_probe_one(struct pci_dev *pdev,
5182                              const struct pci_device_id *id)
5183 {
5184         int rval, pos;
5185         struct Scsi_Host *host;
5186         struct megasas_instance *instance;
5187         u16 control = 0;
5188         struct fusion_context *fusion = NULL;
5189
5190         /* Reset MSI-X in the kdump kernel */
5191         if (reset_devices) {
5192                 pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
5193                 if (pos) {
5194                         pci_read_config_word(pdev, pos + PCI_MSIX_FLAGS,
5195                                              &control);
5196                         if (control & PCI_MSIX_FLAGS_ENABLE) {
5197                                 dev_info(&pdev->dev, "resetting MSI-X\n");
5198                                 pci_write_config_word(pdev,
5199                                                       pos + PCI_MSIX_FLAGS,
5200                                                       control &
5201                                                       ~PCI_MSIX_FLAGS_ENABLE);
5202                         }
5203                 }
5204         }
5205
5206         /*
5207          * PCI prepping: enable device set bus mastering and dma mask
5208          */
5209         rval = pci_enable_device_mem(pdev);
5210
5211         if (rval) {
5212                 return rval;
5213         }
5214
5215         pci_set_master(pdev);
5216
5217         if (megasas_set_dma_mask(pdev))
5218                 goto fail_set_dma_mask;
5219
5220         host = scsi_host_alloc(&megasas_template,
5221                                sizeof(struct megasas_instance));
5222
5223         if (!host) {
5224                 printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
5225                 goto fail_alloc_instance;
5226         }
5227
5228         instance = (struct megasas_instance *)host->hostdata;
5229         memset(instance, 0, sizeof(*instance));
5230         atomic_set( &instance->fw_reset_no_pci_access, 0 );
5231         instance->pdev = pdev;
5232
5233         switch (instance->pdev->device) {
5234         case PCI_DEVICE_ID_LSI_FUSION:
5235         case PCI_DEVICE_ID_LSI_PLASMA:
5236         case PCI_DEVICE_ID_LSI_INVADER:
5237         case PCI_DEVICE_ID_LSI_FURY:
5238         {
5239                 instance->ctrl_context_pages =
5240                         get_order(sizeof(struct fusion_context));
5241                 instance->ctrl_context = (void *)__get_free_pages(GFP_KERNEL,
5242                                 instance->ctrl_context_pages);
5243                 if (!instance->ctrl_context) {
5244                         printk(KERN_DEBUG "megasas: Failed to allocate "
5245                                "memory for Fusion context info\n");
5246                         goto fail_alloc_dma_buf;
5247                 }
5248                 fusion = instance->ctrl_context;
5249                 memset(fusion, 0,
5250                         ((1 << PAGE_SHIFT) << instance->ctrl_context_pages));
5251         }
5252         break;
5253         default: /* For all other supported controllers */
5254
5255                 instance->producer =
5256                         pci_alloc_consistent(pdev, sizeof(u32),
5257                                              &instance->producer_h);
5258                 instance->consumer =
5259                         pci_alloc_consistent(pdev, sizeof(u32),
5260                                              &instance->consumer_h);
5261
5262                 if (!instance->producer || !instance->consumer) {
5263                         printk(KERN_DEBUG "megasas: Failed to allocate"
5264                                "memory for producer, consumer\n");
5265                         goto fail_alloc_dma_buf;
5266                 }
5267
5268                 *instance->producer = 0;
5269                 *instance->consumer = 0;
5270                 break;
5271         }
5272
5273         instance->system_info_buf = pci_zalloc_consistent(pdev,
5274                                         sizeof(struct MR_DRV_SYSTEM_INFO),
5275                                         &instance->system_info_h);
5276
5277         if (!instance->system_info_buf)
5278                 dev_info(&instance->pdev->dev, "Can't allocate system info buffer\n");
5279
5280         /* Crash dump feature related initialisation*/
5281         instance->drv_buf_index = 0;
5282         instance->drv_buf_alloc = 0;
5283         instance->crash_dump_fw_support = 0;
5284         instance->crash_dump_app_support = 0;
5285         instance->fw_crash_state = UNAVAILABLE;
5286         spin_lock_init(&instance->crashdump_lock);
5287         instance->crash_dump_buf = NULL;
5288
5289         if (!reset_devices)
5290                 instance->crash_dump_buf = pci_alloc_consistent(pdev,
5291                                                 CRASH_DMA_BUF_SIZE,
5292                                                 &instance->crash_dump_h);
5293         if (!instance->crash_dump_buf)
5294                 dev_err(&instance->pdev->dev, "Can't allocate Firmware "
5295                         "crash dump DMA buffer\n");
5296
5297         megasas_poll_wait_aen = 0;
5298         instance->flag_ieee = 0;
5299         instance->ev = NULL;
5300         instance->issuepend_done = 1;
5301         instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
5302         instance->is_imr = 0;
5303
5304         instance->evt_detail = pci_alloc_consistent(pdev,
5305                                                     sizeof(struct
5306                                                            megasas_evt_detail),
5307                                                     &instance->evt_detail_h);
5308
5309         if (!instance->evt_detail) {
5310                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
5311                        "event detail structure\n");
5312                 goto fail_alloc_dma_buf;
5313         }
5314
5315         /*
5316          * Initialize locks and queues
5317          */
5318         INIT_LIST_HEAD(&instance->cmd_pool);
5319         INIT_LIST_HEAD(&instance->internal_reset_pending_q);
5320
5321         atomic_set(&instance->fw_outstanding,0);
5322
5323         init_waitqueue_head(&instance->int_cmd_wait_q);
5324         init_waitqueue_head(&instance->abort_cmd_wait_q);
5325
5326         spin_lock_init(&instance->mfi_pool_lock);
5327         spin_lock_init(&instance->hba_lock);
5328         spin_lock_init(&instance->completion_lock);
5329
5330         mutex_init(&instance->aen_mutex);
5331         mutex_init(&instance->reset_mutex);
5332
5333         /*
5334          * Initialize PCI related and misc parameters
5335          */
5336         instance->host = host;
5337         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
5338         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
5339         instance->ctrl_info = NULL;
5340
5341
5342         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
5343                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY))
5344                 instance->flag_ieee = 1;
5345
5346         megasas_dbg_lvl = 0;
5347         instance->flag = 0;
5348         instance->unload = 1;
5349         instance->last_time = 0;
5350         instance->disableOnlineCtrlReset = 1;
5351         instance->UnevenSpanSupport = 0;
5352
5353         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
5354             (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
5355             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
5356             (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY)) {
5357                 INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
5358                 INIT_WORK(&instance->crash_init, megasas_fusion_crash_dump_wq);
5359         } else
5360                 INIT_WORK(&instance->work_init, process_fw_state_change_wq);
5361
5362         /*
5363          * Initialize MFI Firmware
5364          */
5365         if (megasas_init_fw(instance))
5366                 goto fail_init_mfi;
5367
5368         if (instance->requestorId) {
5369                 if (instance->PlasmaFW111) {
5370                         instance->vf_affiliation_111 =
5371                                 pci_alloc_consistent(pdev, sizeof(struct MR_LD_VF_AFFILIATION_111),
5372                                                      &instance->vf_affiliation_111_h);
5373                         if (!instance->vf_affiliation_111)
5374                                 printk(KERN_WARNING "megasas: Can't allocate "
5375                                        "memory for VF affiliation buffer\n");
5376                 } else {
5377                         instance->vf_affiliation =
5378                                 pci_alloc_consistent(pdev,
5379                                                      (MAX_LOGICAL_DRIVES + 1) *
5380                                                      sizeof(struct MR_LD_VF_AFFILIATION),
5381                                                      &instance->vf_affiliation_h);
5382                         if (!instance->vf_affiliation)
5383                                 printk(KERN_WARNING "megasas: Can't allocate "
5384                                        "memory for VF affiliation buffer\n");
5385                 }
5386         }
5387
5388         /*
5389          * Store instance in PCI softstate
5390          */
5391         pci_set_drvdata(pdev, instance);
5392
5393         /*
5394          * Add this controller to megasas_mgmt_info structure so that it
5395          * can be exported to management applications
5396          */
5397         megasas_mgmt_info.count++;
5398         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
5399         megasas_mgmt_info.max_index++;
5400
5401         /*
5402          * Register with SCSI mid-layer
5403          */
5404         if (megasas_io_attach(instance))
5405                 goto fail_io_attach;
5406
5407         instance->unload = 0;
5408         /*
5409          * Trigger SCSI to scan our drives
5410          */
5411         scsi_scan_host(host);
5412
5413         /*
5414          * Initiate AEN (Asynchronous Event Notification)
5415          */
5416         if (megasas_start_aen(instance)) {
5417                 printk(KERN_DEBUG "megasas: start aen failed\n");
5418                 goto fail_start_aen;
5419         }
5420
5421         /* Get current SR-IOV LD/VF affiliation */
5422         if (instance->requestorId)
5423                 megasas_get_ld_vf_affiliation(instance, 1);
5424
5425         return 0;
5426
5427       fail_start_aen:
5428       fail_io_attach:
5429         megasas_mgmt_info.count--;
5430         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
5431         megasas_mgmt_info.max_index--;
5432
5433         instance->instancet->disable_intr(instance);
5434         megasas_destroy_irqs(instance);
5435
5436         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
5437             (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
5438             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
5439             (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY))
5440                 megasas_release_fusion(instance);
5441         else
5442                 megasas_release_mfi(instance);
5443         if (instance->msix_vectors)
5444                 pci_disable_msix(instance->pdev);
5445 fail_init_mfi:
5446       fail_alloc_dma_buf:
5447         if (instance->evt_detail)
5448                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
5449                                     instance->evt_detail,
5450                                     instance->evt_detail_h);
5451
5452         if (instance->producer)
5453                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
5454                                     instance->producer_h);
5455         if (instance->consumer)
5456                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
5457                                     instance->consumer_h);
5458         scsi_host_put(host);
5459
5460       fail_alloc_instance:
5461       fail_set_dma_mask:
5462         pci_disable_device(pdev);
5463
5464         return -ENODEV;
5465 }
5466
5467 /**
5468  * megasas_flush_cache -        Requests FW to flush all its caches
5469  * @instance:                   Adapter soft state
5470  */
5471 static void megasas_flush_cache(struct megasas_instance *instance)
5472 {
5473         struct megasas_cmd *cmd;
5474         struct megasas_dcmd_frame *dcmd;
5475
5476         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
5477                 return;
5478
5479         cmd = megasas_get_cmd(instance);
5480
5481         if (!cmd)
5482                 return;
5483
5484         dcmd = &cmd->frame->dcmd;
5485
5486         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5487
5488         dcmd->cmd = MFI_CMD_DCMD;
5489         dcmd->cmd_status = 0x0;
5490         dcmd->sge_count = 0;
5491         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
5492         dcmd->timeout = 0;
5493         dcmd->pad_0 = 0;
5494         dcmd->data_xfer_len = 0;
5495         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_CACHE_FLUSH);
5496         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
5497
5498         if (megasas_issue_blocked_cmd(instance, cmd, 30))
5499                 dev_err(&instance->pdev->dev, "Command timedout"
5500                         " from %s\n", __func__);
5501
5502         megasas_return_cmd(instance, cmd);
5503
5504         return;
5505 }
5506
5507 /**
5508  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
5509  * @instance:                           Adapter soft state
5510  * @opcode:                             Shutdown/Hibernate
5511  */
5512 static void megasas_shutdown_controller(struct megasas_instance *instance,
5513                                         u32 opcode)
5514 {
5515         struct megasas_cmd *cmd;
5516         struct megasas_dcmd_frame *dcmd;
5517
5518         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
5519                 return;
5520
5521         cmd = megasas_get_cmd(instance);
5522
5523         if (!cmd)
5524                 return;
5525
5526         if (instance->aen_cmd)
5527                 megasas_issue_blocked_abort_cmd(instance,
5528                         instance->aen_cmd, 30);
5529         if (instance->map_update_cmd)
5530                 megasas_issue_blocked_abort_cmd(instance,
5531                         instance->map_update_cmd, 30);
5532         dcmd = &cmd->frame->dcmd;
5533
5534         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5535
5536         dcmd->cmd = MFI_CMD_DCMD;
5537         dcmd->cmd_status = 0x0;
5538         dcmd->sge_count = 0;
5539         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
5540         dcmd->timeout = 0;
5541         dcmd->pad_0 = 0;
5542         dcmd->data_xfer_len = 0;
5543         dcmd->opcode = cpu_to_le32(opcode);
5544
5545         if (megasas_issue_blocked_cmd(instance, cmd, 30))
5546                 dev_err(&instance->pdev->dev, "Command timedout"
5547                         "from %s\n", __func__);
5548
5549         megasas_return_cmd(instance, cmd);
5550
5551         return;
5552 }
5553
5554 #ifdef CONFIG_PM
5555 /**
5556  * megasas_suspend -    driver suspend entry point
5557  * @pdev:               PCI device structure
5558  * @state:              PCI power state to suspend routine
5559  */
5560 static int
5561 megasas_suspend(struct pci_dev *pdev, pm_message_t state)
5562 {
5563         struct Scsi_Host *host;
5564         struct megasas_instance *instance;
5565
5566         instance = pci_get_drvdata(pdev);
5567         host = instance->host;
5568         instance->unload = 1;
5569
5570         /* Shutdown SR-IOV heartbeat timer */
5571         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
5572                 del_timer_sync(&instance->sriov_heartbeat_timer);
5573
5574         megasas_flush_cache(instance);
5575         megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
5576
5577         /* cancel the delayed work if this work still in queue */
5578         if (instance->ev != NULL) {
5579                 struct megasas_aen_event *ev = instance->ev;
5580                 cancel_delayed_work_sync(&ev->hotplug_work);
5581                 instance->ev = NULL;
5582         }
5583
5584         tasklet_kill(&instance->isr_tasklet);
5585
5586         pci_set_drvdata(instance->pdev, instance);
5587         instance->instancet->disable_intr(instance);
5588
5589         megasas_destroy_irqs(instance);
5590
5591         if (instance->msix_vectors)
5592                 pci_disable_msix(instance->pdev);
5593
5594         pci_save_state(pdev);
5595         pci_disable_device(pdev);
5596
5597         pci_set_power_state(pdev, pci_choose_state(pdev, state));
5598
5599         return 0;
5600 }
5601
5602 /**
5603  * megasas_resume-      driver resume entry point
5604  * @pdev:               PCI device structure
5605  */
5606 static int
5607 megasas_resume(struct pci_dev *pdev)
5608 {
5609         int rval;
5610         struct Scsi_Host *host;
5611         struct megasas_instance *instance;
5612
5613         instance = pci_get_drvdata(pdev);
5614         host = instance->host;
5615         pci_set_power_state(pdev, PCI_D0);
5616         pci_enable_wake(pdev, PCI_D0, 0);
5617         pci_restore_state(pdev);
5618
5619         /*
5620          * PCI prepping: enable device set bus mastering and dma mask
5621          */
5622         rval = pci_enable_device_mem(pdev);
5623
5624         if (rval) {
5625                 printk(KERN_ERR "megasas: Enable device failed\n");
5626                 return rval;
5627         }
5628
5629         pci_set_master(pdev);
5630
5631         if (megasas_set_dma_mask(pdev))
5632                 goto fail_set_dma_mask;
5633
5634         /*
5635          * Initialize MFI Firmware
5636          */
5637
5638         atomic_set(&instance->fw_outstanding, 0);
5639
5640         /*
5641          * We expect the FW state to be READY
5642          */
5643         if (megasas_transition_to_ready(instance, 0))
5644                 goto fail_ready_state;
5645
5646         /* Now re-enable MSI-X */
5647         if (instance->msix_vectors &&
5648             pci_enable_msix_exact(instance->pdev, instance->msixentry,
5649                                   instance->msix_vectors))
5650                 goto fail_reenable_msix;
5651
5652         switch (instance->pdev->device) {
5653         case PCI_DEVICE_ID_LSI_FUSION:
5654         case PCI_DEVICE_ID_LSI_PLASMA:
5655         case PCI_DEVICE_ID_LSI_INVADER:
5656         case PCI_DEVICE_ID_LSI_FURY:
5657         {
5658                 megasas_reset_reply_desc(instance);
5659                 if (megasas_ioc_init_fusion(instance)) {
5660                         megasas_free_cmds(instance);
5661                         megasas_free_cmds_fusion(instance);
5662                         goto fail_init_mfi;
5663                 }
5664                 if (!megasas_get_map_info(instance))
5665                         megasas_sync_map_info(instance);
5666         }
5667         break;
5668         default:
5669                 *instance->producer = 0;
5670                 *instance->consumer = 0;
5671                 if (megasas_issue_init_mfi(instance))
5672                         goto fail_init_mfi;
5673                 break;
5674         }
5675
5676         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
5677                      (unsigned long)instance);
5678
5679         if (instance->msix_vectors ?
5680                         megasas_setup_irqs_msix(instance, 0) :
5681                         megasas_setup_irqs_ioapic(instance))
5682                 goto fail_init_mfi;
5683
5684         /* Re-launch SR-IOV heartbeat timer */
5685         if (instance->requestorId) {
5686                 if (!megasas_sriov_start_heartbeat(instance, 0))
5687                         megasas_start_timer(instance,
5688                                             &instance->sriov_heartbeat_timer,
5689                                             megasas_sriov_heartbeat_handler,
5690                                             MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
5691                 else {
5692                         instance->skip_heartbeat_timer_del = 1;
5693                         goto fail_init_mfi;
5694                 }
5695         }
5696
5697         instance->instancet->enable_intr(instance);
5698         instance->unload = 0;
5699
5700         /*
5701          * Initiate AEN (Asynchronous Event Notification)
5702          */
5703         if (megasas_start_aen(instance))
5704                 printk(KERN_ERR "megasas: Start AEN failed\n");
5705
5706         return 0;
5707
5708 fail_init_mfi:
5709         if (instance->evt_detail)
5710                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
5711                                 instance->evt_detail,
5712                                 instance->evt_detail_h);
5713
5714         if (instance->producer)
5715                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
5716                                 instance->producer_h);
5717         if (instance->consumer)
5718                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
5719                                 instance->consumer_h);
5720         scsi_host_put(host);
5721
5722 fail_set_dma_mask:
5723 fail_ready_state:
5724 fail_reenable_msix:
5725
5726         pci_disable_device(pdev);
5727
5728         return -ENODEV;
5729 }
5730 #else
5731 #define megasas_suspend NULL
5732 #define megasas_resume  NULL
5733 #endif
5734
5735 /**
5736  * megasas_detach_one - PCI hot"un"plug entry point
5737  * @pdev:               PCI device structure
5738  */
5739 static void megasas_detach_one(struct pci_dev *pdev)
5740 {
5741         int i;
5742         struct Scsi_Host *host;
5743         struct megasas_instance *instance;
5744         struct fusion_context *fusion;
5745
5746         instance = pci_get_drvdata(pdev);
5747         instance->unload = 1;
5748         host = instance->host;
5749         fusion = instance->ctrl_context;
5750
5751         /* Shutdown SR-IOV heartbeat timer */
5752         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
5753                 del_timer_sync(&instance->sriov_heartbeat_timer);
5754
5755         if (instance->fw_crash_state != UNAVAILABLE)
5756                 megasas_free_host_crash_buffer(instance);
5757         scsi_remove_host(instance->host);
5758         megasas_flush_cache(instance);
5759         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
5760
5761         /* cancel the delayed work if this work still in queue*/
5762         if (instance->ev != NULL) {
5763                 struct megasas_aen_event *ev = instance->ev;
5764                 cancel_delayed_work_sync(&ev->hotplug_work);
5765                 instance->ev = NULL;
5766         }
5767
5768         /* cancel all wait events */
5769         wake_up_all(&instance->int_cmd_wait_q);
5770
5771         tasklet_kill(&instance->isr_tasklet);
5772
5773         /*
5774          * Take the instance off the instance array. Note that we will not
5775          * decrement the max_index. We let this array be sparse array
5776          */
5777         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
5778                 if (megasas_mgmt_info.instance[i] == instance) {
5779                         megasas_mgmt_info.count--;
5780                         megasas_mgmt_info.instance[i] = NULL;
5781
5782                         break;
5783                 }
5784         }
5785
5786         instance->instancet->disable_intr(instance);
5787
5788         megasas_destroy_irqs(instance);
5789
5790         if (instance->msix_vectors)
5791                 pci_disable_msix(instance->pdev);
5792
5793         switch (instance->pdev->device) {
5794         case PCI_DEVICE_ID_LSI_FUSION:
5795         case PCI_DEVICE_ID_LSI_PLASMA:
5796         case PCI_DEVICE_ID_LSI_INVADER:
5797         case PCI_DEVICE_ID_LSI_FURY:
5798                 megasas_release_fusion(instance);
5799                 for (i = 0; i < 2 ; i++) {
5800                         if (fusion->ld_map[i])
5801                                 dma_free_coherent(&instance->pdev->dev,
5802                                                   fusion->max_map_sz,
5803                                                   fusion->ld_map[i],
5804                                                   fusion->ld_map_phys[i]);
5805                         if (fusion->ld_drv_map[i])
5806                                 free_pages((ulong)fusion->ld_drv_map[i],
5807                                         fusion->drv_map_pages);
5808                 }
5809                 free_pages((ulong)instance->ctrl_context,
5810                         instance->ctrl_context_pages);
5811                 break;
5812         default:
5813                 megasas_release_mfi(instance);
5814                 pci_free_consistent(pdev, sizeof(u32),
5815                                     instance->producer,
5816                                     instance->producer_h);
5817                 pci_free_consistent(pdev, sizeof(u32),
5818                                     instance->consumer,
5819                                     instance->consumer_h);
5820                 break;
5821         }
5822
5823         kfree(instance->ctrl_info);
5824
5825         if (instance->evt_detail)
5826                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
5827                                 instance->evt_detail, instance->evt_detail_h);
5828
5829         if (instance->vf_affiliation)
5830                 pci_free_consistent(pdev, (MAX_LOGICAL_DRIVES + 1) *
5831                                     sizeof(struct MR_LD_VF_AFFILIATION),
5832                                     instance->vf_affiliation,
5833                                     instance->vf_affiliation_h);
5834
5835         if (instance->vf_affiliation_111)
5836                 pci_free_consistent(pdev,
5837                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
5838                                     instance->vf_affiliation_111,
5839                                     instance->vf_affiliation_111_h);
5840
5841         if (instance->hb_host_mem)
5842                 pci_free_consistent(pdev, sizeof(struct MR_CTRL_HB_HOST_MEM),
5843                                     instance->hb_host_mem,
5844                                     instance->hb_host_mem_h);
5845
5846         if (instance->crash_dump_buf)
5847                 pci_free_consistent(pdev, CRASH_DMA_BUF_SIZE,
5848                             instance->crash_dump_buf, instance->crash_dump_h);
5849
5850         if (instance->system_info_buf)
5851                 pci_free_consistent(pdev, sizeof(struct MR_DRV_SYSTEM_INFO),
5852                                     instance->system_info_buf, instance->system_info_h);
5853
5854         scsi_host_put(host);
5855
5856         pci_disable_device(pdev);
5857
5858         return;
5859 }
5860
5861 /**
5862  * megasas_shutdown -   Shutdown entry point
5863  * @device:             Generic device structure
5864  */
5865 static void megasas_shutdown(struct pci_dev *pdev)
5866 {
5867         struct megasas_instance *instance = pci_get_drvdata(pdev);
5868
5869         instance->unload = 1;
5870         megasas_flush_cache(instance);
5871         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
5872         instance->instancet->disable_intr(instance);
5873         megasas_destroy_irqs(instance);
5874
5875         if (instance->msix_vectors)
5876                 pci_disable_msix(instance->pdev);
5877 }
5878
5879 /**
5880  * megasas_mgmt_open -  char node "open" entry point
5881  */
5882 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
5883 {
5884         /*
5885          * Allow only those users with admin rights
5886          */
5887         if (!capable(CAP_SYS_ADMIN))
5888                 return -EACCES;
5889
5890         return 0;
5891 }
5892
5893 /**
5894  * megasas_mgmt_fasync -        Async notifier registration from applications
5895  *
5896  * This function adds the calling process to a driver global queue. When an
5897  * event occurs, SIGIO will be sent to all processes in this queue.
5898  */
5899 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
5900 {
5901         int rc;
5902
5903         mutex_lock(&megasas_async_queue_mutex);
5904
5905         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
5906
5907         mutex_unlock(&megasas_async_queue_mutex);
5908
5909         if (rc >= 0) {
5910                 /* For sanity check when we get ioctl */
5911                 filep->private_data = filep;
5912                 return 0;
5913         }
5914
5915         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
5916
5917         return rc;
5918 }
5919
5920 /**
5921  * megasas_mgmt_poll -  char node "poll" entry point
5922  * */
5923 static unsigned int megasas_mgmt_poll(struct file *file, poll_table *wait)
5924 {
5925         unsigned int mask;
5926         unsigned long flags;
5927         poll_wait(file, &megasas_poll_wait, wait);
5928         spin_lock_irqsave(&poll_aen_lock, flags);
5929         if (megasas_poll_wait_aen)
5930                 mask =   (POLLIN | POLLRDNORM);
5931
5932         else
5933                 mask = 0;
5934         megasas_poll_wait_aen = 0;
5935         spin_unlock_irqrestore(&poll_aen_lock, flags);
5936         return mask;
5937 }
5938
5939 /*
5940  * megasas_set_crash_dump_params_ioctl:
5941  *              Send CRASH_DUMP_MODE DCMD to all controllers
5942  * @cmd:        MFI command frame
5943  */
5944
5945 static int megasas_set_crash_dump_params_ioctl(
5946         struct megasas_cmd *cmd)
5947 {
5948         struct megasas_instance *local_instance;
5949         int i, error = 0;
5950         int crash_support;
5951
5952         crash_support = cmd->frame->dcmd.mbox.w[0];
5953
5954         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
5955                 local_instance = megasas_mgmt_info.instance[i];
5956                 if (local_instance && local_instance->crash_dump_drv_support) {
5957                         if ((local_instance->adprecovery ==
5958                                 MEGASAS_HBA_OPERATIONAL) &&
5959                                 !megasas_set_crash_dump_params(local_instance,
5960                                         crash_support)) {
5961                                 local_instance->crash_dump_app_support =
5962                                         crash_support;
5963                                 dev_info(&local_instance->pdev->dev,
5964                                         "Application firmware crash "
5965                                         "dump mode set success\n");
5966                                 error = 0;
5967                         } else {
5968                                 dev_info(&local_instance->pdev->dev,
5969                                         "Application firmware crash "
5970                                         "dump mode set failed\n");
5971                                 error = -1;
5972                         }
5973                 }
5974         }
5975         return error;
5976 }
5977
5978 /**
5979  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
5980  * @instance:                   Adapter soft state
5981  * @argp:                       User's ioctl packet
5982  */
5983 static int
5984 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
5985                       struct megasas_iocpacket __user * user_ioc,
5986                       struct megasas_iocpacket *ioc)
5987 {
5988         struct megasas_sge32 *kern_sge32;
5989         struct megasas_cmd *cmd;
5990         void *kbuff_arr[MAX_IOCTL_SGE];
5991         dma_addr_t buf_handle = 0;
5992         int error = 0, i;
5993         void *sense = NULL;
5994         dma_addr_t sense_handle;
5995         unsigned long *sense_ptr;
5996
5997         memset(kbuff_arr, 0, sizeof(kbuff_arr));
5998
5999         if (ioc->sge_count > MAX_IOCTL_SGE) {
6000                 printk(KERN_DEBUG "megasas: SGE count [%d] >  max limit [%d]\n",
6001                        ioc->sge_count, MAX_IOCTL_SGE);
6002                 return -EINVAL;
6003         }
6004
6005         cmd = megasas_get_cmd(instance);
6006         if (!cmd) {
6007                 printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
6008                 return -ENOMEM;
6009         }
6010
6011         /*
6012          * User's IOCTL packet has 2 frames (maximum). Copy those two
6013          * frames into our cmd's frames. cmd->frame's context will get
6014          * overwritten when we copy from user's frames. So set that value
6015          * alone separately
6016          */
6017         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
6018         cmd->frame->hdr.context = cpu_to_le32(cmd->index);
6019         cmd->frame->hdr.pad_0 = 0;
6020         cmd->frame->hdr.flags &= cpu_to_le16(~(MFI_FRAME_IEEE |
6021                                                MFI_FRAME_SGL64 |
6022                                                MFI_FRAME_SENSE64));
6023
6024         if (cmd->frame->dcmd.opcode == MR_DRIVER_SET_APP_CRASHDUMP_MODE) {
6025                 error = megasas_set_crash_dump_params_ioctl(cmd);
6026                 megasas_return_cmd(instance, cmd);
6027                 return error;
6028         }
6029
6030         /*
6031          * The management interface between applications and the fw uses
6032          * MFI frames. E.g, RAID configuration changes, LD property changes
6033          * etc are accomplishes through different kinds of MFI frames. The
6034          * driver needs to care only about substituting user buffers with
6035          * kernel buffers in SGLs. The location of SGL is embedded in the
6036          * struct iocpacket itself.
6037          */
6038         kern_sge32 = (struct megasas_sge32 *)
6039             ((unsigned long)cmd->frame + ioc->sgl_off);
6040
6041         /*
6042          * For each user buffer, create a mirror buffer and copy in
6043          */
6044         for (i = 0; i < ioc->sge_count; i++) {
6045                 if (!ioc->sgl[i].iov_len)
6046                         continue;
6047
6048                 kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
6049                                                     ioc->sgl[i].iov_len,
6050                                                     &buf_handle, GFP_KERNEL);
6051                 if (!kbuff_arr[i]) {
6052                         printk(KERN_DEBUG "megasas: Failed to alloc "
6053                                "kernel SGL buffer for IOCTL \n");
6054                         error = -ENOMEM;
6055                         goto out;
6056                 }
6057
6058                 /*
6059                  * We don't change the dma_coherent_mask, so
6060                  * pci_alloc_consistent only returns 32bit addresses
6061                  */
6062                 kern_sge32[i].phys_addr = cpu_to_le32(buf_handle);
6063                 kern_sge32[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
6064
6065                 /*
6066                  * We created a kernel buffer corresponding to the
6067                  * user buffer. Now copy in from the user buffer
6068                  */
6069                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
6070                                    (u32) (ioc->sgl[i].iov_len))) {
6071                         error = -EFAULT;
6072                         goto out;
6073                 }
6074         }
6075
6076         if (ioc->sense_len) {
6077                 sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
6078                                              &sense_handle, GFP_KERNEL);
6079                 if (!sense) {
6080                         error = -ENOMEM;
6081                         goto out;
6082                 }
6083
6084                 sense_ptr =
6085                 (unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off);
6086                 *sense_ptr = cpu_to_le32(sense_handle);
6087         }
6088
6089         /*
6090          * Set the sync_cmd flag so that the ISR knows not to complete this
6091          * cmd to the SCSI mid-layer
6092          */
6093         cmd->sync_cmd = 1;
6094         megasas_issue_blocked_cmd(instance, cmd, 0);
6095         cmd->sync_cmd = 0;
6096
6097         if (instance->unload == 1) {
6098                 dev_info(&instance->pdev->dev, "Driver unload is in progress "
6099                         "don't submit data to application\n");
6100                 goto out;
6101         }
6102         /*
6103          * copy out the kernel buffers to user buffers
6104          */
6105         for (i = 0; i < ioc->sge_count; i++) {
6106                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
6107                                  ioc->sgl[i].iov_len)) {
6108                         error = -EFAULT;
6109                         goto out;
6110                 }
6111         }
6112
6113         /*
6114          * copy out the sense
6115          */
6116         if (ioc->sense_len) {
6117                 /*
6118                  * sense_ptr points to the location that has the user
6119                  * sense buffer address
6120                  */
6121                 sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
6122                                 ioc->sense_off);
6123
6124                 if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
6125                                  sense, ioc->sense_len)) {
6126                         printk(KERN_ERR "megasas: Failed to copy out to user "
6127                                         "sense data\n");
6128                         error = -EFAULT;
6129                         goto out;
6130                 }
6131         }
6132
6133         /*
6134          * copy the status codes returned by the fw
6135          */
6136         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
6137                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
6138                 printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
6139                 error = -EFAULT;
6140         }
6141
6142       out:
6143         if (sense) {
6144                 dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
6145                                     sense, sense_handle);
6146         }
6147
6148         for (i = 0; i < ioc->sge_count; i++) {
6149                 if (kbuff_arr[i])
6150                         dma_free_coherent(&instance->pdev->dev,
6151                                           le32_to_cpu(kern_sge32[i].length),
6152                                           kbuff_arr[i],
6153                                           le32_to_cpu(kern_sge32[i].phys_addr));
6154                         kbuff_arr[i] = NULL;
6155         }
6156
6157         megasas_return_cmd(instance, cmd);
6158         return error;
6159 }
6160
6161 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
6162 {
6163         struct megasas_iocpacket __user *user_ioc =
6164             (struct megasas_iocpacket __user *)arg;
6165         struct megasas_iocpacket *ioc;
6166         struct megasas_instance *instance;
6167         int error;
6168         int i;
6169         unsigned long flags;
6170         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
6171
6172         ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
6173         if (!ioc)
6174                 return -ENOMEM;
6175
6176         if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
6177                 error = -EFAULT;
6178                 goto out_kfree_ioc;
6179         }
6180
6181         instance = megasas_lookup_instance(ioc->host_no);
6182         if (!instance) {
6183                 error = -ENODEV;
6184                 goto out_kfree_ioc;
6185         }
6186
6187         /* Adjust ioctl wait time for VF mode */
6188         if (instance->requestorId)
6189                 wait_time = MEGASAS_ROUTINE_WAIT_TIME_VF;
6190
6191         /* Block ioctls in VF mode */
6192         if (instance->requestorId && !allow_vf_ioctls) {
6193                 error = -ENODEV;
6194                 goto out_kfree_ioc;
6195         }
6196
6197         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
6198                 printk(KERN_ERR "Controller in crit error\n");
6199                 error = -ENODEV;
6200                 goto out_kfree_ioc;
6201         }
6202
6203         if (instance->unload == 1) {
6204                 error = -ENODEV;
6205                 goto out_kfree_ioc;
6206         }
6207
6208         if (down_interruptible(&instance->ioctl_sem)) {
6209                 error = -ERESTARTSYS;
6210                 goto out_kfree_ioc;
6211         }
6212
6213         for (i = 0; i < wait_time; i++) {
6214
6215                 spin_lock_irqsave(&instance->hba_lock, flags);
6216                 if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
6217                         spin_unlock_irqrestore(&instance->hba_lock, flags);
6218                         break;
6219                 }
6220                 spin_unlock_irqrestore(&instance->hba_lock, flags);
6221
6222                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
6223                         printk(KERN_NOTICE "megasas: waiting"
6224                                 "for controller reset to finish\n");
6225                 }
6226
6227                 msleep(1000);
6228         }
6229
6230         spin_lock_irqsave(&instance->hba_lock, flags);
6231         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
6232                 spin_unlock_irqrestore(&instance->hba_lock, flags);
6233
6234                 printk(KERN_ERR "megaraid_sas: timed out while"
6235                         "waiting for HBA to recover\n");
6236                 error = -ENODEV;
6237                 goto out_up;
6238         }
6239         spin_unlock_irqrestore(&instance->hba_lock, flags);
6240
6241         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
6242       out_up:
6243         up(&instance->ioctl_sem);
6244
6245       out_kfree_ioc:
6246         kfree(ioc);
6247         return error;
6248 }
6249
6250 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
6251 {
6252         struct megasas_instance *instance;
6253         struct megasas_aen aen;
6254         int error;
6255         int i;
6256         unsigned long flags;
6257         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
6258
6259         if (file->private_data != file) {
6260                 printk(KERN_DEBUG "megasas: fasync_helper was not "
6261                        "called first\n");
6262                 return -EINVAL;
6263         }
6264
6265         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
6266                 return -EFAULT;
6267
6268         instance = megasas_lookup_instance(aen.host_no);
6269
6270         if (!instance)
6271                 return -ENODEV;
6272
6273         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
6274                 return -ENODEV;
6275         }
6276
6277         if (instance->unload == 1) {
6278                 return -ENODEV;
6279         }
6280
6281         for (i = 0; i < wait_time; i++) {
6282
6283                 spin_lock_irqsave(&instance->hba_lock, flags);
6284                 if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
6285                         spin_unlock_irqrestore(&instance->hba_lock,
6286                                                 flags);
6287                         break;
6288                 }
6289
6290                 spin_unlock_irqrestore(&instance->hba_lock, flags);
6291
6292                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
6293                         printk(KERN_NOTICE "megasas: waiting for"
6294                                 "controller reset to finish\n");
6295                 }
6296
6297                 msleep(1000);
6298         }
6299
6300         spin_lock_irqsave(&instance->hba_lock, flags);
6301         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
6302                 spin_unlock_irqrestore(&instance->hba_lock, flags);
6303                 printk(KERN_ERR "megaraid_sas: timed out while waiting"
6304                                 "for HBA to recover.\n");
6305                 return -ENODEV;
6306         }
6307         spin_unlock_irqrestore(&instance->hba_lock, flags);
6308
6309         mutex_lock(&instance->aen_mutex);
6310         error = megasas_register_aen(instance, aen.seq_num,
6311                                      aen.class_locale_word);
6312         mutex_unlock(&instance->aen_mutex);
6313         return error;
6314 }
6315
6316 /**
6317  * megasas_mgmt_ioctl - char node ioctl entry point
6318  */
6319 static long
6320 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6321 {
6322         switch (cmd) {
6323         case MEGASAS_IOC_FIRMWARE:
6324                 return megasas_mgmt_ioctl_fw(file, arg);
6325
6326         case MEGASAS_IOC_GET_AEN:
6327                 return megasas_mgmt_ioctl_aen(file, arg);
6328         }
6329
6330         return -ENOTTY;
6331 }
6332
6333 #ifdef CONFIG_COMPAT
6334 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
6335 {
6336         struct compat_megasas_iocpacket __user *cioc =
6337             (struct compat_megasas_iocpacket __user *)arg;
6338         struct megasas_iocpacket __user *ioc =
6339             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
6340         int i;
6341         int error = 0;
6342         compat_uptr_t ptr;
6343
6344         if (clear_user(ioc, sizeof(*ioc)))
6345                 return -EFAULT;
6346
6347         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
6348             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
6349             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
6350             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
6351             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
6352             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
6353                 return -EFAULT;
6354
6355         /*
6356          * The sense_ptr is used in megasas_mgmt_fw_ioctl only when
6357          * sense_len is not null, so prepare the 64bit value under
6358          * the same condition.
6359          */
6360         if (ioc->sense_len) {
6361                 void __user **sense_ioc_ptr =
6362                         (void __user **)(ioc->frame.raw + ioc->sense_off);
6363                 compat_uptr_t *sense_cioc_ptr =
6364                         (compat_uptr_t *)(cioc->frame.raw + cioc->sense_off);
6365                 if (get_user(ptr, sense_cioc_ptr) ||
6366                     put_user(compat_ptr(ptr), sense_ioc_ptr))
6367                         return -EFAULT;
6368         }
6369
6370         for (i = 0; i < MAX_IOCTL_SGE; i++) {
6371                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
6372                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
6373                     copy_in_user(&ioc->sgl[i].iov_len,
6374                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
6375                         return -EFAULT;
6376         }
6377
6378         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
6379
6380         if (copy_in_user(&cioc->frame.hdr.cmd_status,
6381                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
6382                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
6383                 return -EFAULT;
6384         }
6385         return error;
6386 }
6387
6388 static long
6389 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
6390                           unsigned long arg)
6391 {
6392         switch (cmd) {
6393         case MEGASAS_IOC_FIRMWARE32:
6394                 return megasas_mgmt_compat_ioctl_fw(file, arg);
6395         case MEGASAS_IOC_GET_AEN:
6396                 return megasas_mgmt_ioctl_aen(file, arg);
6397         }
6398
6399         return -ENOTTY;
6400 }
6401 #endif
6402
6403 /*
6404  * File operations structure for management interface
6405  */
6406 static const struct file_operations megasas_mgmt_fops = {
6407         .owner = THIS_MODULE,
6408         .open = megasas_mgmt_open,
6409         .fasync = megasas_mgmt_fasync,
6410         .unlocked_ioctl = megasas_mgmt_ioctl,
6411         .poll = megasas_mgmt_poll,
6412 #ifdef CONFIG_COMPAT
6413         .compat_ioctl = megasas_mgmt_compat_ioctl,
6414 #endif
6415         .llseek = noop_llseek,
6416 };
6417
6418 /*
6419  * PCI hotplug support registration structure
6420  */
6421 static struct pci_driver megasas_pci_driver = {
6422
6423         .name = "megaraid_sas",
6424         .id_table = megasas_pci_table,
6425         .probe = megasas_probe_one,
6426         .remove = megasas_detach_one,
6427         .suspend = megasas_suspend,
6428         .resume = megasas_resume,
6429         .shutdown = megasas_shutdown,
6430 };
6431
6432 /*
6433  * Sysfs driver attributes
6434  */
6435 static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
6436 {
6437         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
6438                         MEGASAS_VERSION);
6439 }
6440
6441 static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
6442
6443 static ssize_t
6444 megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
6445 {
6446         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
6447                 MEGASAS_RELDATE);
6448 }
6449
6450 static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date, NULL);
6451
6452 static ssize_t
6453 megasas_sysfs_show_support_poll_for_event(struct device_driver *dd, char *buf)
6454 {
6455         return sprintf(buf, "%u\n", support_poll_for_event);
6456 }
6457
6458 static DRIVER_ATTR(support_poll_for_event, S_IRUGO,
6459                         megasas_sysfs_show_support_poll_for_event, NULL);
6460
6461  static ssize_t
6462 megasas_sysfs_show_support_device_change(struct device_driver *dd, char *buf)
6463 {
6464         return sprintf(buf, "%u\n", support_device_change);
6465 }
6466
6467 static DRIVER_ATTR(support_device_change, S_IRUGO,
6468                         megasas_sysfs_show_support_device_change, NULL);
6469
6470 static ssize_t
6471 megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
6472 {
6473         return sprintf(buf, "%u\n", megasas_dbg_lvl);
6474 }
6475
6476 static ssize_t
6477 megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
6478 {
6479         int retval = count;
6480         if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
6481                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
6482                 retval = -EINVAL;
6483         }
6484         return retval;
6485 }
6486
6487 static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUSR, megasas_sysfs_show_dbg_lvl,
6488                 megasas_sysfs_set_dbg_lvl);
6489
6490 static void
6491 megasas_aen_polling(struct work_struct *work)
6492 {
6493         struct megasas_aen_event *ev =
6494                 container_of(work, struct megasas_aen_event, hotplug_work.work);
6495         struct megasas_instance *instance = ev->instance;
6496         union megasas_evt_class_locale class_locale;
6497         struct  Scsi_Host *host;
6498         struct  scsi_device *sdev1;
6499         u16     pd_index = 0;
6500         u16     ld_index = 0;
6501         int     i, j, doscan = 0;
6502         u32 seq_num, wait_time = MEGASAS_RESET_WAIT_TIME;
6503         int error;
6504
6505         if (!instance) {
6506                 printk(KERN_ERR "invalid instance!\n");
6507                 kfree(ev);
6508                 return;
6509         }
6510
6511         /* Adjust event workqueue thread wait time for VF mode */
6512         if (instance->requestorId)
6513                 wait_time = MEGASAS_ROUTINE_WAIT_TIME_VF;
6514
6515         /* Don't run the event workqueue thread if OCR is running */
6516         for (i = 0; i < wait_time; i++) {
6517                 if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL)
6518                         break;
6519                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
6520                         printk(KERN_NOTICE "megasas: %s waiting for "
6521                                "controller reset to finish for scsi%d\n",
6522                                __func__, instance->host->host_no);
6523                 }
6524                 msleep(1000);
6525         }
6526
6527         instance->ev = NULL;
6528         host = instance->host;
6529         if (instance->evt_detail) {
6530
6531                 switch (le32_to_cpu(instance->evt_detail->code)) {
6532                 case MR_EVT_PD_INSERTED:
6533                         if (megasas_get_pd_list(instance) == 0) {
6534                         for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
6535                                 for (j = 0;
6536                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
6537                                 j++) {
6538
6539                                 pd_index =
6540                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6541
6542                                 sdev1 =
6543                                 scsi_device_lookup(host, i, j, 0);
6544
6545                                 if (instance->pd_list[pd_index].driveState
6546                                                 == MR_PD_STATE_SYSTEM) {
6547                                                 if (!sdev1) {
6548                                                 scsi_add_device(host, i, j, 0);
6549                                                 }
6550
6551                                         if (sdev1)
6552                                                 scsi_device_put(sdev1);
6553                                         }
6554                                 }
6555                         }
6556                         }
6557                         doscan = 0;
6558                         break;
6559
6560                 case MR_EVT_PD_REMOVED:
6561                         if (megasas_get_pd_list(instance) == 0) {
6562                         for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
6563                                 for (j = 0;
6564                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
6565                                 j++) {
6566
6567                                 pd_index =
6568                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6569
6570                                 sdev1 =
6571                                 scsi_device_lookup(host, i, j, 0);
6572
6573                                 if (instance->pd_list[pd_index].driveState
6574                                         == MR_PD_STATE_SYSTEM) {
6575                                         if (sdev1) {
6576                                                 scsi_device_put(sdev1);
6577                                         }
6578                                 } else {
6579                                         if (sdev1) {
6580                                                 scsi_remove_device(sdev1);
6581                                                 scsi_device_put(sdev1);
6582                                         }
6583                                 }
6584                                 }
6585                         }
6586                         }
6587                         doscan = 0;
6588                         break;
6589
6590                 case MR_EVT_LD_OFFLINE:
6591                 case MR_EVT_CFG_CLEARED:
6592                 case MR_EVT_LD_DELETED:
6593                         if (!instance->requestorId ||
6594                             (instance->requestorId &&
6595                              megasas_get_ld_vf_affiliation(instance, 0))) {
6596                                 if (megasas_ld_list_query(instance,
6597                                                           MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
6598                                         megasas_get_ld_list(instance);
6599                                 for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
6600                                         for (j = 0;
6601                                              j < MEGASAS_MAX_DEV_PER_CHANNEL;
6602                                              j++) {
6603
6604                                                 ld_index =
6605                                                         (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6606
6607                                                 sdev1 = scsi_device_lookup(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6608
6609                                                 if (instance->ld_ids[ld_index]
6610                                                     != 0xff) {
6611                                                         if (sdev1)
6612                                                                 scsi_device_put(sdev1);
6613                                                 } else {
6614                                                         if (sdev1) {
6615                                                                 scsi_remove_device(sdev1);
6616                                                                 scsi_device_put(sdev1);
6617                                                         }
6618                                                 }
6619                                         }
6620                                 }
6621                                 doscan = 0;
6622                         }
6623                         break;
6624                 case MR_EVT_LD_CREATED:
6625                         if (!instance->requestorId ||
6626                             (instance->requestorId &&
6627                              megasas_get_ld_vf_affiliation(instance, 0))) {
6628                                 if (megasas_ld_list_query(instance,
6629                                                           MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
6630                                         megasas_get_ld_list(instance);
6631                                 for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
6632                                         for (j = 0;
6633                                              j < MEGASAS_MAX_DEV_PER_CHANNEL;
6634                                              j++) {
6635                                                 ld_index =
6636                                                         (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6637
6638                                                 sdev1 = scsi_device_lookup(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6639
6640                                                 if (instance->ld_ids[ld_index]
6641                                                     != 0xff) {
6642                                                         if (!sdev1)
6643                                                                 scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6644                                                 }
6645                                                 if (sdev1)
6646                                                         scsi_device_put(sdev1);
6647                                         }
6648                                 }
6649                                 doscan = 0;
6650                         }
6651                         break;
6652                 case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
6653                 case MR_EVT_FOREIGN_CFG_IMPORTED:
6654                 case MR_EVT_LD_STATE_CHANGE:
6655                         doscan = 1;
6656                         break;
6657                 default:
6658                         doscan = 0;
6659                         break;
6660                 }
6661         } else {
6662                 printk(KERN_ERR "invalid evt_detail!\n");
6663                 kfree(ev);
6664                 return;
6665         }
6666
6667         if (doscan) {
6668                 printk(KERN_INFO "megaraid_sas: scanning for scsi%d...\n",
6669                        instance->host->host_no);
6670                 if (megasas_get_pd_list(instance) == 0) {
6671                         for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
6672                                 for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
6673                                         pd_index = i*MEGASAS_MAX_DEV_PER_CHANNEL + j;
6674                                         sdev1 = scsi_device_lookup(host, i, j, 0);
6675                                         if (instance->pd_list[pd_index].driveState ==
6676                                             MR_PD_STATE_SYSTEM) {
6677                                                 if (!sdev1) {
6678                                                         scsi_add_device(host, i, j, 0);
6679                                                 }
6680                                                 if (sdev1)
6681                                                         scsi_device_put(sdev1);
6682                                         } else {
6683                                                 if (sdev1) {
6684                                                         scsi_remove_device(sdev1);
6685                                                         scsi_device_put(sdev1);
6686                                                 }
6687                                         }
6688                                 }
6689                         }
6690                 }
6691
6692                 if (!instance->requestorId ||
6693                     (instance->requestorId &&
6694                      megasas_get_ld_vf_affiliation(instance, 0))) {
6695                         if (megasas_ld_list_query(instance,
6696                                                   MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
6697                                 megasas_get_ld_list(instance);
6698                         for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
6699                                 for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL;
6700                                      j++) {
6701                                         ld_index =
6702                                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6703
6704                                         sdev1 = scsi_device_lookup(host,
6705                                                                    MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6706                                         if (instance->ld_ids[ld_index]
6707                                             != 0xff) {
6708                                                 if (!sdev1)
6709                                                         scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6710                                                 else
6711                                                         scsi_device_put(sdev1);
6712                                         } else {
6713                                                 if (sdev1) {
6714                                                         scsi_remove_device(sdev1);
6715                                                         scsi_device_put(sdev1);
6716                                                 }
6717                                         }
6718                                 }
6719                         }
6720                 }
6721         }
6722
6723         if ( instance->aen_cmd != NULL ) {
6724                 kfree(ev);
6725                 return ;
6726         }
6727
6728         seq_num = le32_to_cpu(instance->evt_detail->seq_num) + 1;
6729
6730         /* Register AEN with FW for latest sequence number plus 1 */
6731         class_locale.members.reserved = 0;
6732         class_locale.members.locale = MR_EVT_LOCALE_ALL;
6733         class_locale.members.class = MR_EVT_CLASS_DEBUG;
6734         mutex_lock(&instance->aen_mutex);
6735         error = megasas_register_aen(instance, seq_num,
6736                                         class_locale.word);
6737         mutex_unlock(&instance->aen_mutex);
6738
6739         if (error)
6740                 printk(KERN_ERR "register aen failed error %x\n", error);
6741
6742         kfree(ev);
6743 }
6744
6745 /**
6746  * megasas_init - Driver load entry point
6747  */
6748 static int __init megasas_init(void)
6749 {
6750         int rval;
6751
6752         /*
6753          * Announce driver version and other information
6754          */
6755         pr_info("megasas: %s\n", MEGASAS_VERSION);
6756
6757         spin_lock_init(&poll_aen_lock);
6758
6759         support_poll_for_event = 2;
6760         support_device_change = 1;
6761
6762         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
6763
6764         /*
6765          * Register character device node
6766          */
6767         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
6768
6769         if (rval < 0) {
6770                 printk(KERN_DEBUG "megasas: failed to open device node\n");
6771                 return rval;
6772         }
6773
6774         megasas_mgmt_majorno = rval;
6775
6776         /*
6777          * Register ourselves as PCI hotplug module
6778          */
6779         rval = pci_register_driver(&megasas_pci_driver);
6780
6781         if (rval) {
6782                 printk(KERN_DEBUG "megasas: PCI hotplug registration failed \n");
6783                 goto err_pcidrv;
6784         }
6785
6786         rval = driver_create_file(&megasas_pci_driver.driver,
6787                                   &driver_attr_version);
6788         if (rval)
6789                 goto err_dcf_attr_ver;
6790
6791         rval = driver_create_file(&megasas_pci_driver.driver,
6792                                   &driver_attr_release_date);
6793         if (rval)
6794                 goto err_dcf_rel_date;
6795
6796         rval = driver_create_file(&megasas_pci_driver.driver,
6797                                 &driver_attr_support_poll_for_event);
6798         if (rval)
6799                 goto err_dcf_support_poll_for_event;
6800
6801         rval = driver_create_file(&megasas_pci_driver.driver,
6802                                   &driver_attr_dbg_lvl);
6803         if (rval)
6804                 goto err_dcf_dbg_lvl;
6805         rval = driver_create_file(&megasas_pci_driver.driver,
6806                                 &driver_attr_support_device_change);
6807         if (rval)
6808                 goto err_dcf_support_device_change;
6809
6810         return rval;
6811
6812 err_dcf_support_device_change:
6813         driver_remove_file(&megasas_pci_driver.driver,
6814                            &driver_attr_dbg_lvl);
6815 err_dcf_dbg_lvl:
6816         driver_remove_file(&megasas_pci_driver.driver,
6817                         &driver_attr_support_poll_for_event);
6818 err_dcf_support_poll_for_event:
6819         driver_remove_file(&megasas_pci_driver.driver,
6820                            &driver_attr_release_date);
6821 err_dcf_rel_date:
6822         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
6823 err_dcf_attr_ver:
6824         pci_unregister_driver(&megasas_pci_driver);
6825 err_pcidrv:
6826         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
6827         return rval;
6828 }
6829
6830 /**
6831  * megasas_exit - Driver unload entry point
6832  */
6833 static void __exit megasas_exit(void)
6834 {
6835         driver_remove_file(&megasas_pci_driver.driver,
6836                            &driver_attr_dbg_lvl);
6837         driver_remove_file(&megasas_pci_driver.driver,
6838                         &driver_attr_support_poll_for_event);
6839         driver_remove_file(&megasas_pci_driver.driver,
6840                         &driver_attr_support_device_change);
6841         driver_remove_file(&megasas_pci_driver.driver,
6842                            &driver_attr_release_date);
6843         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
6844
6845         pci_unregister_driver(&megasas_pci_driver);
6846         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
6847 }
6848
6849 module_init(megasas_init);
6850 module_exit(megasas_exit);