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