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