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