GNU Linux-libre 5.10.153-gnu1
[releases.git] / drivers / scsi / megaraid / megaraid_sas_base.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Linux MegaRAID driver for SAS based RAID controllers
4  *
5  *  Copyright (c) 2003-2013  LSI Corporation
6  *  Copyright (c) 2013-2016  Avago Technologies
7  *  Copyright (c) 2016-2018  Broadcom Inc.
8  *
9  *  Authors: Broadcom Inc.
10  *           Sreenivas Bagalkote
11  *           Sumant Patro
12  *           Bo Yang
13  *           Adam Radford
14  *           Kashyap Desai <kashyap.desai@broadcom.com>
15  *           Sumit Saxena <sumit.saxena@broadcom.com>
16  *
17  *  Send feedback to: megaraidlinux.pdl@broadcom.com
18  */
19
20 #include <linux/kernel.h>
21 #include <linux/types.h>
22 #include <linux/pci.h>
23 #include <linux/list.h>
24 #include <linux/moduleparam.h>
25 #include <linux/module.h>
26 #include <linux/spinlock.h>
27 #include <linux/interrupt.h>
28 #include <linux/delay.h>
29 #include <linux/uio.h>
30 #include <linux/slab.h>
31 #include <linux/uaccess.h>
32 #include <asm/unaligned.h>
33 #include <linux/fs.h>
34 #include <linux/compat.h>
35 #include <linux/blkdev.h>
36 #include <linux/mutex.h>
37 #include <linux/poll.h>
38 #include <linux/vmalloc.h>
39 #include <linux/irq_poll.h>
40
41 #include <scsi/scsi.h>
42 #include <scsi/scsi_cmnd.h>
43 #include <scsi/scsi_device.h>
44 #include <scsi/scsi_host.h>
45 #include <scsi/scsi_tcq.h>
46 #include <scsi/scsi_dbg.h>
47 #include "megaraid_sas_fusion.h"
48 #include "megaraid_sas.h"
49
50 /*
51  * Number of sectors per IO command
52  * Will be set in megasas_init_mfi if user does not provide
53  */
54 static unsigned int max_sectors;
55 module_param_named(max_sectors, max_sectors, int, 0444);
56 MODULE_PARM_DESC(max_sectors,
57         "Maximum number of sectors per IO command");
58
59 static int msix_disable;
60 module_param(msix_disable, int, 0444);
61 MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0");
62
63 static unsigned int msix_vectors;
64 module_param(msix_vectors, int, 0444);
65 MODULE_PARM_DESC(msix_vectors, "MSI-X max vector count. Default: Set by FW");
66
67 static int allow_vf_ioctls;
68 module_param(allow_vf_ioctls, int, 0444);
69 MODULE_PARM_DESC(allow_vf_ioctls, "Allow ioctls in SR-IOV VF mode. Default: 0");
70
71 static unsigned int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH;
72 module_param(throttlequeuedepth, int, 0444);
73 MODULE_PARM_DESC(throttlequeuedepth,
74         "Adapter queue depth when throttled due to I/O timeout. Default: 16");
75
76 unsigned int resetwaittime = MEGASAS_RESET_WAIT_TIME;
77 module_param(resetwaittime, int, 0444);
78 MODULE_PARM_DESC(resetwaittime, "Wait time in (1-180s) after I/O timeout before resetting adapter. Default: 180s");
79
80 static int smp_affinity_enable = 1;
81 module_param(smp_affinity_enable, int, 0444);
82 MODULE_PARM_DESC(smp_affinity_enable, "SMP affinity feature enable/disable Default: enable(1)");
83
84 static int rdpq_enable = 1;
85 module_param(rdpq_enable, int, 0444);
86 MODULE_PARM_DESC(rdpq_enable, "Allocate reply queue in chunks for large queue depth enable/disable Default: enable(1)");
87
88 unsigned int dual_qdepth_disable;
89 module_param(dual_qdepth_disable, int, 0444);
90 MODULE_PARM_DESC(dual_qdepth_disable, "Disable dual queue depth feature. Default: 0");
91
92 static unsigned int scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT;
93 module_param(scmd_timeout, int, 0444);
94 MODULE_PARM_DESC(scmd_timeout, "scsi command timeout (10-90s), default 90s. See megasas_reset_timer.");
95
96 int perf_mode = -1;
97 module_param(perf_mode, int, 0444);
98 MODULE_PARM_DESC(perf_mode, "Performance mode (only for Aero adapters), options:\n\t\t"
99                 "0 - balanced: High iops and low latency queues are allocated &\n\t\t"
100                 "interrupt coalescing is enabled only on high iops queues\n\t\t"
101                 "1 - iops: High iops queues are not allocated &\n\t\t"
102                 "interrupt coalescing is enabled on all queues\n\t\t"
103                 "2 - latency: High iops queues are not allocated &\n\t\t"
104                 "interrupt coalescing is disabled on all queues\n\t\t"
105                 "default mode is 'balanced'"
106                 );
107
108 int event_log_level = MFI_EVT_CLASS_CRITICAL;
109 module_param(event_log_level, int, 0644);
110 MODULE_PARM_DESC(event_log_level, "Asynchronous event logging level- range is: -2(CLASS_DEBUG) to 4(CLASS_DEAD), Default: 2(CLASS_CRITICAL)");
111
112 unsigned int enable_sdev_max_qd;
113 module_param(enable_sdev_max_qd, int, 0444);
114 MODULE_PARM_DESC(enable_sdev_max_qd, "Enable sdev max qd as can_queue. Default: 0");
115
116 MODULE_LICENSE("GPL");
117 MODULE_VERSION(MEGASAS_VERSION);
118 MODULE_AUTHOR("megaraidlinux.pdl@broadcom.com");
119 MODULE_DESCRIPTION("Broadcom MegaRAID SAS Driver");
120
121 int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
122 static int megasas_get_pd_list(struct megasas_instance *instance);
123 static int megasas_ld_list_query(struct megasas_instance *instance,
124                                  u8 query_type);
125 static int megasas_issue_init_mfi(struct megasas_instance *instance);
126 static int megasas_register_aen(struct megasas_instance *instance,
127                                 u32 seq_num, u32 class_locale_word);
128 static void megasas_get_pd_info(struct megasas_instance *instance,
129                                 struct scsi_device *sdev);
130 static void
131 megasas_set_ld_removed_by_fw(struct megasas_instance *instance);
132
133 /*
134  * PCI ID table for all supported controllers
135  */
136 static struct pci_device_id megasas_pci_table[] = {
137
138         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
139         /* xscale IOP */
140         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
141         /* ppc IOP */
142         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
143         /* ppc IOP */
144         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
145         /* gen2*/
146         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
147         /* gen2*/
148         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)},
149         /* skinny*/
150         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)},
151         /* skinny*/
152         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
153         /* xscale IOP, vega */
154         {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
155         /* xscale IOP */
156         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)},
157         /* Fusion */
158         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_PLASMA)},
159         /* Plasma */
160         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)},
161         /* Invader */
162         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FURY)},
163         /* Fury */
164         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER)},
165         /* Intruder */
166         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER_24)},
167         /* Intruder 24 port*/
168         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_52)},
169         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_53)},
170         /* VENTURA */
171         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA)},
172         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER)},
173         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_HARPOON)},
174         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_TOMCAT)},
175         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA_4PORT)},
176         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER_4PORT)},
177         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E1)},
178         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E2)},
179         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E5)},
180         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E6)},
181         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E0)},
182         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E3)},
183         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E4)},
184         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E7)},
185         {}
186 };
187
188 MODULE_DEVICE_TABLE(pci, megasas_pci_table);
189
190 static int megasas_mgmt_majorno;
191 struct megasas_mgmt_info megasas_mgmt_info;
192 static struct fasync_struct *megasas_async_queue;
193 static DEFINE_MUTEX(megasas_async_queue_mutex);
194
195 static int megasas_poll_wait_aen;
196 static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait);
197 static u32 support_poll_for_event;
198 u32 megasas_dbg_lvl;
199 static u32 support_device_change;
200 static bool support_nvme_encapsulation;
201 static bool support_pci_lane_margining;
202
203 /* define lock for aen poll */
204 static spinlock_t poll_aen_lock;
205
206 extern struct dentry *megasas_debugfs_root;
207
208 void
209 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
210                      u8 alt_status);
211 static u32
212 megasas_read_fw_status_reg_gen2(struct megasas_instance *instance);
213 static int
214 megasas_adp_reset_gen2(struct megasas_instance *instance,
215                        struct megasas_register_set __iomem *reg_set);
216 static irqreturn_t megasas_isr(int irq, void *devp);
217 static u32
218 megasas_init_adapter_mfi(struct megasas_instance *instance);
219 u32
220 megasas_build_and_issue_cmd(struct megasas_instance *instance,
221                             struct scsi_cmnd *scmd);
222 static void megasas_complete_cmd_dpc(unsigned long instance_addr);
223 int
224 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
225         int seconds);
226 void megasas_fusion_ocr_wq(struct work_struct *work);
227 static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
228                                          int initial);
229 static int
230 megasas_set_dma_mask(struct megasas_instance *instance);
231 static int
232 megasas_alloc_ctrl_mem(struct megasas_instance *instance);
233 static inline void
234 megasas_free_ctrl_mem(struct megasas_instance *instance);
235 static inline int
236 megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance);
237 static inline void
238 megasas_free_ctrl_dma_buffers(struct megasas_instance *instance);
239 static inline void
240 megasas_init_ctrl_params(struct megasas_instance *instance);
241
242 u32 megasas_readl(struct megasas_instance *instance,
243                   const volatile void __iomem *addr)
244 {
245         u32 i = 0, ret_val;
246         /*
247          * Due to a HW errata in Aero controllers, reads to certain
248          * Fusion registers could intermittently return all zeroes.
249          * This behavior is transient in nature and subsequent reads will
250          * return valid value. As a workaround in driver, retry readl for
251          * upto three times until a non-zero value is read.
252          */
253         if (instance->adapter_type == AERO_SERIES) {
254                 do {
255                         ret_val = readl(addr);
256                         i++;
257                 } while (ret_val == 0 && i < 3);
258                 return ret_val;
259         } else {
260                 return readl(addr);
261         }
262 }
263
264 /**
265  * megasas_set_dma_settings -   Populate DMA address, length and flags for DCMDs
266  * @instance:                   Adapter soft state
267  * @dcmd:                       DCMD frame inside MFI command
268  * @dma_addr:                   DMA address of buffer to be passed to FW
269  * @dma_len:                    Length of DMA buffer to be passed to FW
270  * @return:                     void
271  */
272 void megasas_set_dma_settings(struct megasas_instance *instance,
273                               struct megasas_dcmd_frame *dcmd,
274                               dma_addr_t dma_addr, u32 dma_len)
275 {
276         if (instance->consistent_mask_64bit) {
277                 dcmd->sgl.sge64[0].phys_addr = cpu_to_le64(dma_addr);
278                 dcmd->sgl.sge64[0].length = cpu_to_le32(dma_len);
279                 dcmd->flags = cpu_to_le16(dcmd->flags | MFI_FRAME_SGL64);
280
281         } else {
282                 dcmd->sgl.sge32[0].phys_addr =
283                                 cpu_to_le32(lower_32_bits(dma_addr));
284                 dcmd->sgl.sge32[0].length = cpu_to_le32(dma_len);
285                 dcmd->flags = cpu_to_le16(dcmd->flags);
286         }
287 }
288
289 static void
290 megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
291 {
292         instance->instancet->fire_cmd(instance,
293                 cmd->frame_phys_addr, 0, instance->reg_set);
294         return;
295 }
296
297 /**
298  * megasas_get_cmd -    Get a command from the free pool
299  * @instance:           Adapter soft state
300  *
301  * Returns a free command from the pool
302  */
303 struct megasas_cmd *megasas_get_cmd(struct megasas_instance
304                                                   *instance)
305 {
306         unsigned long flags;
307         struct megasas_cmd *cmd = NULL;
308
309         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
310
311         if (!list_empty(&instance->cmd_pool)) {
312                 cmd = list_entry((&instance->cmd_pool)->next,
313                                  struct megasas_cmd, list);
314                 list_del_init(&cmd->list);
315         } else {
316                 dev_err(&instance->pdev->dev, "Command pool empty!\n");
317         }
318
319         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
320         return cmd;
321 }
322
323 /**
324  * megasas_return_cmd - Return a cmd to free command pool
325  * @instance:           Adapter soft state
326  * @cmd:                Command packet to be returned to free command pool
327  */
328 void
329 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
330 {
331         unsigned long flags;
332         u32 blk_tags;
333         struct megasas_cmd_fusion *cmd_fusion;
334         struct fusion_context *fusion = instance->ctrl_context;
335
336         /* This flag is used only for fusion adapter.
337          * Wait for Interrupt for Polled mode DCMD
338          */
339         if (cmd->flags & DRV_DCMD_POLLED_MODE)
340                 return;
341
342         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
343
344         if (fusion) {
345                 blk_tags = instance->max_scsi_cmds + cmd->index;
346                 cmd_fusion = fusion->cmd_list[blk_tags];
347                 megasas_return_cmd_fusion(instance, cmd_fusion);
348         }
349         cmd->scmd = NULL;
350         cmd->frame_count = 0;
351         cmd->flags = 0;
352         memset(cmd->frame, 0, instance->mfi_frame_size);
353         cmd->frame->io.context = cpu_to_le32(cmd->index);
354         if (!fusion && reset_devices)
355                 cmd->frame->hdr.cmd = MFI_CMD_INVALID;
356         list_add(&cmd->list, (&instance->cmd_pool)->next);
357
358         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
359
360 }
361
362 static const char *
363 format_timestamp(uint32_t timestamp)
364 {
365         static char buffer[32];
366
367         if ((timestamp & 0xff000000) == 0xff000000)
368                 snprintf(buffer, sizeof(buffer), "boot + %us", timestamp &
369                 0x00ffffff);
370         else
371                 snprintf(buffer, sizeof(buffer), "%us", timestamp);
372         return buffer;
373 }
374
375 static const char *
376 format_class(int8_t class)
377 {
378         static char buffer[6];
379
380         switch (class) {
381         case MFI_EVT_CLASS_DEBUG:
382                 return "debug";
383         case MFI_EVT_CLASS_PROGRESS:
384                 return "progress";
385         case MFI_EVT_CLASS_INFO:
386                 return "info";
387         case MFI_EVT_CLASS_WARNING:
388                 return "WARN";
389         case MFI_EVT_CLASS_CRITICAL:
390                 return "CRIT";
391         case MFI_EVT_CLASS_FATAL:
392                 return "FATAL";
393         case MFI_EVT_CLASS_DEAD:
394                 return "DEAD";
395         default:
396                 snprintf(buffer, sizeof(buffer), "%d", class);
397                 return buffer;
398         }
399 }
400
401 /**
402   * megasas_decode_evt: Decode FW AEN event and print critical event
403   * for information.
404   * @instance:                  Adapter soft state
405   */
406 static void
407 megasas_decode_evt(struct megasas_instance *instance)
408 {
409         struct megasas_evt_detail *evt_detail = instance->evt_detail;
410         union megasas_evt_class_locale class_locale;
411         class_locale.word = le32_to_cpu(evt_detail->cl.word);
412
413         if ((event_log_level < MFI_EVT_CLASS_DEBUG) ||
414             (event_log_level > MFI_EVT_CLASS_DEAD)) {
415                 printk(KERN_WARNING "megaraid_sas: provided event log level is out of range, setting it to default 2(CLASS_CRITICAL), permissible range is: -2 to 4\n");
416                 event_log_level = MFI_EVT_CLASS_CRITICAL;
417         }
418
419         if (class_locale.members.class >= event_log_level)
420                 dev_info(&instance->pdev->dev, "%d (%s/0x%04x/%s) - %s\n",
421                         le32_to_cpu(evt_detail->seq_num),
422                         format_timestamp(le32_to_cpu(evt_detail->time_stamp)),
423                         (class_locale.members.locale),
424                         format_class(class_locale.members.class),
425                         evt_detail->description);
426
427         if (megasas_dbg_lvl & LD_PD_DEBUG)
428                 dev_info(&instance->pdev->dev,
429                          "evt_detail.args.ld.target_id/index %d/%d\n",
430                          evt_detail->args.ld.target_id, evt_detail->args.ld.ld_index);
431
432 }
433
434 /*
435  * The following functions are defined for xscale
436  * (deviceid : 1064R, PERC5) controllers
437  */
438
439 /**
440  * megasas_enable_intr_xscale - Enables interrupts
441  * @instance:   Adapter soft state
442  */
443 static inline void
444 megasas_enable_intr_xscale(struct megasas_instance *instance)
445 {
446         struct megasas_register_set __iomem *regs;
447
448         regs = instance->reg_set;
449         writel(0, &(regs)->outbound_intr_mask);
450
451         /* Dummy readl to force pci flush */
452         readl(&regs->outbound_intr_mask);
453 }
454
455 /**
456  * megasas_disable_intr_xscale -Disables interrupt
457  * @instance:   Adapter soft state
458  */
459 static inline void
460 megasas_disable_intr_xscale(struct megasas_instance *instance)
461 {
462         struct megasas_register_set __iomem *regs;
463         u32 mask = 0x1f;
464
465         regs = instance->reg_set;
466         writel(mask, &regs->outbound_intr_mask);
467         /* Dummy readl to force pci flush */
468         readl(&regs->outbound_intr_mask);
469 }
470
471 /**
472  * megasas_read_fw_status_reg_xscale - returns the current FW status value
473  * @instance:   Adapter soft state
474  */
475 static u32
476 megasas_read_fw_status_reg_xscale(struct megasas_instance *instance)
477 {
478         return readl(&instance->reg_set->outbound_msg_0);
479 }
480 /**
481  * megasas_clear_interrupt_xscale -     Check & clear interrupt
482  * @instance:   Adapter soft state
483  */
484 static int
485 megasas_clear_intr_xscale(struct megasas_instance *instance)
486 {
487         u32 status;
488         u32 mfiStatus = 0;
489         struct megasas_register_set __iomem *regs;
490         regs = instance->reg_set;
491
492         /*
493          * Check if it is our interrupt
494          */
495         status = readl(&regs->outbound_intr_status);
496
497         if (status & MFI_OB_INTR_STATUS_MASK)
498                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
499         if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT)
500                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
501
502         /*
503          * Clear the interrupt by writing back the same value
504          */
505         if (mfiStatus)
506                 writel(status, &regs->outbound_intr_status);
507
508         /* Dummy readl to force pci flush */
509         readl(&regs->outbound_intr_status);
510
511         return mfiStatus;
512 }
513
514 /**
515  * megasas_fire_cmd_xscale -    Sends command to the FW
516  * @instance:           Adapter soft state
517  * @frame_phys_addr :   Physical address of cmd
518  * @frame_count :       Number of frames for the command
519  * @regs :              MFI register set
520  */
521 static inline void
522 megasas_fire_cmd_xscale(struct megasas_instance *instance,
523                 dma_addr_t frame_phys_addr,
524                 u32 frame_count,
525                 struct megasas_register_set __iomem *regs)
526 {
527         unsigned long flags;
528
529         spin_lock_irqsave(&instance->hba_lock, flags);
530         writel((frame_phys_addr >> 3)|(frame_count),
531                &(regs)->inbound_queue_port);
532         spin_unlock_irqrestore(&instance->hba_lock, flags);
533 }
534
535 /**
536  * megasas_adp_reset_xscale -  For controller reset
537  * @instance:   Adapter soft state
538  * @regs:       MFI register set
539  */
540 static int
541 megasas_adp_reset_xscale(struct megasas_instance *instance,
542         struct megasas_register_set __iomem *regs)
543 {
544         u32 i;
545         u32 pcidata;
546
547         writel(MFI_ADP_RESET, &regs->inbound_doorbell);
548
549         for (i = 0; i < 3; i++)
550                 msleep(1000); /* sleep for 3 secs */
551         pcidata  = 0;
552         pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata);
553         dev_notice(&instance->pdev->dev, "pcidata = %x\n", pcidata);
554         if (pcidata & 0x2) {
555                 dev_notice(&instance->pdev->dev, "mfi 1068 offset read=%x\n", pcidata);
556                 pcidata &= ~0x2;
557                 pci_write_config_dword(instance->pdev,
558                                 MFI_1068_PCSR_OFFSET, pcidata);
559
560                 for (i = 0; i < 2; i++)
561                         msleep(1000); /* need to wait 2 secs again */
562
563                 pcidata  = 0;
564                 pci_read_config_dword(instance->pdev,
565                                 MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata);
566                 dev_notice(&instance->pdev->dev, "1068 offset handshake read=%x\n", pcidata);
567                 if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) {
568                         dev_notice(&instance->pdev->dev, "1068 offset pcidt=%x\n", pcidata);
569                         pcidata = 0;
570                         pci_write_config_dword(instance->pdev,
571                                 MFI_1068_FW_HANDSHAKE_OFFSET, pcidata);
572                 }
573         }
574         return 0;
575 }
576
577 /**
578  * megasas_check_reset_xscale - For controller reset check
579  * @instance:   Adapter soft state
580  * @regs:       MFI register set
581  */
582 static int
583 megasas_check_reset_xscale(struct megasas_instance *instance,
584                 struct megasas_register_set __iomem *regs)
585 {
586         if ((atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) &&
587             (le32_to_cpu(*instance->consumer) ==
588                 MEGASAS_ADPRESET_INPROG_SIGN))
589                 return 1;
590         return 0;
591 }
592
593 static struct megasas_instance_template megasas_instance_template_xscale = {
594
595         .fire_cmd = megasas_fire_cmd_xscale,
596         .enable_intr = megasas_enable_intr_xscale,
597         .disable_intr = megasas_disable_intr_xscale,
598         .clear_intr = megasas_clear_intr_xscale,
599         .read_fw_status_reg = megasas_read_fw_status_reg_xscale,
600         .adp_reset = megasas_adp_reset_xscale,
601         .check_reset = megasas_check_reset_xscale,
602         .service_isr = megasas_isr,
603         .tasklet = megasas_complete_cmd_dpc,
604         .init_adapter = megasas_init_adapter_mfi,
605         .build_and_issue_cmd = megasas_build_and_issue_cmd,
606         .issue_dcmd = megasas_issue_dcmd,
607 };
608
609 /*
610  * This is the end of set of functions & definitions specific
611  * to xscale (deviceid : 1064R, PERC5) controllers
612  */
613
614 /*
615  * The following functions are defined for ppc (deviceid : 0x60)
616  * controllers
617  */
618
619 /**
620  * megasas_enable_intr_ppc -    Enables interrupts
621  * @instance:   Adapter soft state
622  */
623 static inline void
624 megasas_enable_intr_ppc(struct megasas_instance *instance)
625 {
626         struct megasas_register_set __iomem *regs;
627
628         regs = instance->reg_set;
629         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
630
631         writel(~0x80000000, &(regs)->outbound_intr_mask);
632
633         /* Dummy readl to force pci flush */
634         readl(&regs->outbound_intr_mask);
635 }
636
637 /**
638  * megasas_disable_intr_ppc -   Disable interrupt
639  * @instance:   Adapter soft state
640  */
641 static inline void
642 megasas_disable_intr_ppc(struct megasas_instance *instance)
643 {
644         struct megasas_register_set __iomem *regs;
645         u32 mask = 0xFFFFFFFF;
646
647         regs = instance->reg_set;
648         writel(mask, &regs->outbound_intr_mask);
649         /* Dummy readl to force pci flush */
650         readl(&regs->outbound_intr_mask);
651 }
652
653 /**
654  * megasas_read_fw_status_reg_ppc - returns the current FW status value
655  * @instance:   Adapter soft state
656  */
657 static u32
658 megasas_read_fw_status_reg_ppc(struct megasas_instance *instance)
659 {
660         return readl(&instance->reg_set->outbound_scratch_pad_0);
661 }
662
663 /**
664  * megasas_clear_interrupt_ppc -        Check & clear interrupt
665  * @instance:   Adapter soft state
666  */
667 static int
668 megasas_clear_intr_ppc(struct megasas_instance *instance)
669 {
670         u32 status, mfiStatus = 0;
671         struct megasas_register_set __iomem *regs;
672         regs = instance->reg_set;
673
674         /*
675          * Check if it is our interrupt
676          */
677         status = readl(&regs->outbound_intr_status);
678
679         if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT)
680                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
681
682         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT)
683                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
684
685         /*
686          * Clear the interrupt by writing back the same value
687          */
688         writel(status, &regs->outbound_doorbell_clear);
689
690         /* Dummy readl to force pci flush */
691         readl(&regs->outbound_doorbell_clear);
692
693         return mfiStatus;
694 }
695
696 /**
697  * megasas_fire_cmd_ppc -       Sends command to the FW
698  * @instance:           Adapter soft state
699  * @frame_phys_addr:    Physical address of cmd
700  * @frame_count:        Number of frames for the command
701  * @regs:               MFI register set
702  */
703 static inline void
704 megasas_fire_cmd_ppc(struct megasas_instance *instance,
705                 dma_addr_t frame_phys_addr,
706                 u32 frame_count,
707                 struct megasas_register_set __iomem *regs)
708 {
709         unsigned long flags;
710
711         spin_lock_irqsave(&instance->hba_lock, flags);
712         writel((frame_phys_addr | (frame_count<<1))|1,
713                         &(regs)->inbound_queue_port);
714         spin_unlock_irqrestore(&instance->hba_lock, flags);
715 }
716
717 /**
718  * megasas_check_reset_ppc -    For controller reset check
719  * @instance:   Adapter soft state
720  * @regs:       MFI register set
721  */
722 static int
723 megasas_check_reset_ppc(struct megasas_instance *instance,
724                         struct megasas_register_set __iomem *regs)
725 {
726         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
727                 return 1;
728
729         return 0;
730 }
731
732 static struct megasas_instance_template megasas_instance_template_ppc = {
733
734         .fire_cmd = megasas_fire_cmd_ppc,
735         .enable_intr = megasas_enable_intr_ppc,
736         .disable_intr = megasas_disable_intr_ppc,
737         .clear_intr = megasas_clear_intr_ppc,
738         .read_fw_status_reg = megasas_read_fw_status_reg_ppc,
739         .adp_reset = megasas_adp_reset_xscale,
740         .check_reset = megasas_check_reset_ppc,
741         .service_isr = megasas_isr,
742         .tasklet = megasas_complete_cmd_dpc,
743         .init_adapter = megasas_init_adapter_mfi,
744         .build_and_issue_cmd = megasas_build_and_issue_cmd,
745         .issue_dcmd = megasas_issue_dcmd,
746 };
747
748 /**
749  * megasas_enable_intr_skinny - Enables interrupts
750  * @instance:   Adapter soft state
751  */
752 static inline void
753 megasas_enable_intr_skinny(struct megasas_instance *instance)
754 {
755         struct megasas_register_set __iomem *regs;
756
757         regs = instance->reg_set;
758         writel(0xFFFFFFFF, &(regs)->outbound_intr_mask);
759
760         writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
761
762         /* Dummy readl to force pci flush */
763         readl(&regs->outbound_intr_mask);
764 }
765
766 /**
767  * megasas_disable_intr_skinny -        Disables interrupt
768  * @instance:   Adapter soft state
769  */
770 static inline void
771 megasas_disable_intr_skinny(struct megasas_instance *instance)
772 {
773         struct megasas_register_set __iomem *regs;
774         u32 mask = 0xFFFFFFFF;
775
776         regs = instance->reg_set;
777         writel(mask, &regs->outbound_intr_mask);
778         /* Dummy readl to force pci flush */
779         readl(&regs->outbound_intr_mask);
780 }
781
782 /**
783  * megasas_read_fw_status_reg_skinny - returns the current FW status value
784  * @instance:   Adapter soft state
785  */
786 static u32
787 megasas_read_fw_status_reg_skinny(struct megasas_instance *instance)
788 {
789         return readl(&instance->reg_set->outbound_scratch_pad_0);
790 }
791
792 /**
793  * megasas_clear_interrupt_skinny -     Check & clear interrupt
794  * @instance:   Adapter soft state
795  */
796 static int
797 megasas_clear_intr_skinny(struct megasas_instance *instance)
798 {
799         u32 status;
800         u32 mfiStatus = 0;
801         struct megasas_register_set __iomem *regs;
802         regs = instance->reg_set;
803
804         /*
805          * Check if it is our interrupt
806          */
807         status = readl(&regs->outbound_intr_status);
808
809         if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) {
810                 return 0;
811         }
812
813         /*
814          * Check if it is our interrupt
815          */
816         if ((megasas_read_fw_status_reg_skinny(instance) & MFI_STATE_MASK) ==
817             MFI_STATE_FAULT) {
818                 mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
819         } else
820                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
821
822         /*
823          * Clear the interrupt by writing back the same value
824          */
825         writel(status, &regs->outbound_intr_status);
826
827         /*
828          * dummy read to flush PCI
829          */
830         readl(&regs->outbound_intr_status);
831
832         return mfiStatus;
833 }
834
835 /**
836  * megasas_fire_cmd_skinny -    Sends command to the FW
837  * @instance:           Adapter soft state
838  * @frame_phys_addr:    Physical address of cmd
839  * @frame_count:        Number of frames for the command
840  * @regs:               MFI register set
841  */
842 static inline void
843 megasas_fire_cmd_skinny(struct megasas_instance *instance,
844                         dma_addr_t frame_phys_addr,
845                         u32 frame_count,
846                         struct megasas_register_set __iomem *regs)
847 {
848         unsigned long flags;
849
850         spin_lock_irqsave(&instance->hba_lock, flags);
851         writel(upper_32_bits(frame_phys_addr),
852                &(regs)->inbound_high_queue_port);
853         writel((lower_32_bits(frame_phys_addr) | (frame_count<<1))|1,
854                &(regs)->inbound_low_queue_port);
855         spin_unlock_irqrestore(&instance->hba_lock, flags);
856 }
857
858 /**
859  * megasas_check_reset_skinny - For controller reset check
860  * @instance:   Adapter soft state
861  * @regs:       MFI register set
862  */
863 static int
864 megasas_check_reset_skinny(struct megasas_instance *instance,
865                                 struct megasas_register_set __iomem *regs)
866 {
867         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
868                 return 1;
869
870         return 0;
871 }
872
873 static struct megasas_instance_template megasas_instance_template_skinny = {
874
875         .fire_cmd = megasas_fire_cmd_skinny,
876         .enable_intr = megasas_enable_intr_skinny,
877         .disable_intr = megasas_disable_intr_skinny,
878         .clear_intr = megasas_clear_intr_skinny,
879         .read_fw_status_reg = megasas_read_fw_status_reg_skinny,
880         .adp_reset = megasas_adp_reset_gen2,
881         .check_reset = megasas_check_reset_skinny,
882         .service_isr = megasas_isr,
883         .tasklet = megasas_complete_cmd_dpc,
884         .init_adapter = megasas_init_adapter_mfi,
885         .build_and_issue_cmd = megasas_build_and_issue_cmd,
886         .issue_dcmd = megasas_issue_dcmd,
887 };
888
889
890 /*
891  * The following functions are defined for gen2 (deviceid : 0x78 0x79)
892  * controllers
893  */
894
895 /**
896  * megasas_enable_intr_gen2 -  Enables interrupts
897  * @instance:   Adapter soft state
898  */
899 static inline void
900 megasas_enable_intr_gen2(struct megasas_instance *instance)
901 {
902         struct megasas_register_set __iomem *regs;
903
904         regs = instance->reg_set;
905         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
906
907         /* write ~0x00000005 (4 & 1) to the intr mask*/
908         writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
909
910         /* Dummy readl to force pci flush */
911         readl(&regs->outbound_intr_mask);
912 }
913
914 /**
915  * megasas_disable_intr_gen2 - Disables interrupt
916  * @instance:   Adapter soft state
917  */
918 static inline void
919 megasas_disable_intr_gen2(struct megasas_instance *instance)
920 {
921         struct megasas_register_set __iomem *regs;
922         u32 mask = 0xFFFFFFFF;
923
924         regs = instance->reg_set;
925         writel(mask, &regs->outbound_intr_mask);
926         /* Dummy readl to force pci flush */
927         readl(&regs->outbound_intr_mask);
928 }
929
930 /**
931  * megasas_read_fw_status_reg_gen2 - returns the current FW status value
932  * @instance:   Adapter soft state
933  */
934 static u32
935 megasas_read_fw_status_reg_gen2(struct megasas_instance *instance)
936 {
937         return readl(&instance->reg_set->outbound_scratch_pad_0);
938 }
939
940 /**
941  * megasas_clear_interrupt_gen2 -      Check & clear interrupt
942  * @instance:   Adapter soft state
943  */
944 static int
945 megasas_clear_intr_gen2(struct megasas_instance *instance)
946 {
947         u32 status;
948         u32 mfiStatus = 0;
949         struct megasas_register_set __iomem *regs;
950         regs = instance->reg_set;
951
952         /*
953          * Check if it is our interrupt
954          */
955         status = readl(&regs->outbound_intr_status);
956
957         if (status & MFI_INTR_FLAG_REPLY_MESSAGE) {
958                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
959         }
960         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) {
961                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
962         }
963
964         /*
965          * Clear the interrupt by writing back the same value
966          */
967         if (mfiStatus)
968                 writel(status, &regs->outbound_doorbell_clear);
969
970         /* Dummy readl to force pci flush */
971         readl(&regs->outbound_intr_status);
972
973         return mfiStatus;
974 }
975
976 /**
977  * megasas_fire_cmd_gen2 -     Sends command to the FW
978  * @instance:           Adapter soft state
979  * @frame_phys_addr:    Physical address of cmd
980  * @frame_count:        Number of frames for the command
981  * @regs:               MFI register set
982  */
983 static inline void
984 megasas_fire_cmd_gen2(struct megasas_instance *instance,
985                         dma_addr_t frame_phys_addr,
986                         u32 frame_count,
987                         struct megasas_register_set __iomem *regs)
988 {
989         unsigned long flags;
990
991         spin_lock_irqsave(&instance->hba_lock, flags);
992         writel((frame_phys_addr | (frame_count<<1))|1,
993                         &(regs)->inbound_queue_port);
994         spin_unlock_irqrestore(&instance->hba_lock, flags);
995 }
996
997 /**
998  * megasas_adp_reset_gen2 -     For controller reset
999  * @instance:   Adapter soft state
1000  * @reg_set:    MFI register set
1001  */
1002 static int
1003 megasas_adp_reset_gen2(struct megasas_instance *instance,
1004                         struct megasas_register_set __iomem *reg_set)
1005 {
1006         u32 retry = 0 ;
1007         u32 HostDiag;
1008         u32 __iomem *seq_offset = &reg_set->seq_offset;
1009         u32 __iomem *hostdiag_offset = &reg_set->host_diag;
1010
1011         if (instance->instancet == &megasas_instance_template_skinny) {
1012                 seq_offset = &reg_set->fusion_seq_offset;
1013                 hostdiag_offset = &reg_set->fusion_host_diag;
1014         }
1015
1016         writel(0, seq_offset);
1017         writel(4, seq_offset);
1018         writel(0xb, seq_offset);
1019         writel(2, seq_offset);
1020         writel(7, seq_offset);
1021         writel(0xd, seq_offset);
1022
1023         msleep(1000);
1024
1025         HostDiag = (u32)readl(hostdiag_offset);
1026
1027         while (!(HostDiag & DIAG_WRITE_ENABLE)) {
1028                 msleep(100);
1029                 HostDiag = (u32)readl(hostdiag_offset);
1030                 dev_notice(&instance->pdev->dev, "RESETGEN2: retry=%x, hostdiag=%x\n",
1031                                         retry, HostDiag);
1032
1033                 if (retry++ >= 100)
1034                         return 1;
1035
1036         }
1037
1038         dev_notice(&instance->pdev->dev, "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag);
1039
1040         writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset);
1041
1042         ssleep(10);
1043
1044         HostDiag = (u32)readl(hostdiag_offset);
1045         while (HostDiag & DIAG_RESET_ADAPTER) {
1046                 msleep(100);
1047                 HostDiag = (u32)readl(hostdiag_offset);
1048                 dev_notice(&instance->pdev->dev, "RESET_GEN2: retry=%x, hostdiag=%x\n",
1049                                 retry, HostDiag);
1050
1051                 if (retry++ >= 1000)
1052                         return 1;
1053
1054         }
1055         return 0;
1056 }
1057
1058 /**
1059  * megasas_check_reset_gen2 -   For controller reset check
1060  * @instance:   Adapter soft state
1061  * @regs:       MFI register set
1062  */
1063 static int
1064 megasas_check_reset_gen2(struct megasas_instance *instance,
1065                 struct megasas_register_set __iomem *regs)
1066 {
1067         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
1068                 return 1;
1069
1070         return 0;
1071 }
1072
1073 static struct megasas_instance_template megasas_instance_template_gen2 = {
1074
1075         .fire_cmd = megasas_fire_cmd_gen2,
1076         .enable_intr = megasas_enable_intr_gen2,
1077         .disable_intr = megasas_disable_intr_gen2,
1078         .clear_intr = megasas_clear_intr_gen2,
1079         .read_fw_status_reg = megasas_read_fw_status_reg_gen2,
1080         .adp_reset = megasas_adp_reset_gen2,
1081         .check_reset = megasas_check_reset_gen2,
1082         .service_isr = megasas_isr,
1083         .tasklet = megasas_complete_cmd_dpc,
1084         .init_adapter = megasas_init_adapter_mfi,
1085         .build_and_issue_cmd = megasas_build_and_issue_cmd,
1086         .issue_dcmd = megasas_issue_dcmd,
1087 };
1088
1089 /*
1090  * This is the end of set of functions & definitions
1091  * specific to gen2 (deviceid : 0x78, 0x79) controllers
1092  */
1093
1094 /*
1095  * Template added for TB (Fusion)
1096  */
1097 extern struct megasas_instance_template megasas_instance_template_fusion;
1098
1099 /**
1100  * megasas_issue_polled -       Issues a polling command
1101  * @instance:                   Adapter soft state
1102  * @cmd:                        Command packet to be issued
1103  *
1104  * For polling, MFI requires the cmd_status to be set to MFI_STAT_INVALID_STATUS before posting.
1105  */
1106 int
1107 megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
1108 {
1109         struct megasas_header *frame_hdr = &cmd->frame->hdr;
1110
1111         frame_hdr->cmd_status = MFI_STAT_INVALID_STATUS;
1112         frame_hdr->flags |= cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE);
1113
1114         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1115                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1116                         __func__, __LINE__);
1117                 return DCMD_INIT;
1118         }
1119
1120         instance->instancet->issue_dcmd(instance, cmd);
1121
1122         return wait_and_poll(instance, cmd, instance->requestorId ?
1123                         MEGASAS_ROUTINE_WAIT_TIME_VF : MFI_IO_TIMEOUT_SECS);
1124 }
1125
1126 /**
1127  * megasas_issue_blocked_cmd -  Synchronous wrapper around regular FW cmds
1128  * @instance:                   Adapter soft state
1129  * @cmd:                        Command to be issued
1130  * @timeout:                    Timeout in seconds
1131  *
1132  * This function waits on an event for the command to be returned from ISR.
1133  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
1134  * Used to issue ioctl commands.
1135  */
1136 int
1137 megasas_issue_blocked_cmd(struct megasas_instance *instance,
1138                           struct megasas_cmd *cmd, int timeout)
1139 {
1140         int ret = 0;
1141         cmd->cmd_status_drv = DCMD_INIT;
1142
1143         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1144                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1145                         __func__, __LINE__);
1146                 return DCMD_INIT;
1147         }
1148
1149         instance->instancet->issue_dcmd(instance, cmd);
1150
1151         if (timeout) {
1152                 ret = wait_event_timeout(instance->int_cmd_wait_q,
1153                 cmd->cmd_status_drv != DCMD_INIT, timeout * HZ);
1154                 if (!ret) {
1155                         dev_err(&instance->pdev->dev,
1156                                 "DCMD(opcode: 0x%x) is timed out, func:%s\n",
1157                                 cmd->frame->dcmd.opcode, __func__);
1158                         return DCMD_TIMEOUT;
1159                 }
1160         } else
1161                 wait_event(instance->int_cmd_wait_q,
1162                                 cmd->cmd_status_drv != DCMD_INIT);
1163
1164         return cmd->cmd_status_drv;
1165 }
1166
1167 /**
1168  * megasas_issue_blocked_abort_cmd -    Aborts previously issued cmd
1169  * @instance:                           Adapter soft state
1170  * @cmd_to_abort:                       Previously issued cmd to be aborted
1171  * @timeout:                            Timeout in seconds
1172  *
1173  * MFI firmware can abort previously issued AEN comamnd (automatic event
1174  * notification). The megasas_issue_blocked_abort_cmd() issues such abort
1175  * cmd and waits for return status.
1176  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
1177  */
1178 static int
1179 megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
1180                                 struct megasas_cmd *cmd_to_abort, int timeout)
1181 {
1182         struct megasas_cmd *cmd;
1183         struct megasas_abort_frame *abort_fr;
1184         int ret = 0;
1185         u32 opcode;
1186
1187         cmd = megasas_get_cmd(instance);
1188
1189         if (!cmd)
1190                 return -1;
1191
1192         abort_fr = &cmd->frame->abort;
1193
1194         /*
1195          * Prepare and issue the abort frame
1196          */
1197         abort_fr->cmd = MFI_CMD_ABORT;
1198         abort_fr->cmd_status = MFI_STAT_INVALID_STATUS;
1199         abort_fr->flags = cpu_to_le16(0);
1200         abort_fr->abort_context = cpu_to_le32(cmd_to_abort->index);
1201         abort_fr->abort_mfi_phys_addr_lo =
1202                 cpu_to_le32(lower_32_bits(cmd_to_abort->frame_phys_addr));
1203         abort_fr->abort_mfi_phys_addr_hi =
1204                 cpu_to_le32(upper_32_bits(cmd_to_abort->frame_phys_addr));
1205
1206         cmd->sync_cmd = 1;
1207         cmd->cmd_status_drv = DCMD_INIT;
1208
1209         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1210                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1211                         __func__, __LINE__);
1212                 return DCMD_INIT;
1213         }
1214
1215         instance->instancet->issue_dcmd(instance, cmd);
1216
1217         if (timeout) {
1218                 ret = wait_event_timeout(instance->abort_cmd_wait_q,
1219                 cmd->cmd_status_drv != DCMD_INIT, timeout * HZ);
1220                 if (!ret) {
1221                         opcode = cmd_to_abort->frame->dcmd.opcode;
1222                         dev_err(&instance->pdev->dev,
1223                                 "Abort(to be aborted DCMD opcode: 0x%x) is timed out func:%s\n",
1224                                 opcode,  __func__);
1225                         return DCMD_TIMEOUT;
1226                 }
1227         } else
1228                 wait_event(instance->abort_cmd_wait_q,
1229                 cmd->cmd_status_drv != DCMD_INIT);
1230
1231         cmd->sync_cmd = 0;
1232
1233         megasas_return_cmd(instance, cmd);
1234         return cmd->cmd_status_drv;
1235 }
1236
1237 /**
1238  * megasas_make_sgl32 - Prepares 32-bit SGL
1239  * @instance:           Adapter soft state
1240  * @scp:                SCSI command from the mid-layer
1241  * @mfi_sgl:            SGL to be filled in
1242  *
1243  * If successful, this function returns the number of SG elements. Otherwise,
1244  * it returnes -1.
1245  */
1246 static int
1247 megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
1248                    union megasas_sgl *mfi_sgl)
1249 {
1250         int i;
1251         int sge_count;
1252         struct scatterlist *os_sgl;
1253
1254         sge_count = scsi_dma_map(scp);
1255         BUG_ON(sge_count < 0);
1256
1257         if (sge_count) {
1258                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1259                         mfi_sgl->sge32[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1260                         mfi_sgl->sge32[i].phys_addr = cpu_to_le32(sg_dma_address(os_sgl));
1261                 }
1262         }
1263         return sge_count;
1264 }
1265
1266 /**
1267  * megasas_make_sgl64 - Prepares 64-bit SGL
1268  * @instance:           Adapter soft state
1269  * @scp:                SCSI command from the mid-layer
1270  * @mfi_sgl:            SGL to be filled in
1271  *
1272  * If successful, this function returns the number of SG elements. Otherwise,
1273  * it returnes -1.
1274  */
1275 static int
1276 megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
1277                    union megasas_sgl *mfi_sgl)
1278 {
1279         int i;
1280         int sge_count;
1281         struct scatterlist *os_sgl;
1282
1283         sge_count = scsi_dma_map(scp);
1284         BUG_ON(sge_count < 0);
1285
1286         if (sge_count) {
1287                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1288                         mfi_sgl->sge64[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1289                         mfi_sgl->sge64[i].phys_addr = cpu_to_le64(sg_dma_address(os_sgl));
1290                 }
1291         }
1292         return sge_count;
1293 }
1294
1295 /**
1296  * megasas_make_sgl_skinny - Prepares IEEE SGL
1297  * @instance:           Adapter soft state
1298  * @scp:                SCSI command from the mid-layer
1299  * @mfi_sgl:            SGL to be filled in
1300  *
1301  * If successful, this function returns the number of SG elements. Otherwise,
1302  * it returnes -1.
1303  */
1304 static int
1305 megasas_make_sgl_skinny(struct megasas_instance *instance,
1306                 struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl)
1307 {
1308         int i;
1309         int sge_count;
1310         struct scatterlist *os_sgl;
1311
1312         sge_count = scsi_dma_map(scp);
1313
1314         if (sge_count) {
1315                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1316                         mfi_sgl->sge_skinny[i].length =
1317                                 cpu_to_le32(sg_dma_len(os_sgl));
1318                         mfi_sgl->sge_skinny[i].phys_addr =
1319                                 cpu_to_le64(sg_dma_address(os_sgl));
1320                         mfi_sgl->sge_skinny[i].flag = cpu_to_le32(0);
1321                 }
1322         }
1323         return sge_count;
1324 }
1325
1326  /**
1327  * megasas_get_frame_count - Computes the number of frames
1328  * @frame_type          : type of frame- io or pthru frame
1329  * @sge_count           : number of sg elements
1330  *
1331  * Returns the number of frames required for numnber of sge's (sge_count)
1332  */
1333
1334 static u32 megasas_get_frame_count(struct megasas_instance *instance,
1335                         u8 sge_count, u8 frame_type)
1336 {
1337         int num_cnt;
1338         int sge_bytes;
1339         u32 sge_sz;
1340         u32 frame_count = 0;
1341
1342         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1343             sizeof(struct megasas_sge32);
1344
1345         if (instance->flag_ieee) {
1346                 sge_sz = sizeof(struct megasas_sge_skinny);
1347         }
1348
1349         /*
1350          * Main frame can contain 2 SGEs for 64-bit SGLs and
1351          * 3 SGEs for 32-bit SGLs for ldio &
1352          * 1 SGEs for 64-bit SGLs and
1353          * 2 SGEs for 32-bit SGLs for pthru frame
1354          */
1355         if (unlikely(frame_type == PTHRU_FRAME)) {
1356                 if (instance->flag_ieee == 1) {
1357                         num_cnt = sge_count - 1;
1358                 } else if (IS_DMA64)
1359                         num_cnt = sge_count - 1;
1360                 else
1361                         num_cnt = sge_count - 2;
1362         } else {
1363                 if (instance->flag_ieee == 1) {
1364                         num_cnt = sge_count - 1;
1365                 } else if (IS_DMA64)
1366                         num_cnt = sge_count - 2;
1367                 else
1368                         num_cnt = sge_count - 3;
1369         }
1370
1371         if (num_cnt > 0) {
1372                 sge_bytes = sge_sz * num_cnt;
1373
1374                 frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
1375                     ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
1376         }
1377         /* Main frame */
1378         frame_count += 1;
1379
1380         if (frame_count > 7)
1381                 frame_count = 8;
1382         return frame_count;
1383 }
1384
1385 /**
1386  * megasas_build_dcdb - Prepares a direct cdb (DCDB) command
1387  * @instance:           Adapter soft state
1388  * @scp:                SCSI command
1389  * @cmd:                Command to be prepared in
1390  *
1391  * This function prepares CDB commands. These are typcially pass-through
1392  * commands to the devices.
1393  */
1394 static int
1395 megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
1396                    struct megasas_cmd *cmd)
1397 {
1398         u32 is_logical;
1399         u32 device_id;
1400         u16 flags = 0;
1401         struct megasas_pthru_frame *pthru;
1402
1403         is_logical = MEGASAS_IS_LOGICAL(scp->device);
1404         device_id = MEGASAS_DEV_INDEX(scp);
1405         pthru = (struct megasas_pthru_frame *)cmd->frame;
1406
1407         if (scp->sc_data_direction == DMA_TO_DEVICE)
1408                 flags = MFI_FRAME_DIR_WRITE;
1409         else if (scp->sc_data_direction == DMA_FROM_DEVICE)
1410                 flags = MFI_FRAME_DIR_READ;
1411         else if (scp->sc_data_direction == DMA_NONE)
1412                 flags = MFI_FRAME_DIR_NONE;
1413
1414         if (instance->flag_ieee == 1) {
1415                 flags |= MFI_FRAME_IEEE;
1416         }
1417
1418         /*
1419          * Prepare the DCDB frame
1420          */
1421         pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
1422         pthru->cmd_status = 0x0;
1423         pthru->scsi_status = 0x0;
1424         pthru->target_id = device_id;
1425         pthru->lun = scp->device->lun;
1426         pthru->cdb_len = scp->cmd_len;
1427         pthru->timeout = 0;
1428         pthru->pad_0 = 0;
1429         pthru->flags = cpu_to_le16(flags);
1430         pthru->data_xfer_len = cpu_to_le32(scsi_bufflen(scp));
1431
1432         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
1433
1434         /*
1435          * If the command is for the tape device, set the
1436          * pthru timeout to the os layer timeout value.
1437          */
1438         if (scp->device->type == TYPE_TAPE) {
1439                 if ((scp->request->timeout / HZ) > 0xFFFF)
1440                         pthru->timeout = cpu_to_le16(0xFFFF);
1441                 else
1442                         pthru->timeout = cpu_to_le16(scp->request->timeout / HZ);
1443         }
1444
1445         /*
1446          * Construct SGL
1447          */
1448         if (instance->flag_ieee == 1) {
1449                 pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1450                 pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
1451                                                       &pthru->sgl);
1452         } else if (IS_DMA64) {
1453                 pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1454                 pthru->sge_count = megasas_make_sgl64(instance, scp,
1455                                                       &pthru->sgl);
1456         } else
1457                 pthru->sge_count = megasas_make_sgl32(instance, scp,
1458                                                       &pthru->sgl);
1459
1460         if (pthru->sge_count > instance->max_num_sge) {
1461                 dev_err(&instance->pdev->dev, "DCDB too many SGE NUM=%x\n",
1462                         pthru->sge_count);
1463                 return 0;
1464         }
1465
1466         /*
1467          * Sense info specific
1468          */
1469         pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
1470         pthru->sense_buf_phys_addr_hi =
1471                 cpu_to_le32(upper_32_bits(cmd->sense_phys_addr));
1472         pthru->sense_buf_phys_addr_lo =
1473                 cpu_to_le32(lower_32_bits(cmd->sense_phys_addr));
1474
1475         /*
1476          * Compute the total number of frames this command consumes. FW uses
1477          * this number to pull sufficient number of frames from host memory.
1478          */
1479         cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
1480                                                         PTHRU_FRAME);
1481
1482         return cmd->frame_count;
1483 }
1484
1485 /**
1486  * megasas_build_ldio - Prepares IOs to logical devices
1487  * @instance:           Adapter soft state
1488  * @scp:                SCSI command
1489  * @cmd:                Command to be prepared
1490  *
1491  * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
1492  */
1493 static int
1494 megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
1495                    struct megasas_cmd *cmd)
1496 {
1497         u32 device_id;
1498         u8 sc = scp->cmnd[0];
1499         u16 flags = 0;
1500         struct megasas_io_frame *ldio;
1501
1502         device_id = MEGASAS_DEV_INDEX(scp);
1503         ldio = (struct megasas_io_frame *)cmd->frame;
1504
1505         if (scp->sc_data_direction == DMA_TO_DEVICE)
1506                 flags = MFI_FRAME_DIR_WRITE;
1507         else if (scp->sc_data_direction == DMA_FROM_DEVICE)
1508                 flags = MFI_FRAME_DIR_READ;
1509
1510         if (instance->flag_ieee == 1) {
1511                 flags |= MFI_FRAME_IEEE;
1512         }
1513
1514         /*
1515          * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
1516          */
1517         ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
1518         ldio->cmd_status = 0x0;
1519         ldio->scsi_status = 0x0;
1520         ldio->target_id = device_id;
1521         ldio->timeout = 0;
1522         ldio->reserved_0 = 0;
1523         ldio->pad_0 = 0;
1524         ldio->flags = cpu_to_le16(flags);
1525         ldio->start_lba_hi = 0;
1526         ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
1527
1528         /*
1529          * 6-byte READ(0x08) or WRITE(0x0A) cdb
1530          */
1531         if (scp->cmd_len == 6) {
1532                 ldio->lba_count = cpu_to_le32((u32) scp->cmnd[4]);
1533                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[1] << 16) |
1534                                                  ((u32) scp->cmnd[2] << 8) |
1535                                                  (u32) scp->cmnd[3]);
1536
1537                 ldio->start_lba_lo &= cpu_to_le32(0x1FFFFF);
1538         }
1539
1540         /*
1541          * 10-byte READ(0x28) or WRITE(0x2A) cdb
1542          */
1543         else if (scp->cmd_len == 10) {
1544                 ldio->lba_count = cpu_to_le32((u32) scp->cmnd[8] |
1545                                               ((u32) scp->cmnd[7] << 8));
1546                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1547                                                  ((u32) scp->cmnd[3] << 16) |
1548                                                  ((u32) scp->cmnd[4] << 8) |
1549                                                  (u32) scp->cmnd[5]);
1550         }
1551
1552         /*
1553          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1554          */
1555         else if (scp->cmd_len == 12) {
1556                 ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1557                                               ((u32) scp->cmnd[7] << 16) |
1558                                               ((u32) scp->cmnd[8] << 8) |
1559                                               (u32) scp->cmnd[9]);
1560
1561                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1562                                                  ((u32) scp->cmnd[3] << 16) |
1563                                                  ((u32) scp->cmnd[4] << 8) |
1564                                                  (u32) scp->cmnd[5]);
1565         }
1566
1567         /*
1568          * 16-byte READ(0x88) or WRITE(0x8A) cdb
1569          */
1570         else if (scp->cmd_len == 16) {
1571                 ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[10] << 24) |
1572                                               ((u32) scp->cmnd[11] << 16) |
1573                                               ((u32) scp->cmnd[12] << 8) |
1574                                               (u32) scp->cmnd[13]);
1575
1576                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1577                                                  ((u32) scp->cmnd[7] << 16) |
1578                                                  ((u32) scp->cmnd[8] << 8) |
1579                                                  (u32) scp->cmnd[9]);
1580
1581                 ldio->start_lba_hi = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1582                                                  ((u32) scp->cmnd[3] << 16) |
1583                                                  ((u32) scp->cmnd[4] << 8) |
1584                                                  (u32) scp->cmnd[5]);
1585
1586         }
1587
1588         /*
1589          * Construct SGL
1590          */
1591         if (instance->flag_ieee) {
1592                 ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1593                 ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
1594                                               &ldio->sgl);
1595         } else if (IS_DMA64) {
1596                 ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1597                 ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
1598         } else
1599                 ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
1600
1601         if (ldio->sge_count > instance->max_num_sge) {
1602                 dev_err(&instance->pdev->dev, "build_ld_io: sge_count = %x\n",
1603                         ldio->sge_count);
1604                 return 0;
1605         }
1606
1607         /*
1608          * Sense info specific
1609          */
1610         ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
1611         ldio->sense_buf_phys_addr_hi = 0;
1612         ldio->sense_buf_phys_addr_lo = cpu_to_le32(cmd->sense_phys_addr);
1613
1614         /*
1615          * Compute the total number of frames this command consumes. FW uses
1616          * this number to pull sufficient number of frames from host memory.
1617          */
1618         cmd->frame_count = megasas_get_frame_count(instance,
1619                         ldio->sge_count, IO_FRAME);
1620
1621         return cmd->frame_count;
1622 }
1623
1624 /**
1625  * megasas_cmd_type -           Checks if the cmd is for logical drive/sysPD
1626  *                              and whether it's RW or non RW
1627  * @cmd:                        SCSI command
1628  *
1629  */
1630 inline int megasas_cmd_type(struct scsi_cmnd *cmd)
1631 {
1632         int ret;
1633
1634         switch (cmd->cmnd[0]) {
1635         case READ_10:
1636         case WRITE_10:
1637         case READ_12:
1638         case WRITE_12:
1639         case READ_6:
1640         case WRITE_6:
1641         case READ_16:
1642         case WRITE_16:
1643                 ret = (MEGASAS_IS_LOGICAL(cmd->device)) ?
1644                         READ_WRITE_LDIO : READ_WRITE_SYSPDIO;
1645                 break;
1646         default:
1647                 ret = (MEGASAS_IS_LOGICAL(cmd->device)) ?
1648                         NON_READ_WRITE_LDIO : NON_READ_WRITE_SYSPDIO;
1649         }
1650         return ret;
1651 }
1652
1653  /**
1654  * megasas_dump_pending_frames -        Dumps the frame address of all pending cmds
1655  *                                      in FW
1656  * @instance:                           Adapter soft state
1657  */
1658 static inline void
1659 megasas_dump_pending_frames(struct megasas_instance *instance)
1660 {
1661         struct megasas_cmd *cmd;
1662         int i,n;
1663         union megasas_sgl *mfi_sgl;
1664         struct megasas_io_frame *ldio;
1665         struct megasas_pthru_frame *pthru;
1666         u32 sgcount;
1667         u16 max_cmd = instance->max_fw_cmds;
1668
1669         dev_err(&instance->pdev->dev, "[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
1670         dev_err(&instance->pdev->dev, "[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
1671         if (IS_DMA64)
1672                 dev_err(&instance->pdev->dev, "[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
1673         else
1674                 dev_err(&instance->pdev->dev, "[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
1675
1676         dev_err(&instance->pdev->dev, "[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
1677         for (i = 0; i < max_cmd; i++) {
1678                 cmd = instance->cmd_list[i];
1679                 if (!cmd->scmd)
1680                         continue;
1681                 dev_err(&instance->pdev->dev, "[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
1682                 if (megasas_cmd_type(cmd->scmd) == READ_WRITE_LDIO) {
1683                         ldio = (struct megasas_io_frame *)cmd->frame;
1684                         mfi_sgl = &ldio->sgl;
1685                         sgcount = ldio->sge_count;
1686                         dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x,"
1687                         " lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1688                         instance->host->host_no, cmd->frame_count, ldio->cmd, ldio->target_id,
1689                         le32_to_cpu(ldio->start_lba_lo), le32_to_cpu(ldio->start_lba_hi),
1690                         le32_to_cpu(ldio->sense_buf_phys_addr_lo), sgcount);
1691                 } else {
1692                         pthru = (struct megasas_pthru_frame *) cmd->frame;
1693                         mfi_sgl = &pthru->sgl;
1694                         sgcount = pthru->sge_count;
1695                         dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, "
1696                         "lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1697                         instance->host->host_no, cmd->frame_count, pthru->cmd, pthru->target_id,
1698                         pthru->lun, pthru->cdb_len, le32_to_cpu(pthru->data_xfer_len),
1699                         le32_to_cpu(pthru->sense_buf_phys_addr_lo), sgcount);
1700                 }
1701                 if (megasas_dbg_lvl & MEGASAS_DBG_LVL) {
1702                         for (n = 0; n < sgcount; n++) {
1703                                 if (IS_DMA64)
1704                                         dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%llx\n",
1705                                                 le32_to_cpu(mfi_sgl->sge64[n].length),
1706                                                 le64_to_cpu(mfi_sgl->sge64[n].phys_addr));
1707                                 else
1708                                         dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%x\n",
1709                                                 le32_to_cpu(mfi_sgl->sge32[n].length),
1710                                                 le32_to_cpu(mfi_sgl->sge32[n].phys_addr));
1711                         }
1712                 }
1713         } /*for max_cmd*/
1714         dev_err(&instance->pdev->dev, "[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
1715         for (i = 0; i < max_cmd; i++) {
1716
1717                 cmd = instance->cmd_list[i];
1718
1719                 if (cmd->sync_cmd == 1)
1720                         dev_err(&instance->pdev->dev, "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
1721         }
1722         dev_err(&instance->pdev->dev, "[%d]: Dumping Done\n\n",instance->host->host_no);
1723 }
1724
1725 u32
1726 megasas_build_and_issue_cmd(struct megasas_instance *instance,
1727                             struct scsi_cmnd *scmd)
1728 {
1729         struct megasas_cmd *cmd;
1730         u32 frame_count;
1731
1732         cmd = megasas_get_cmd(instance);
1733         if (!cmd)
1734                 return SCSI_MLQUEUE_HOST_BUSY;
1735
1736         /*
1737          * Logical drive command
1738          */
1739         if (megasas_cmd_type(scmd) == READ_WRITE_LDIO)
1740                 frame_count = megasas_build_ldio(instance, scmd, cmd);
1741         else
1742                 frame_count = megasas_build_dcdb(instance, scmd, cmd);
1743
1744         if (!frame_count)
1745                 goto out_return_cmd;
1746
1747         cmd->scmd = scmd;
1748         scmd->SCp.ptr = (char *)cmd;
1749
1750         /*
1751          * Issue the command to the FW
1752          */
1753         atomic_inc(&instance->fw_outstanding);
1754
1755         instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
1756                                 cmd->frame_count-1, instance->reg_set);
1757
1758         return 0;
1759 out_return_cmd:
1760         megasas_return_cmd(instance, cmd);
1761         return SCSI_MLQUEUE_HOST_BUSY;
1762 }
1763
1764
1765 /**
1766  * megasas_queue_command -      Queue entry point
1767  * @shost:                      adapter SCSI host
1768  * @scmd:                       SCSI command to be queued
1769  */
1770 static int
1771 megasas_queue_command(struct Scsi_Host *shost, struct scsi_cmnd *scmd)
1772 {
1773         struct megasas_instance *instance;
1774         struct MR_PRIV_DEVICE *mr_device_priv_data;
1775         u32 ld_tgt_id;
1776
1777         instance = (struct megasas_instance *)
1778             scmd->device->host->hostdata;
1779
1780         if (instance->unload == 1) {
1781                 scmd->result = DID_NO_CONNECT << 16;
1782                 scmd->scsi_done(scmd);
1783                 return 0;
1784         }
1785
1786         if (instance->issuepend_done == 0)
1787                 return SCSI_MLQUEUE_HOST_BUSY;
1788
1789
1790         /* Check for an mpio path and adjust behavior */
1791         if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) {
1792                 if (megasas_check_mpio_paths(instance, scmd) ==
1793                     (DID_REQUEUE << 16)) {
1794                         return SCSI_MLQUEUE_HOST_BUSY;
1795                 } else {
1796                         scmd->result = DID_NO_CONNECT << 16;
1797                         scmd->scsi_done(scmd);
1798                         return 0;
1799                 }
1800         }
1801
1802         mr_device_priv_data = scmd->device->hostdata;
1803         if (!mr_device_priv_data ||
1804             (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)) {
1805                 scmd->result = DID_NO_CONNECT << 16;
1806                 scmd->scsi_done(scmd);
1807                 return 0;
1808         }
1809
1810         if (MEGASAS_IS_LOGICAL(scmd->device)) {
1811                 ld_tgt_id = MEGASAS_TARGET_ID(scmd->device);
1812                 if (instance->ld_tgtid_status[ld_tgt_id] == LD_TARGET_ID_DELETED) {
1813                         scmd->result = DID_NO_CONNECT << 16;
1814                         scmd->scsi_done(scmd);
1815                         return 0;
1816                 }
1817         }
1818
1819         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
1820                 return SCSI_MLQUEUE_HOST_BUSY;
1821
1822         if (mr_device_priv_data->tm_busy)
1823                 return SCSI_MLQUEUE_DEVICE_BUSY;
1824
1825
1826         scmd->result = 0;
1827
1828         if (MEGASAS_IS_LOGICAL(scmd->device) &&
1829             (scmd->device->id >= instance->fw_supported_vd_count ||
1830                 scmd->device->lun)) {
1831                 scmd->result = DID_BAD_TARGET << 16;
1832                 goto out_done;
1833         }
1834
1835         if ((scmd->cmnd[0] == SYNCHRONIZE_CACHE) &&
1836             MEGASAS_IS_LOGICAL(scmd->device) &&
1837             (!instance->fw_sync_cache_support)) {
1838                 scmd->result = DID_OK << 16;
1839                 goto out_done;
1840         }
1841
1842         return instance->instancet->build_and_issue_cmd(instance, scmd);
1843
1844  out_done:
1845         scmd->scsi_done(scmd);
1846         return 0;
1847 }
1848
1849 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
1850 {
1851         int i;
1852
1853         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
1854
1855                 if ((megasas_mgmt_info.instance[i]) &&
1856                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
1857                         return megasas_mgmt_info.instance[i];
1858         }
1859
1860         return NULL;
1861 }
1862
1863 /*
1864 * megasas_set_dynamic_target_properties -
1865 * Device property set by driver may not be static and it is required to be
1866 * updated after OCR
1867 *
1868 * set tm_capable.
1869 * set dma alignment (only for eedp protection enable vd).
1870 *
1871 * @sdev: OS provided scsi device
1872 *
1873 * Returns void
1874 */
1875 void megasas_set_dynamic_target_properties(struct scsi_device *sdev,
1876                                            bool is_target_prop)
1877 {
1878         u16 pd_index = 0, ld;
1879         u32 device_id;
1880         struct megasas_instance *instance;
1881         struct fusion_context *fusion;
1882         struct MR_PRIV_DEVICE *mr_device_priv_data;
1883         struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
1884         struct MR_LD_RAID *raid;
1885         struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
1886
1887         instance = megasas_lookup_instance(sdev->host->host_no);
1888         fusion = instance->ctrl_context;
1889         mr_device_priv_data = sdev->hostdata;
1890
1891         if (!fusion || !mr_device_priv_data)
1892                 return;
1893
1894         if (MEGASAS_IS_LOGICAL(sdev)) {
1895                 device_id = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL)
1896                                         + sdev->id;
1897                 local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
1898                 ld = MR_TargetIdToLdGet(device_id, local_map_ptr);
1899                 if (ld >= instance->fw_supported_vd_count)
1900                         return;
1901                 raid = MR_LdRaidGet(ld, local_map_ptr);
1902
1903                 if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER)
1904                 blk_queue_update_dma_alignment(sdev->request_queue, 0x7);
1905
1906                 mr_device_priv_data->is_tm_capable =
1907                         raid->capability.tmCapable;
1908
1909                 if (!raid->flags.isEPD)
1910                         sdev->no_write_same = 1;
1911
1912         } else if (instance->use_seqnum_jbod_fp) {
1913                 pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1914                         sdev->id;
1915                 pd_sync = (void *)fusion->pd_seq_sync
1916                                 [(instance->pd_seq_map_id - 1) & 1];
1917                 mr_device_priv_data->is_tm_capable =
1918                         pd_sync->seq[pd_index].capability.tmCapable;
1919         }
1920
1921         if (is_target_prop && instance->tgt_prop->reset_tmo) {
1922                 /*
1923                  * If FW provides a target reset timeout value, driver will use
1924                  * it. If not set, fallback to default values.
1925                  */
1926                 mr_device_priv_data->target_reset_tmo =
1927                         min_t(u8, instance->max_reset_tmo,
1928                               instance->tgt_prop->reset_tmo);
1929                 mr_device_priv_data->task_abort_tmo = instance->task_abort_tmo;
1930         } else {
1931                 mr_device_priv_data->target_reset_tmo =
1932                                                 MEGASAS_DEFAULT_TM_TIMEOUT;
1933                 mr_device_priv_data->task_abort_tmo =
1934                                                 MEGASAS_DEFAULT_TM_TIMEOUT;
1935         }
1936 }
1937
1938 /*
1939  * megasas_set_nvme_device_properties -
1940  * set nomerges=2
1941  * set virtual page boundary = 4K (current mr_nvme_pg_size is 4K).
1942  * set maximum io transfer = MDTS of NVME device provided by MR firmware.
1943  *
1944  * MR firmware provides value in KB. Caller of this function converts
1945  * kb into bytes.
1946  *
1947  * e.a MDTS=5 means 2^5 * nvme page size. (In case of 4K page size,
1948  * MR firmware provides value 128 as (32 * 4K) = 128K.
1949  *
1950  * @sdev:                               scsi device
1951  * @max_io_size:                                maximum io transfer size
1952  *
1953  */
1954 static inline void
1955 megasas_set_nvme_device_properties(struct scsi_device *sdev, u32 max_io_size)
1956 {
1957         struct megasas_instance *instance;
1958         u32 mr_nvme_pg_size;
1959
1960         instance = (struct megasas_instance *)sdev->host->hostdata;
1961         mr_nvme_pg_size = max_t(u32, instance->nvme_page_size,
1962                                 MR_DEFAULT_NVME_PAGE_SIZE);
1963
1964         blk_queue_max_hw_sectors(sdev->request_queue, (max_io_size / 512));
1965
1966         blk_queue_flag_set(QUEUE_FLAG_NOMERGES, sdev->request_queue);
1967         blk_queue_virt_boundary(sdev->request_queue, mr_nvme_pg_size - 1);
1968 }
1969
1970 /*
1971  * megasas_set_fw_assisted_qd -
1972  * set device queue depth to can_queue
1973  * set device queue depth to fw assisted qd
1974  *
1975  * @sdev:                               scsi device
1976  * @is_target_prop                      true, if fw provided target properties.
1977  */
1978 static void megasas_set_fw_assisted_qd(struct scsi_device *sdev,
1979                                                  bool is_target_prop)
1980 {
1981         u8 interface_type;
1982         u32 device_qd = MEGASAS_DEFAULT_CMD_PER_LUN;
1983         u32 tgt_device_qd;
1984         struct megasas_instance *instance;
1985         struct MR_PRIV_DEVICE *mr_device_priv_data;
1986
1987         instance = megasas_lookup_instance(sdev->host->host_no);
1988         mr_device_priv_data = sdev->hostdata;
1989         interface_type  = mr_device_priv_data->interface_type;
1990
1991         switch (interface_type) {
1992         case SAS_PD:
1993                 device_qd = MEGASAS_SAS_QD;
1994                 break;
1995         case SATA_PD:
1996                 device_qd = MEGASAS_SATA_QD;
1997                 break;
1998         case NVME_PD:
1999                 device_qd = MEGASAS_NVME_QD;
2000                 break;
2001         }
2002
2003         if (is_target_prop) {
2004                 tgt_device_qd = le32_to_cpu(instance->tgt_prop->device_qdepth);
2005                 if (tgt_device_qd)
2006                         device_qd = min(instance->host->can_queue,
2007                                         (int)tgt_device_qd);
2008         }
2009
2010         if (instance->enable_sdev_max_qd && interface_type != UNKNOWN_DRIVE)
2011                 device_qd = instance->host->can_queue;
2012
2013         scsi_change_queue_depth(sdev, device_qd);
2014 }
2015
2016 /*
2017  * megasas_set_static_target_properties -
2018  * Device property set by driver are static and it is not required to be
2019  * updated after OCR.
2020  *
2021  * set io timeout
2022  * set device queue depth
2023  * set nvme device properties. see - megasas_set_nvme_device_properties
2024  *
2025  * @sdev:                               scsi device
2026  * @is_target_prop                      true, if fw provided target properties.
2027  */
2028 static void megasas_set_static_target_properties(struct scsi_device *sdev,
2029                                                  bool is_target_prop)
2030 {
2031         u32 max_io_size_kb = MR_DEFAULT_NVME_MDTS_KB;
2032         struct megasas_instance *instance;
2033
2034         instance = megasas_lookup_instance(sdev->host->host_no);
2035
2036         /*
2037          * The RAID firmware may require extended timeouts.
2038          */
2039         blk_queue_rq_timeout(sdev->request_queue, scmd_timeout * HZ);
2040
2041         /* max_io_size_kb will be set to non zero for
2042          * nvme based vd and syspd.
2043          */
2044         if (is_target_prop)
2045                 max_io_size_kb = le32_to_cpu(instance->tgt_prop->max_io_size_kb);
2046
2047         if (instance->nvme_page_size && max_io_size_kb)
2048                 megasas_set_nvme_device_properties(sdev, (max_io_size_kb << 10));
2049
2050         megasas_set_fw_assisted_qd(sdev, is_target_prop);
2051 }
2052
2053
2054 static int megasas_slave_configure(struct scsi_device *sdev)
2055 {
2056         u16 pd_index = 0;
2057         struct megasas_instance *instance;
2058         int ret_target_prop = DCMD_FAILED;
2059         bool is_target_prop = false;
2060
2061         instance = megasas_lookup_instance(sdev->host->host_no);
2062         if (instance->pd_list_not_supported) {
2063                 if (!MEGASAS_IS_LOGICAL(sdev) && sdev->type == TYPE_DISK) {
2064                         pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
2065                                 sdev->id;
2066                         if (instance->pd_list[pd_index].driveState !=
2067                                 MR_PD_STATE_SYSTEM)
2068                                 return -ENXIO;
2069                 }
2070         }
2071
2072         mutex_lock(&instance->reset_mutex);
2073         /* Send DCMD to Firmware and cache the information */
2074         if ((instance->pd_info) && !MEGASAS_IS_LOGICAL(sdev))
2075                 megasas_get_pd_info(instance, sdev);
2076
2077         /* Some ventura firmware may not have instance->nvme_page_size set.
2078          * Do not send MR_DCMD_DRV_GET_TARGET_PROP
2079          */
2080         if ((instance->tgt_prop) && (instance->nvme_page_size))
2081                 ret_target_prop = megasas_get_target_prop(instance, sdev);
2082
2083         is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false;
2084         megasas_set_static_target_properties(sdev, is_target_prop);
2085
2086         /* This sdev property may change post OCR */
2087         megasas_set_dynamic_target_properties(sdev, is_target_prop);
2088
2089         mutex_unlock(&instance->reset_mutex);
2090
2091         return 0;
2092 }
2093
2094 static int megasas_slave_alloc(struct scsi_device *sdev)
2095 {
2096         u16 pd_index = 0, ld_tgt_id;
2097         struct megasas_instance *instance ;
2098         struct MR_PRIV_DEVICE *mr_device_priv_data;
2099
2100         instance = megasas_lookup_instance(sdev->host->host_no);
2101         if (!MEGASAS_IS_LOGICAL(sdev)) {
2102                 /*
2103                  * Open the OS scan to the SYSTEM PD
2104                  */
2105                 pd_index =
2106                         (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
2107                         sdev->id;
2108                 if ((instance->pd_list_not_supported ||
2109                         instance->pd_list[pd_index].driveState ==
2110                         MR_PD_STATE_SYSTEM)) {
2111                         goto scan_target;
2112                 }
2113                 return -ENXIO;
2114         } else if (!MEGASAS_IS_LUN_VALID(sdev)) {
2115                 sdev_printk(KERN_INFO, sdev, "%s: invalid LUN\n", __func__);
2116                 return -ENXIO;
2117         }
2118
2119 scan_target:
2120         mr_device_priv_data = kzalloc(sizeof(*mr_device_priv_data),
2121                                         GFP_KERNEL);
2122         if (!mr_device_priv_data)
2123                 return -ENOMEM;
2124
2125         if (MEGASAS_IS_LOGICAL(sdev)) {
2126                 ld_tgt_id = MEGASAS_TARGET_ID(sdev);
2127                 instance->ld_tgtid_status[ld_tgt_id] = LD_TARGET_ID_ACTIVE;
2128                 if (megasas_dbg_lvl & LD_PD_DEBUG)
2129                         sdev_printk(KERN_INFO, sdev, "LD target ID %d created.\n", ld_tgt_id);
2130         }
2131
2132         sdev->hostdata = mr_device_priv_data;
2133
2134         atomic_set(&mr_device_priv_data->r1_ldio_hint,
2135                    instance->r1_ldio_hint_default);
2136         return 0;
2137 }
2138
2139 static void megasas_slave_destroy(struct scsi_device *sdev)
2140 {
2141         u16 ld_tgt_id;
2142         struct megasas_instance *instance;
2143
2144         instance = megasas_lookup_instance(sdev->host->host_no);
2145
2146         if (MEGASAS_IS_LOGICAL(sdev)) {
2147                 if (!MEGASAS_IS_LUN_VALID(sdev)) {
2148                         sdev_printk(KERN_INFO, sdev, "%s: invalid LUN\n", __func__);
2149                         return;
2150                 }
2151                 ld_tgt_id = MEGASAS_TARGET_ID(sdev);
2152                 instance->ld_tgtid_status[ld_tgt_id] = LD_TARGET_ID_DELETED;
2153                 if (megasas_dbg_lvl & LD_PD_DEBUG)
2154                         sdev_printk(KERN_INFO, sdev,
2155                                     "LD target ID %d removed from OS stack\n", ld_tgt_id);
2156         }
2157
2158         kfree(sdev->hostdata);
2159         sdev->hostdata = NULL;
2160 }
2161
2162 /*
2163 * megasas_complete_outstanding_ioctls - Complete outstanding ioctls after a
2164 *                                       kill adapter
2165 * @instance:                            Adapter soft state
2166 *
2167 */
2168 static void megasas_complete_outstanding_ioctls(struct megasas_instance *instance)
2169 {
2170         int i;
2171         struct megasas_cmd *cmd_mfi;
2172         struct megasas_cmd_fusion *cmd_fusion;
2173         struct fusion_context *fusion = instance->ctrl_context;
2174
2175         /* Find all outstanding ioctls */
2176         if (fusion) {
2177                 for (i = 0; i < instance->max_fw_cmds; i++) {
2178                         cmd_fusion = fusion->cmd_list[i];
2179                         if (cmd_fusion->sync_cmd_idx != (u32)ULONG_MAX) {
2180                                 cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
2181                                 if (cmd_mfi->sync_cmd &&
2182                                     (cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT)) {
2183                                         cmd_mfi->frame->hdr.cmd_status =
2184                                                         MFI_STAT_WRONG_STATE;
2185                                         megasas_complete_cmd(instance,
2186                                                              cmd_mfi, DID_OK);
2187                                 }
2188                         }
2189                 }
2190         } else {
2191                 for (i = 0; i < instance->max_fw_cmds; i++) {
2192                         cmd_mfi = instance->cmd_list[i];
2193                         if (cmd_mfi->sync_cmd && cmd_mfi->frame->hdr.cmd !=
2194                                 MFI_CMD_ABORT)
2195                                 megasas_complete_cmd(instance, cmd_mfi, DID_OK);
2196                 }
2197         }
2198 }
2199
2200
2201 void megaraid_sas_kill_hba(struct megasas_instance *instance)
2202 {
2203         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2204                 dev_warn(&instance->pdev->dev,
2205                          "Adapter already dead, skipping kill HBA\n");
2206                 return;
2207         }
2208
2209         /* Set critical error to block I/O & ioctls in case caller didn't */
2210         atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR);
2211         /* Wait 1 second to ensure IO or ioctls in build have posted */
2212         msleep(1000);
2213         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2214                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
2215                 (instance->adapter_type != MFI_SERIES)) {
2216                 if (!instance->requestorId) {
2217                         writel(MFI_STOP_ADP, &instance->reg_set->doorbell);
2218                         /* Flush */
2219                         readl(&instance->reg_set->doorbell);
2220                 }
2221                 if (instance->requestorId && instance->peerIsPresent)
2222                         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
2223         } else {
2224                 writel(MFI_STOP_ADP,
2225                         &instance->reg_set->inbound_doorbell);
2226         }
2227         /* Complete outstanding ioctls when adapter is killed */
2228         megasas_complete_outstanding_ioctls(instance);
2229 }
2230
2231  /**
2232   * megasas_check_and_restore_queue_depth - Check if queue depth needs to be
2233   *                                     restored to max value
2234   * @instance:                  Adapter soft state
2235   *
2236   */
2237 void
2238 megasas_check_and_restore_queue_depth(struct megasas_instance *instance)
2239 {
2240         unsigned long flags;
2241
2242         if (instance->flag & MEGASAS_FW_BUSY
2243             && time_after(jiffies, instance->last_time + 5 * HZ)
2244             && atomic_read(&instance->fw_outstanding) <
2245             instance->throttlequeuedepth + 1) {
2246
2247                 spin_lock_irqsave(instance->host->host_lock, flags);
2248                 instance->flag &= ~MEGASAS_FW_BUSY;
2249
2250                 instance->host->can_queue = instance->cur_can_queue;
2251                 spin_unlock_irqrestore(instance->host->host_lock, flags);
2252         }
2253 }
2254
2255 /**
2256  * megasas_complete_cmd_dpc      -      Returns FW's controller structure
2257  * @instance_addr:                      Address of adapter soft state
2258  *
2259  * Tasklet to complete cmds
2260  */
2261 static void megasas_complete_cmd_dpc(unsigned long instance_addr)
2262 {
2263         u32 producer;
2264         u32 consumer;
2265         u32 context;
2266         struct megasas_cmd *cmd;
2267         struct megasas_instance *instance =
2268                                 (struct megasas_instance *)instance_addr;
2269         unsigned long flags;
2270
2271         /* If we have already declared adapter dead, donot complete cmds */
2272         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
2273                 return;
2274
2275         spin_lock_irqsave(&instance->completion_lock, flags);
2276
2277         producer = le32_to_cpu(*instance->producer);
2278         consumer = le32_to_cpu(*instance->consumer);
2279
2280         while (consumer != producer) {
2281                 context = le32_to_cpu(instance->reply_queue[consumer]);
2282                 if (context >= instance->max_fw_cmds) {
2283                         dev_err(&instance->pdev->dev, "Unexpected context value %x\n",
2284                                 context);
2285                         BUG();
2286                 }
2287
2288                 cmd = instance->cmd_list[context];
2289
2290                 megasas_complete_cmd(instance, cmd, DID_OK);
2291
2292                 consumer++;
2293                 if (consumer == (instance->max_fw_cmds + 1)) {
2294                         consumer = 0;
2295                 }
2296         }
2297
2298         *instance->consumer = cpu_to_le32(producer);
2299
2300         spin_unlock_irqrestore(&instance->completion_lock, flags);
2301
2302         /*
2303          * Check if we can restore can_queue
2304          */
2305         megasas_check_and_restore_queue_depth(instance);
2306 }
2307
2308 static void megasas_sriov_heartbeat_handler(struct timer_list *t);
2309
2310 /**
2311  * megasas_start_timer - Initializes sriov heartbeat timer object
2312  * @instance:           Adapter soft state
2313  *
2314  */
2315 void megasas_start_timer(struct megasas_instance *instance)
2316 {
2317         struct timer_list *timer = &instance->sriov_heartbeat_timer;
2318
2319         timer_setup(timer, megasas_sriov_heartbeat_handler, 0);
2320         timer->expires = jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF;
2321         add_timer(timer);
2322 }
2323
2324 static void
2325 megasas_internal_reset_defer_cmds(struct megasas_instance *instance);
2326
2327 static void
2328 process_fw_state_change_wq(struct work_struct *work);
2329
2330 static void megasas_do_ocr(struct megasas_instance *instance)
2331 {
2332         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
2333         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
2334         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
2335                 *instance->consumer = cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
2336         }
2337         instance->instancet->disable_intr(instance);
2338         atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
2339         instance->issuepend_done = 0;
2340
2341         atomic_set(&instance->fw_outstanding, 0);
2342         megasas_internal_reset_defer_cmds(instance);
2343         process_fw_state_change_wq(&instance->work_init);
2344 }
2345
2346 static int megasas_get_ld_vf_affiliation_111(struct megasas_instance *instance,
2347                                             int initial)
2348 {
2349         struct megasas_cmd *cmd;
2350         struct megasas_dcmd_frame *dcmd;
2351         struct MR_LD_VF_AFFILIATION_111 *new_affiliation_111 = NULL;
2352         dma_addr_t new_affiliation_111_h;
2353         int ld, retval = 0;
2354         u8 thisVf;
2355
2356         cmd = megasas_get_cmd(instance);
2357
2358         if (!cmd) {
2359                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation_111:"
2360                        "Failed to get cmd for scsi%d\n",
2361                         instance->host->host_no);
2362                 return -ENOMEM;
2363         }
2364
2365         dcmd = &cmd->frame->dcmd;
2366
2367         if (!instance->vf_affiliation_111) {
2368                 dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF "
2369                        "affiliation for scsi%d\n", instance->host->host_no);
2370                 megasas_return_cmd(instance, cmd);
2371                 return -ENOMEM;
2372         }
2373
2374         if (initial)
2375                         memset(instance->vf_affiliation_111, 0,
2376                                sizeof(struct MR_LD_VF_AFFILIATION_111));
2377         else {
2378                 new_affiliation_111 =
2379                         dma_alloc_coherent(&instance->pdev->dev,
2380                                            sizeof(struct MR_LD_VF_AFFILIATION_111),
2381                                            &new_affiliation_111_h, GFP_KERNEL);
2382                 if (!new_affiliation_111) {
2383                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate "
2384                                "memory for new affiliation for scsi%d\n",
2385                                instance->host->host_no);
2386                         megasas_return_cmd(instance, cmd);
2387                         return -ENOMEM;
2388                 }
2389         }
2390
2391         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2392
2393         dcmd->cmd = MFI_CMD_DCMD;
2394         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2395         dcmd->sge_count = 1;
2396         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2397         dcmd->timeout = 0;
2398         dcmd->pad_0 = 0;
2399         dcmd->data_xfer_len =
2400                 cpu_to_le32(sizeof(struct MR_LD_VF_AFFILIATION_111));
2401         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS_111);
2402
2403         if (initial)
2404                 dcmd->sgl.sge32[0].phys_addr =
2405                         cpu_to_le32(instance->vf_affiliation_111_h);
2406         else
2407                 dcmd->sgl.sge32[0].phys_addr =
2408                         cpu_to_le32(new_affiliation_111_h);
2409
2410         dcmd->sgl.sge32[0].length = cpu_to_le32(
2411                 sizeof(struct MR_LD_VF_AFFILIATION_111));
2412
2413         dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for "
2414                "scsi%d\n", instance->host->host_no);
2415
2416         if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) {
2417                 dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD"
2418                        " failed with status 0x%x for scsi%d\n",
2419                        dcmd->cmd_status, instance->host->host_no);
2420                 retval = 1; /* Do a scan if we couldn't get affiliation */
2421                 goto out;
2422         }
2423
2424         if (!initial) {
2425                 thisVf = new_affiliation_111->thisVf;
2426                 for (ld = 0 ; ld < new_affiliation_111->vdCount; ld++)
2427                         if (instance->vf_affiliation_111->map[ld].policy[thisVf] !=
2428                             new_affiliation_111->map[ld].policy[thisVf]) {
2429                                 dev_warn(&instance->pdev->dev, "SR-IOV: "
2430                                        "Got new LD/VF affiliation for scsi%d\n",
2431                                        instance->host->host_no);
2432                                 memcpy(instance->vf_affiliation_111,
2433                                        new_affiliation_111,
2434                                        sizeof(struct MR_LD_VF_AFFILIATION_111));
2435                                 retval = 1;
2436                                 goto out;
2437                         }
2438         }
2439 out:
2440         if (new_affiliation_111) {
2441                 dma_free_coherent(&instance->pdev->dev,
2442                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
2443                                     new_affiliation_111,
2444                                     new_affiliation_111_h);
2445         }
2446
2447         megasas_return_cmd(instance, cmd);
2448
2449         return retval;
2450 }
2451
2452 static int megasas_get_ld_vf_affiliation_12(struct megasas_instance *instance,
2453                                             int initial)
2454 {
2455         struct megasas_cmd *cmd;
2456         struct megasas_dcmd_frame *dcmd;
2457         struct MR_LD_VF_AFFILIATION *new_affiliation = NULL;
2458         struct MR_LD_VF_MAP *newmap = NULL, *savedmap = NULL;
2459         dma_addr_t new_affiliation_h;
2460         int i, j, retval = 0, found = 0, doscan = 0;
2461         u8 thisVf;
2462
2463         cmd = megasas_get_cmd(instance);
2464
2465         if (!cmd) {
2466                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation12: "
2467                        "Failed to get cmd for scsi%d\n",
2468                        instance->host->host_no);
2469                 return -ENOMEM;
2470         }
2471
2472         dcmd = &cmd->frame->dcmd;
2473
2474         if (!instance->vf_affiliation) {
2475                 dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF "
2476                        "affiliation for scsi%d\n", instance->host->host_no);
2477                 megasas_return_cmd(instance, cmd);
2478                 return -ENOMEM;
2479         }
2480
2481         if (initial)
2482                 memset(instance->vf_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) *
2483                        sizeof(struct MR_LD_VF_AFFILIATION));
2484         else {
2485                 new_affiliation =
2486                         dma_alloc_coherent(&instance->pdev->dev,
2487                                            (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION),
2488                                            &new_affiliation_h, GFP_KERNEL);
2489                 if (!new_affiliation) {
2490                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate "
2491                                "memory for new affiliation for scsi%d\n",
2492                                instance->host->host_no);
2493                         megasas_return_cmd(instance, cmd);
2494                         return -ENOMEM;
2495                 }
2496         }
2497
2498         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2499
2500         dcmd->cmd = MFI_CMD_DCMD;
2501         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2502         dcmd->sge_count = 1;
2503         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2504         dcmd->timeout = 0;
2505         dcmd->pad_0 = 0;
2506         dcmd->data_xfer_len = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2507                 sizeof(struct MR_LD_VF_AFFILIATION));
2508         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS);
2509
2510         if (initial)
2511                 dcmd->sgl.sge32[0].phys_addr =
2512                         cpu_to_le32(instance->vf_affiliation_h);
2513         else
2514                 dcmd->sgl.sge32[0].phys_addr =
2515                         cpu_to_le32(new_affiliation_h);
2516
2517         dcmd->sgl.sge32[0].length = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2518                 sizeof(struct MR_LD_VF_AFFILIATION));
2519
2520         dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for "
2521                "scsi%d\n", instance->host->host_no);
2522
2523
2524         if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) {
2525                 dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD"
2526                        " failed with status 0x%x for scsi%d\n",
2527                        dcmd->cmd_status, instance->host->host_no);
2528                 retval = 1; /* Do a scan if we couldn't get affiliation */
2529                 goto out;
2530         }
2531
2532         if (!initial) {
2533                 if (!new_affiliation->ldCount) {
2534                         dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF "
2535                                "affiliation for passive path for scsi%d\n",
2536                                instance->host->host_no);
2537                         retval = 1;
2538                         goto out;
2539                 }
2540                 newmap = new_affiliation->map;
2541                 savedmap = instance->vf_affiliation->map;
2542                 thisVf = new_affiliation->thisVf;
2543                 for (i = 0 ; i < new_affiliation->ldCount; i++) {
2544                         found = 0;
2545                         for (j = 0; j < instance->vf_affiliation->ldCount;
2546                              j++) {
2547                                 if (newmap->ref.targetId ==
2548                                     savedmap->ref.targetId) {
2549                                         found = 1;
2550                                         if (newmap->policy[thisVf] !=
2551                                             savedmap->policy[thisVf]) {
2552                                                 doscan = 1;
2553                                                 goto out;
2554                                         }
2555                                 }
2556                                 savedmap = (struct MR_LD_VF_MAP *)
2557                                         ((unsigned char *)savedmap +
2558                                          savedmap->size);
2559                         }
2560                         if (!found && newmap->policy[thisVf] !=
2561                             MR_LD_ACCESS_HIDDEN) {
2562                                 doscan = 1;
2563                                 goto out;
2564                         }
2565                         newmap = (struct MR_LD_VF_MAP *)
2566                                 ((unsigned char *)newmap + newmap->size);
2567                 }
2568
2569                 newmap = new_affiliation->map;
2570                 savedmap = instance->vf_affiliation->map;
2571
2572                 for (i = 0 ; i < instance->vf_affiliation->ldCount; i++) {
2573                         found = 0;
2574                         for (j = 0 ; j < new_affiliation->ldCount; j++) {
2575                                 if (savedmap->ref.targetId ==
2576                                     newmap->ref.targetId) {
2577                                         found = 1;
2578                                         if (savedmap->policy[thisVf] !=
2579                                             newmap->policy[thisVf]) {
2580                                                 doscan = 1;
2581                                                 goto out;
2582                                         }
2583                                 }
2584                                 newmap = (struct MR_LD_VF_MAP *)
2585                                         ((unsigned char *)newmap +
2586                                          newmap->size);
2587                         }
2588                         if (!found && savedmap->policy[thisVf] !=
2589                             MR_LD_ACCESS_HIDDEN) {
2590                                 doscan = 1;
2591                                 goto out;
2592                         }
2593                         savedmap = (struct MR_LD_VF_MAP *)
2594                                 ((unsigned char *)savedmap +
2595                                  savedmap->size);
2596                 }
2597         }
2598 out:
2599         if (doscan) {
2600                 dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF "
2601                        "affiliation for scsi%d\n", instance->host->host_no);
2602                 memcpy(instance->vf_affiliation, new_affiliation,
2603                        new_affiliation->size);
2604                 retval = 1;
2605         }
2606
2607         if (new_affiliation)
2608                 dma_free_coherent(&instance->pdev->dev,
2609                                     (MAX_LOGICAL_DRIVES + 1) *
2610                                     sizeof(struct MR_LD_VF_AFFILIATION),
2611                                     new_affiliation, new_affiliation_h);
2612         megasas_return_cmd(instance, cmd);
2613
2614         return retval;
2615 }
2616
2617 /* This function will get the current SR-IOV LD/VF affiliation */
2618 static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
2619         int initial)
2620 {
2621         int retval;
2622
2623         if (instance->PlasmaFW111)
2624                 retval = megasas_get_ld_vf_affiliation_111(instance, initial);
2625         else
2626                 retval = megasas_get_ld_vf_affiliation_12(instance, initial);
2627         return retval;
2628 }
2629
2630 /* This function will tell FW to start the SR-IOV heartbeat */
2631 int megasas_sriov_start_heartbeat(struct megasas_instance *instance,
2632                                          int initial)
2633 {
2634         struct megasas_cmd *cmd;
2635         struct megasas_dcmd_frame *dcmd;
2636         int retval = 0;
2637
2638         cmd = megasas_get_cmd(instance);
2639
2640         if (!cmd) {
2641                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_sriov_start_heartbeat: "
2642                        "Failed to get cmd for scsi%d\n",
2643                        instance->host->host_no);
2644                 return -ENOMEM;
2645         }
2646
2647         dcmd = &cmd->frame->dcmd;
2648
2649         if (initial) {
2650                 instance->hb_host_mem =
2651                         dma_alloc_coherent(&instance->pdev->dev,
2652                                            sizeof(struct MR_CTRL_HB_HOST_MEM),
2653                                            &instance->hb_host_mem_h,
2654                                            GFP_KERNEL);
2655                 if (!instance->hb_host_mem) {
2656                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate"
2657                                " memory for heartbeat host memory for scsi%d\n",
2658                                instance->host->host_no);
2659                         retval = -ENOMEM;
2660                         goto out;
2661                 }
2662         }
2663
2664         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2665
2666         dcmd->mbox.s[0] = cpu_to_le16(sizeof(struct MR_CTRL_HB_HOST_MEM));
2667         dcmd->cmd = MFI_CMD_DCMD;
2668         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2669         dcmd->sge_count = 1;
2670         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2671         dcmd->timeout = 0;
2672         dcmd->pad_0 = 0;
2673         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_CTRL_HB_HOST_MEM));
2674         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SHARED_HOST_MEM_ALLOC);
2675
2676         megasas_set_dma_settings(instance, dcmd, instance->hb_host_mem_h,
2677                                  sizeof(struct MR_CTRL_HB_HOST_MEM));
2678
2679         dev_warn(&instance->pdev->dev, "SR-IOV: Starting heartbeat for scsi%d\n",
2680                instance->host->host_no);
2681
2682         if ((instance->adapter_type != MFI_SERIES) &&
2683             !instance->mask_interrupts)
2684                 retval = megasas_issue_blocked_cmd(instance, cmd,
2685                         MEGASAS_ROUTINE_WAIT_TIME_VF);
2686         else
2687                 retval = megasas_issue_polled(instance, cmd);
2688
2689         if (retval) {
2690                 dev_warn(&instance->pdev->dev, "SR-IOV: MR_DCMD_CTRL_SHARED_HOST"
2691                         "_MEM_ALLOC DCMD %s for scsi%d\n",
2692                         (dcmd->cmd_status == MFI_STAT_INVALID_STATUS) ?
2693                         "timed out" : "failed", instance->host->host_no);
2694                 retval = 1;
2695         }
2696
2697 out:
2698         megasas_return_cmd(instance, cmd);
2699
2700         return retval;
2701 }
2702
2703 /* Handler for SR-IOV heartbeat */
2704 static void megasas_sriov_heartbeat_handler(struct timer_list *t)
2705 {
2706         struct megasas_instance *instance =
2707                 from_timer(instance, t, sriov_heartbeat_timer);
2708
2709         if (instance->hb_host_mem->HB.fwCounter !=
2710             instance->hb_host_mem->HB.driverCounter) {
2711                 instance->hb_host_mem->HB.driverCounter =
2712                         instance->hb_host_mem->HB.fwCounter;
2713                 mod_timer(&instance->sriov_heartbeat_timer,
2714                           jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
2715         } else {
2716                 dev_warn(&instance->pdev->dev, "SR-IOV: Heartbeat never "
2717                        "completed for scsi%d\n", instance->host->host_no);
2718                 schedule_work(&instance->work_init);
2719         }
2720 }
2721
2722 /**
2723  * megasas_wait_for_outstanding -       Wait for all outstanding cmds
2724  * @instance:                           Adapter soft state
2725  *
2726  * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to
2727  * complete all its outstanding commands. Returns error if one or more IOs
2728  * are pending after this time period. It also marks the controller dead.
2729  */
2730 static int megasas_wait_for_outstanding(struct megasas_instance *instance)
2731 {
2732         int i, sl, outstanding;
2733         u32 reset_index;
2734         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
2735         unsigned long flags;
2736         struct list_head clist_local;
2737         struct megasas_cmd *reset_cmd;
2738         u32 fw_state;
2739
2740         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2741                 dev_info(&instance->pdev->dev, "%s:%d HBA is killed.\n",
2742                 __func__, __LINE__);
2743                 return FAILED;
2744         }
2745
2746         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
2747
2748                 INIT_LIST_HEAD(&clist_local);
2749                 spin_lock_irqsave(&instance->hba_lock, flags);
2750                 list_splice_init(&instance->internal_reset_pending_q,
2751                                 &clist_local);
2752                 spin_unlock_irqrestore(&instance->hba_lock, flags);
2753
2754                 dev_notice(&instance->pdev->dev, "HBA reset wait ...\n");
2755                 for (i = 0; i < wait_time; i++) {
2756                         msleep(1000);
2757                         if (atomic_read(&instance->adprecovery) == MEGASAS_HBA_OPERATIONAL)
2758                                 break;
2759                 }
2760
2761                 if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
2762                         dev_notice(&instance->pdev->dev, "reset: Stopping HBA.\n");
2763                         atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR);
2764                         return FAILED;
2765                 }
2766
2767                 reset_index = 0;
2768                 while (!list_empty(&clist_local)) {
2769                         reset_cmd = list_entry((&clist_local)->next,
2770                                                 struct megasas_cmd, list);
2771                         list_del_init(&reset_cmd->list);
2772                         if (reset_cmd->scmd) {
2773                                 reset_cmd->scmd->result = DID_REQUEUE << 16;
2774                                 dev_notice(&instance->pdev->dev, "%d:%p reset [%02x]\n",
2775                                         reset_index, reset_cmd,
2776                                         reset_cmd->scmd->cmnd[0]);
2777
2778                                 reset_cmd->scmd->scsi_done(reset_cmd->scmd);
2779                                 megasas_return_cmd(instance, reset_cmd);
2780                         } else if (reset_cmd->sync_cmd) {
2781                                 dev_notice(&instance->pdev->dev, "%p synch cmds"
2782                                                 "reset queue\n",
2783                                                 reset_cmd);
2784
2785                                 reset_cmd->cmd_status_drv = DCMD_INIT;
2786                                 instance->instancet->fire_cmd(instance,
2787                                                 reset_cmd->frame_phys_addr,
2788                                                 0, instance->reg_set);
2789                         } else {
2790                                 dev_notice(&instance->pdev->dev, "%p unexpected"
2791                                         "cmds lst\n",
2792                                         reset_cmd);
2793                         }
2794                         reset_index++;
2795                 }
2796
2797                 return SUCCESS;
2798         }
2799
2800         for (i = 0; i < resetwaittime; i++) {
2801                 outstanding = atomic_read(&instance->fw_outstanding);
2802
2803                 if (!outstanding)
2804                         break;
2805
2806                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
2807                         dev_notice(&instance->pdev->dev, "[%2d]waiting for %d "
2808                                "commands to complete\n",i,outstanding);
2809                         /*
2810                          * Call cmd completion routine. Cmd to be
2811                          * be completed directly without depending on isr.
2812                          */
2813                         megasas_complete_cmd_dpc((unsigned long)instance);
2814                 }
2815
2816                 msleep(1000);
2817         }
2818
2819         i = 0;
2820         outstanding = atomic_read(&instance->fw_outstanding);
2821         fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK;
2822
2823         if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL)))
2824                 goto no_outstanding;
2825
2826         if (instance->disableOnlineCtrlReset)
2827                 goto kill_hba_and_failed;
2828         do {
2829                 if ((fw_state == MFI_STATE_FAULT) || atomic_read(&instance->fw_outstanding)) {
2830                         dev_info(&instance->pdev->dev,
2831                                 "%s:%d waiting_for_outstanding: before issue OCR. FW state = 0x%x, outstanding 0x%x\n",
2832                                 __func__, __LINE__, fw_state, atomic_read(&instance->fw_outstanding));
2833                         if (i == 3)
2834                                 goto kill_hba_and_failed;
2835                         megasas_do_ocr(instance);
2836
2837                         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2838                                 dev_info(&instance->pdev->dev, "%s:%d OCR failed and HBA is killed.\n",
2839                                 __func__, __LINE__);
2840                                 return FAILED;
2841                         }
2842                         dev_info(&instance->pdev->dev, "%s:%d waiting_for_outstanding: after issue OCR.\n",
2843                                 __func__, __LINE__);
2844
2845                         for (sl = 0; sl < 10; sl++)
2846                                 msleep(500);
2847
2848                         outstanding = atomic_read(&instance->fw_outstanding);
2849
2850                         fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK;
2851                         if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL)))
2852                                 goto no_outstanding;
2853                 }
2854                 i++;
2855         } while (i <= 3);
2856
2857 no_outstanding:
2858
2859         dev_info(&instance->pdev->dev, "%s:%d no more pending commands remain after reset handling.\n",
2860                 __func__, __LINE__);
2861         return SUCCESS;
2862
2863 kill_hba_and_failed:
2864
2865         /* Reset not supported, kill adapter */
2866         dev_info(&instance->pdev->dev, "%s:%d killing adapter scsi%d"
2867                 " disableOnlineCtrlReset %d fw_outstanding %d \n",
2868                 __func__, __LINE__, instance->host->host_no, instance->disableOnlineCtrlReset,
2869                 atomic_read(&instance->fw_outstanding));
2870         megasas_dump_pending_frames(instance);
2871         megaraid_sas_kill_hba(instance);
2872
2873         return FAILED;
2874 }
2875
2876 /**
2877  * megasas_generic_reset -      Generic reset routine
2878  * @scmd:                       Mid-layer SCSI command
2879  *
2880  * This routine implements a generic reset handler for device, bus and host
2881  * reset requests. Device, bus and host specific reset handlers can use this
2882  * function after they do their specific tasks.
2883  */
2884 static int megasas_generic_reset(struct scsi_cmnd *scmd)
2885 {
2886         int ret_val;
2887         struct megasas_instance *instance;
2888
2889         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2890
2891         scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n",
2892                  scmd->cmnd[0], scmd->retries);
2893
2894         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2895                 dev_err(&instance->pdev->dev, "cannot recover from previous reset failures\n");
2896                 return FAILED;
2897         }
2898
2899         ret_val = megasas_wait_for_outstanding(instance);
2900         if (ret_val == SUCCESS)
2901                 dev_notice(&instance->pdev->dev, "reset successful\n");
2902         else
2903                 dev_err(&instance->pdev->dev, "failed to do reset\n");
2904
2905         return ret_val;
2906 }
2907
2908 /**
2909  * megasas_reset_timer - quiesce the adapter if required
2910  * @scmd:               scsi cmnd
2911  *
2912  * Sets the FW busy flag and reduces the host->can_queue if the
2913  * cmd has not been completed within the timeout period.
2914  */
2915 static enum
2916 blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
2917 {
2918         struct megasas_instance *instance;
2919         unsigned long flags;
2920
2921         if (time_after(jiffies, scmd->jiffies_at_alloc +
2922                                 (scmd_timeout * 2) * HZ)) {
2923                 return BLK_EH_DONE;
2924         }
2925
2926         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2927         if (!(instance->flag & MEGASAS_FW_BUSY)) {
2928                 /* FW is busy, throttle IO */
2929                 spin_lock_irqsave(instance->host->host_lock, flags);
2930
2931                 instance->host->can_queue = instance->throttlequeuedepth;
2932                 instance->last_time = jiffies;
2933                 instance->flag |= MEGASAS_FW_BUSY;
2934
2935                 spin_unlock_irqrestore(instance->host->host_lock, flags);
2936         }
2937         return BLK_EH_RESET_TIMER;
2938 }
2939
2940 /**
2941  * megasas_dump -       This function will print hexdump of provided buffer.
2942  * @buf:                Buffer to be dumped
2943  * @sz:         Size in bytes
2944  * @format:             Different formats of dumping e.g. format=n will
2945  *                      cause only 'n' 32 bit words to be dumped in a single
2946  *                      line.
2947  */
2948 inline void
2949 megasas_dump(void *buf, int sz, int format)
2950 {
2951         int i;
2952         __le32 *buf_loc = (__le32 *)buf;
2953
2954         for (i = 0; i < (sz / sizeof(__le32)); i++) {
2955                 if ((i % format) == 0) {
2956                         if (i != 0)
2957                                 printk(KERN_CONT "\n");
2958                         printk(KERN_CONT "%08x: ", (i * 4));
2959                 }
2960                 printk(KERN_CONT "%08x ", le32_to_cpu(buf_loc[i]));
2961         }
2962         printk(KERN_CONT "\n");
2963 }
2964
2965 /**
2966  * megasas_dump_reg_set -       This function will print hexdump of register set
2967  * @reg_set:    Register set to be dumped
2968  */
2969 inline void
2970 megasas_dump_reg_set(void __iomem *reg_set)
2971 {
2972         unsigned int i, sz = 256;
2973         u32 __iomem *reg = (u32 __iomem *)reg_set;
2974
2975         for (i = 0; i < (sz / sizeof(u32)); i++)
2976                 printk("%08x: %08x\n", (i * 4), readl(&reg[i]));
2977 }
2978
2979 /**
2980  * megasas_dump_fusion_io -     This function will print key details
2981  *                              of SCSI IO
2982  * @scmd:                       SCSI command pointer of SCSI IO
2983  */
2984 void
2985 megasas_dump_fusion_io(struct scsi_cmnd *scmd)
2986 {
2987         struct megasas_cmd_fusion *cmd;
2988         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
2989         struct megasas_instance *instance;
2990
2991         cmd = (struct megasas_cmd_fusion *)scmd->SCp.ptr;
2992         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2993
2994         scmd_printk(KERN_INFO, scmd,
2995                     "scmd: (0x%p)  retries: 0x%x  allowed: 0x%x\n",
2996                     scmd, scmd->retries, scmd->allowed);
2997         scsi_print_command(scmd);
2998
2999         if (cmd) {
3000                 req_desc = (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)cmd->request_desc;
3001                 scmd_printk(KERN_INFO, scmd, "Request descriptor details:\n");
3002                 scmd_printk(KERN_INFO, scmd,
3003                             "RequestFlags:0x%x  MSIxIndex:0x%x  SMID:0x%x  LMID:0x%x  DevHandle:0x%x\n",
3004                             req_desc->SCSIIO.RequestFlags,
3005                             req_desc->SCSIIO.MSIxIndex, req_desc->SCSIIO.SMID,
3006                             req_desc->SCSIIO.LMID, req_desc->SCSIIO.DevHandle);
3007
3008                 printk(KERN_INFO "IO request frame:\n");
3009                 megasas_dump(cmd->io_request,
3010                              MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE, 8);
3011                 printk(KERN_INFO "Chain frame:\n");
3012                 megasas_dump(cmd->sg_frame,
3013                              instance->max_chain_frame_sz, 8);
3014         }
3015
3016 }
3017
3018 /*
3019  * megasas_dump_sys_regs - This function will dump system registers through
3020  *                          sysfs.
3021  * @reg_set:                Pointer to System register set.
3022  * @buf:                    Buffer to which output is to be written.
3023  * @return:                 Number of bytes written to buffer.
3024  */
3025 static inline ssize_t
3026 megasas_dump_sys_regs(void __iomem *reg_set, char *buf)
3027 {
3028         unsigned int i, sz = 256;
3029         int bytes_wrote = 0;
3030         char *loc = (char *)buf;
3031         u32 __iomem *reg = (u32 __iomem *)reg_set;
3032
3033         for (i = 0; i < sz / sizeof(u32); i++) {
3034                 bytes_wrote += scnprintf(loc + bytes_wrote,
3035                                          PAGE_SIZE - bytes_wrote,
3036                                          "%08x: %08x\n", (i * 4),
3037                                          readl(&reg[i]));
3038         }
3039         return bytes_wrote;
3040 }
3041
3042 /**
3043  * megasas_reset_bus_host -     Bus & host reset handler entry point
3044  * @scmd:                       Mid-layer SCSI command
3045  */
3046 static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
3047 {
3048         int ret;
3049         struct megasas_instance *instance;
3050
3051         instance = (struct megasas_instance *)scmd->device->host->hostdata;
3052
3053         scmd_printk(KERN_INFO, scmd,
3054                 "OCR is requested due to IO timeout!!\n");
3055
3056         scmd_printk(KERN_INFO, scmd,
3057                 "SCSI host state: %d  SCSI host busy: %d  FW outstanding: %d\n",
3058                 scmd->device->host->shost_state,
3059                 scsi_host_busy(scmd->device->host),
3060                 atomic_read(&instance->fw_outstanding));
3061         /*
3062          * First wait for all commands to complete
3063          */
3064         if (instance->adapter_type == MFI_SERIES) {
3065                 ret = megasas_generic_reset(scmd);
3066         } else {
3067                 megasas_dump_fusion_io(scmd);
3068                 ret = megasas_reset_fusion(scmd->device->host,
3069                                 SCSIIO_TIMEOUT_OCR);
3070         }
3071
3072         return ret;
3073 }
3074
3075 /**
3076  * megasas_task_abort - Issues task abort request to firmware
3077  *                      (supported only for fusion adapters)
3078  * @scmd:               SCSI command pointer
3079  */
3080 static int megasas_task_abort(struct scsi_cmnd *scmd)
3081 {
3082         int ret;
3083         struct megasas_instance *instance;
3084
3085         instance = (struct megasas_instance *)scmd->device->host->hostdata;
3086
3087         if (instance->adapter_type != MFI_SERIES)
3088                 ret = megasas_task_abort_fusion(scmd);
3089         else {
3090                 sdev_printk(KERN_NOTICE, scmd->device, "TASK ABORT not supported\n");
3091                 ret = FAILED;
3092         }
3093
3094         return ret;
3095 }
3096
3097 /**
3098  * megasas_reset_target:  Issues target reset request to firmware
3099  *                        (supported only for fusion adapters)
3100  * @scmd:                 SCSI command pointer
3101  */
3102 static int megasas_reset_target(struct scsi_cmnd *scmd)
3103 {
3104         int ret;
3105         struct megasas_instance *instance;
3106
3107         instance = (struct megasas_instance *)scmd->device->host->hostdata;
3108
3109         if (instance->adapter_type != MFI_SERIES)
3110                 ret = megasas_reset_target_fusion(scmd);
3111         else {
3112                 sdev_printk(KERN_NOTICE, scmd->device, "TARGET RESET not supported\n");
3113                 ret = FAILED;
3114         }
3115
3116         return ret;
3117 }
3118
3119 /**
3120  * megasas_bios_param - Returns disk geometry for a disk
3121  * @sdev:               device handle
3122  * @bdev:               block device
3123  * @capacity:           drive capacity
3124  * @geom:               geometry parameters
3125  */
3126 static int
3127 megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
3128                  sector_t capacity, int geom[])
3129 {
3130         int heads;
3131         int sectors;
3132         sector_t cylinders;
3133         unsigned long tmp;
3134
3135         /* Default heads (64) & sectors (32) */
3136         heads = 64;
3137         sectors = 32;
3138
3139         tmp = heads * sectors;
3140         cylinders = capacity;
3141
3142         sector_div(cylinders, tmp);
3143
3144         /*
3145          * Handle extended translation size for logical drives > 1Gb
3146          */
3147
3148         if (capacity >= 0x200000) {
3149                 heads = 255;
3150                 sectors = 63;
3151                 tmp = heads*sectors;
3152                 cylinders = capacity;
3153                 sector_div(cylinders, tmp);
3154         }
3155
3156         geom[0] = heads;
3157         geom[1] = sectors;
3158         geom[2] = cylinders;
3159
3160         return 0;
3161 }
3162
3163 static void megasas_aen_polling(struct work_struct *work);
3164
3165 /**
3166  * megasas_service_aen -        Processes an event notification
3167  * @instance:                   Adapter soft state
3168  * @cmd:                        AEN command completed by the ISR
3169  *
3170  * For AEN, driver sends a command down to FW that is held by the FW till an
3171  * event occurs. When an event of interest occurs, FW completes the command
3172  * that it was previously holding.
3173  *
3174  * This routines sends SIGIO signal to processes that have registered with the
3175  * driver for AEN.
3176  */
3177 static void
3178 megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
3179 {
3180         unsigned long flags;
3181
3182         /*
3183          * Don't signal app if it is just an aborted previously registered aen
3184          */
3185         if ((!cmd->abort_aen) && (instance->unload == 0)) {
3186                 spin_lock_irqsave(&poll_aen_lock, flags);
3187                 megasas_poll_wait_aen = 1;
3188                 spin_unlock_irqrestore(&poll_aen_lock, flags);
3189                 wake_up(&megasas_poll_wait);
3190                 kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
3191         }
3192         else
3193                 cmd->abort_aen = 0;
3194
3195         instance->aen_cmd = NULL;
3196
3197         megasas_return_cmd(instance, cmd);
3198
3199         if ((instance->unload == 0) &&
3200                 ((instance->issuepend_done == 1))) {
3201                 struct megasas_aen_event *ev;
3202
3203                 ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
3204                 if (!ev) {
3205                         dev_err(&instance->pdev->dev, "megasas_service_aen: out of memory\n");
3206                 } else {
3207                         ev->instance = instance;
3208                         instance->ev = ev;
3209                         INIT_DELAYED_WORK(&ev->hotplug_work,
3210                                           megasas_aen_polling);
3211                         schedule_delayed_work(&ev->hotplug_work, 0);
3212                 }
3213         }
3214 }
3215
3216 static ssize_t
3217 fw_crash_buffer_store(struct device *cdev,
3218         struct device_attribute *attr, const char *buf, size_t count)
3219 {
3220         struct Scsi_Host *shost = class_to_shost(cdev);
3221         struct megasas_instance *instance =
3222                 (struct megasas_instance *) shost->hostdata;
3223         int val = 0;
3224         unsigned long flags;
3225
3226         if (kstrtoint(buf, 0, &val) != 0)
3227                 return -EINVAL;
3228
3229         spin_lock_irqsave(&instance->crashdump_lock, flags);
3230         instance->fw_crash_buffer_offset = val;
3231         spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3232         return strlen(buf);
3233 }
3234
3235 static ssize_t
3236 fw_crash_buffer_show(struct device *cdev,
3237         struct device_attribute *attr, char *buf)
3238 {
3239         struct Scsi_Host *shost = class_to_shost(cdev);
3240         struct megasas_instance *instance =
3241                 (struct megasas_instance *) shost->hostdata;
3242         u32 size;
3243         unsigned long dmachunk = CRASH_DMA_BUF_SIZE;
3244         unsigned long chunk_left_bytes;
3245         unsigned long src_addr;
3246         unsigned long flags;
3247         u32 buff_offset;
3248
3249         spin_lock_irqsave(&instance->crashdump_lock, flags);
3250         buff_offset = instance->fw_crash_buffer_offset;
3251         if (!instance->crash_dump_buf &&
3252                 !((instance->fw_crash_state == AVAILABLE) ||
3253                 (instance->fw_crash_state == COPYING))) {
3254                 dev_err(&instance->pdev->dev,
3255                         "Firmware crash dump is not available\n");
3256                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3257                 return -EINVAL;
3258         }
3259
3260         if (buff_offset > (instance->fw_crash_buffer_size * dmachunk)) {
3261                 dev_err(&instance->pdev->dev,
3262                         "Firmware crash dump offset is out of range\n");
3263                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3264                 return 0;
3265         }
3266
3267         size = (instance->fw_crash_buffer_size * dmachunk) - buff_offset;
3268         chunk_left_bytes = dmachunk - (buff_offset % dmachunk);
3269         size = (size > chunk_left_bytes) ? chunk_left_bytes : size;
3270         size = (size >= PAGE_SIZE) ? (PAGE_SIZE - 1) : size;
3271
3272         src_addr = (unsigned long)instance->crash_buf[buff_offset / dmachunk] +
3273                 (buff_offset % dmachunk);
3274         memcpy(buf, (void *)src_addr, size);
3275         spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3276
3277         return size;
3278 }
3279
3280 static ssize_t
3281 fw_crash_buffer_size_show(struct device *cdev,
3282         struct device_attribute *attr, char *buf)
3283 {
3284         struct Scsi_Host *shost = class_to_shost(cdev);
3285         struct megasas_instance *instance =
3286                 (struct megasas_instance *) shost->hostdata;
3287
3288         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)
3289                 ((instance->fw_crash_buffer_size) * 1024 * 1024)/PAGE_SIZE);
3290 }
3291
3292 static ssize_t
3293 fw_crash_state_store(struct device *cdev,
3294         struct device_attribute *attr, const char *buf, size_t count)
3295 {
3296         struct Scsi_Host *shost = class_to_shost(cdev);
3297         struct megasas_instance *instance =
3298                 (struct megasas_instance *) shost->hostdata;
3299         int val = 0;
3300         unsigned long flags;
3301
3302         if (kstrtoint(buf, 0, &val) != 0)
3303                 return -EINVAL;
3304
3305         if ((val <= AVAILABLE || val > COPY_ERROR)) {
3306                 dev_err(&instance->pdev->dev, "application updates invalid "
3307                         "firmware crash state\n");
3308                 return -EINVAL;
3309         }
3310
3311         instance->fw_crash_state = val;
3312
3313         if ((val == COPIED) || (val == COPY_ERROR)) {
3314                 spin_lock_irqsave(&instance->crashdump_lock, flags);
3315                 megasas_free_host_crash_buffer(instance);
3316                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3317                 if (val == COPY_ERROR)
3318                         dev_info(&instance->pdev->dev, "application failed to "
3319                                 "copy Firmware crash dump\n");
3320                 else
3321                         dev_info(&instance->pdev->dev, "Firmware crash dump "
3322                                 "copied successfully\n");
3323         }
3324         return strlen(buf);
3325 }
3326
3327 static ssize_t
3328 fw_crash_state_show(struct device *cdev,
3329         struct device_attribute *attr, char *buf)
3330 {
3331         struct Scsi_Host *shost = class_to_shost(cdev);
3332         struct megasas_instance *instance =
3333                 (struct megasas_instance *) shost->hostdata;
3334
3335         return snprintf(buf, PAGE_SIZE, "%d\n", instance->fw_crash_state);
3336 }
3337
3338 static ssize_t
3339 page_size_show(struct device *cdev,
3340         struct device_attribute *attr, char *buf)
3341 {
3342         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)PAGE_SIZE - 1);
3343 }
3344
3345 static ssize_t
3346 ldio_outstanding_show(struct device *cdev, struct device_attribute *attr,
3347         char *buf)
3348 {
3349         struct Scsi_Host *shost = class_to_shost(cdev);
3350         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3351
3352         return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->ldio_outstanding));
3353 }
3354
3355 static ssize_t
3356 fw_cmds_outstanding_show(struct device *cdev,
3357                                  struct device_attribute *attr, char *buf)
3358 {
3359         struct Scsi_Host *shost = class_to_shost(cdev);
3360         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3361
3362         return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->fw_outstanding));
3363 }
3364
3365 static ssize_t
3366 enable_sdev_max_qd_show(struct device *cdev,
3367         struct device_attribute *attr, char *buf)
3368 {
3369         struct Scsi_Host *shost = class_to_shost(cdev);
3370         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3371
3372         return snprintf(buf, PAGE_SIZE, "%d\n", instance->enable_sdev_max_qd);
3373 }
3374
3375 static ssize_t
3376 enable_sdev_max_qd_store(struct device *cdev,
3377         struct device_attribute *attr, const char *buf, size_t count)
3378 {
3379         struct Scsi_Host *shost = class_to_shost(cdev);
3380         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3381         u32 val = 0;
3382         bool is_target_prop;
3383         int ret_target_prop = DCMD_FAILED;
3384         struct scsi_device *sdev;
3385
3386         if (kstrtou32(buf, 0, &val) != 0) {
3387                 pr_err("megasas: could not set enable_sdev_max_qd\n");
3388                 return -EINVAL;
3389         }
3390
3391         mutex_lock(&instance->reset_mutex);
3392         if (val)
3393                 instance->enable_sdev_max_qd = true;
3394         else
3395                 instance->enable_sdev_max_qd = false;
3396
3397         shost_for_each_device(sdev, shost) {
3398                 ret_target_prop = megasas_get_target_prop(instance, sdev);
3399                 is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false;
3400                 megasas_set_fw_assisted_qd(sdev, is_target_prop);
3401         }
3402         mutex_unlock(&instance->reset_mutex);
3403
3404         return strlen(buf);
3405 }
3406
3407 static ssize_t
3408 dump_system_regs_show(struct device *cdev,
3409                                struct device_attribute *attr, char *buf)
3410 {
3411         struct Scsi_Host *shost = class_to_shost(cdev);
3412         struct megasas_instance *instance =
3413                         (struct megasas_instance *)shost->hostdata;
3414
3415         return megasas_dump_sys_regs(instance->reg_set, buf);
3416 }
3417
3418 static ssize_t
3419 raid_map_id_show(struct device *cdev, struct device_attribute *attr,
3420                           char *buf)
3421 {
3422         struct Scsi_Host *shost = class_to_shost(cdev);
3423         struct megasas_instance *instance =
3424                         (struct megasas_instance *)shost->hostdata;
3425
3426         return snprintf(buf, PAGE_SIZE, "%ld\n",
3427                         (unsigned long)instance->map_id);
3428 }
3429
3430 static DEVICE_ATTR_RW(fw_crash_buffer);
3431 static DEVICE_ATTR_RO(fw_crash_buffer_size);
3432 static DEVICE_ATTR_RW(fw_crash_state);
3433 static DEVICE_ATTR_RO(page_size);
3434 static DEVICE_ATTR_RO(ldio_outstanding);
3435 static DEVICE_ATTR_RO(fw_cmds_outstanding);
3436 static DEVICE_ATTR_RW(enable_sdev_max_qd);
3437 static DEVICE_ATTR_RO(dump_system_regs);
3438 static DEVICE_ATTR_RO(raid_map_id);
3439
3440 static struct device_attribute *megaraid_host_attrs[] = {
3441         &dev_attr_fw_crash_buffer_size,
3442         &dev_attr_fw_crash_buffer,
3443         &dev_attr_fw_crash_state,
3444         &dev_attr_page_size,
3445         &dev_attr_ldio_outstanding,
3446         &dev_attr_fw_cmds_outstanding,
3447         &dev_attr_enable_sdev_max_qd,
3448         &dev_attr_dump_system_regs,
3449         &dev_attr_raid_map_id,
3450         NULL,
3451 };
3452
3453 /*
3454  * Scsi host template for megaraid_sas driver
3455  */
3456 static struct scsi_host_template megasas_template = {
3457
3458         .module = THIS_MODULE,
3459         .name = "Avago SAS based MegaRAID driver",
3460         .proc_name = "megaraid_sas",
3461         .slave_configure = megasas_slave_configure,
3462         .slave_alloc = megasas_slave_alloc,
3463         .slave_destroy = megasas_slave_destroy,
3464         .queuecommand = megasas_queue_command,
3465         .eh_target_reset_handler = megasas_reset_target,
3466         .eh_abort_handler = megasas_task_abort,
3467         .eh_host_reset_handler = megasas_reset_bus_host,
3468         .eh_timed_out = megasas_reset_timer,
3469         .shost_attrs = megaraid_host_attrs,
3470         .bios_param = megasas_bios_param,
3471         .change_queue_depth = scsi_change_queue_depth,
3472         .max_segment_size = 0xffffffff,
3473 };
3474
3475 /**
3476  * megasas_complete_int_cmd -   Completes an internal command
3477  * @instance:                   Adapter soft state
3478  * @cmd:                        Command to be completed
3479  *
3480  * The megasas_issue_blocked_cmd() function waits for a command to complete
3481  * after it issues a command. This function wakes up that waiting routine by
3482  * calling wake_up() on the wait queue.
3483  */
3484 static void
3485 megasas_complete_int_cmd(struct megasas_instance *instance,
3486                          struct megasas_cmd *cmd)
3487 {
3488         if (cmd->cmd_status_drv == DCMD_INIT)
3489                 cmd->cmd_status_drv =
3490                 (cmd->frame->io.cmd_status == MFI_STAT_OK) ?
3491                 DCMD_SUCCESS : DCMD_FAILED;
3492
3493         wake_up(&instance->int_cmd_wait_q);
3494 }
3495
3496 /**
3497  * megasas_complete_abort -     Completes aborting a command
3498  * @instance:                   Adapter soft state
3499  * @cmd:                        Cmd that was issued to abort another cmd
3500  *
3501  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
3502  * after it issues an abort on a previously issued command. This function
3503  * wakes up all functions waiting on the same wait queue.
3504  */
3505 static void
3506 megasas_complete_abort(struct megasas_instance *instance,
3507                        struct megasas_cmd *cmd)
3508 {
3509         if (cmd->sync_cmd) {
3510                 cmd->sync_cmd = 0;
3511                 cmd->cmd_status_drv = DCMD_SUCCESS;
3512                 wake_up(&instance->abort_cmd_wait_q);
3513         }
3514 }
3515
3516 static void
3517 megasas_set_ld_removed_by_fw(struct megasas_instance *instance)
3518 {
3519         uint i;
3520
3521         for (i = 0; (i < MEGASAS_MAX_LD_IDS); i++) {
3522                 if (instance->ld_ids_prev[i] != 0xff &&
3523                     instance->ld_ids_from_raidmap[i] == 0xff) {
3524                         if (megasas_dbg_lvl & LD_PD_DEBUG)
3525                                 dev_info(&instance->pdev->dev,
3526                                          "LD target ID %d removed from RAID map\n", i);
3527                         instance->ld_tgtid_status[i] = LD_TARGET_ID_DELETED;
3528                 }
3529         }
3530 }
3531
3532 /**
3533  * megasas_complete_cmd -       Completes a command
3534  * @instance:                   Adapter soft state
3535  * @cmd:                        Command to be completed
3536  * @alt_status:                 If non-zero, use this value as status to
3537  *                              SCSI mid-layer instead of the value returned
3538  *                              by the FW. This should be used if caller wants
3539  *                              an alternate status (as in the case of aborted
3540  *                              commands)
3541  */
3542 void
3543 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
3544                      u8 alt_status)
3545 {
3546         int exception = 0;
3547         struct megasas_header *hdr = &cmd->frame->hdr;
3548         unsigned long flags;
3549         struct fusion_context *fusion = instance->ctrl_context;
3550         u32 opcode, status;
3551
3552         /* flag for the retry reset */
3553         cmd->retry_for_fw_reset = 0;
3554
3555         if (cmd->scmd)
3556                 cmd->scmd->SCp.ptr = NULL;
3557
3558         switch (hdr->cmd) {
3559         case MFI_CMD_INVALID:
3560                 /* Some older 1068 controller FW may keep a pended
3561                    MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
3562                    when booting the kdump kernel.  Ignore this command to
3563                    prevent a kernel panic on shutdown of the kdump kernel. */
3564                 dev_warn(&instance->pdev->dev, "MFI_CMD_INVALID command "
3565                        "completed\n");
3566                 dev_warn(&instance->pdev->dev, "If you have a controller "
3567                        "other than PERC5, please upgrade your firmware\n");
3568                 break;
3569         case MFI_CMD_PD_SCSI_IO:
3570         case MFI_CMD_LD_SCSI_IO:
3571
3572                 /*
3573                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
3574                  * issued either through an IO path or an IOCTL path. If it
3575                  * was via IOCTL, we will send it to internal completion.
3576                  */
3577                 if (cmd->sync_cmd) {
3578                         cmd->sync_cmd = 0;
3579                         megasas_complete_int_cmd(instance, cmd);
3580                         break;
3581                 }
3582                 fallthrough;
3583
3584         case MFI_CMD_LD_READ:
3585         case MFI_CMD_LD_WRITE:
3586
3587                 if (alt_status) {
3588                         cmd->scmd->result = alt_status << 16;
3589                         exception = 1;
3590                 }
3591
3592                 if (exception) {
3593
3594                         atomic_dec(&instance->fw_outstanding);
3595
3596                         scsi_dma_unmap(cmd->scmd);
3597                         cmd->scmd->scsi_done(cmd->scmd);
3598                         megasas_return_cmd(instance, cmd);
3599
3600                         break;
3601                 }
3602
3603                 switch (hdr->cmd_status) {
3604
3605                 case MFI_STAT_OK:
3606                         cmd->scmd->result = DID_OK << 16;
3607                         break;
3608
3609                 case MFI_STAT_SCSI_IO_FAILED:
3610                 case MFI_STAT_LD_INIT_IN_PROGRESS:
3611                         cmd->scmd->result =
3612                             (DID_ERROR << 16) | hdr->scsi_status;
3613                         break;
3614
3615                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
3616
3617                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
3618
3619                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
3620                                 memset(cmd->scmd->sense_buffer, 0,
3621                                        SCSI_SENSE_BUFFERSIZE);
3622                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
3623                                        hdr->sense_len);
3624
3625                                 cmd->scmd->result |= DRIVER_SENSE << 24;
3626                         }
3627
3628                         break;
3629
3630                 case MFI_STAT_LD_OFFLINE:
3631                 case MFI_STAT_DEVICE_NOT_FOUND:
3632                         cmd->scmd->result = DID_BAD_TARGET << 16;
3633                         break;
3634
3635                 default:
3636                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "MFI FW status %#x\n",
3637                                hdr->cmd_status);
3638                         cmd->scmd->result = DID_ERROR << 16;
3639                         break;
3640                 }
3641
3642                 atomic_dec(&instance->fw_outstanding);
3643
3644                 scsi_dma_unmap(cmd->scmd);
3645                 cmd->scmd->scsi_done(cmd->scmd);
3646                 megasas_return_cmd(instance, cmd);
3647
3648                 break;
3649
3650         case MFI_CMD_SMP:
3651         case MFI_CMD_STP:
3652         case MFI_CMD_NVME:
3653         case MFI_CMD_TOOLBOX:
3654                 megasas_complete_int_cmd(instance, cmd);
3655                 break;
3656
3657         case MFI_CMD_DCMD:
3658                 opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
3659                 /* Check for LD map update */
3660                 if ((opcode == MR_DCMD_LD_MAP_GET_INFO)
3661                         && (cmd->frame->dcmd.mbox.b[1] == 1)) {
3662                         fusion->fast_path_io = 0;
3663                         spin_lock_irqsave(instance->host->host_lock, flags);
3664                         status = cmd->frame->hdr.cmd_status;
3665                         instance->map_update_cmd = NULL;
3666                         if (status != MFI_STAT_OK) {
3667                                 if (status != MFI_STAT_NOT_FOUND)
3668                                         dev_warn(&instance->pdev->dev, "map syncfailed, status = 0x%x\n",
3669                                                cmd->frame->hdr.cmd_status);
3670                                 else {
3671                                         megasas_return_cmd(instance, cmd);
3672                                         spin_unlock_irqrestore(
3673                                                 instance->host->host_lock,
3674                                                 flags);
3675                                         break;
3676                                 }
3677                         }
3678
3679                         megasas_return_cmd(instance, cmd);
3680
3681                         /*
3682                          * Set fast path IO to ZERO.
3683                          * Validate Map will set proper value.
3684                          * Meanwhile all IOs will go as LD IO.
3685                          */
3686                         if (status == MFI_STAT_OK &&
3687                             (MR_ValidateMapInfo(instance, (instance->map_id + 1)))) {
3688                                 instance->map_id++;
3689                                 fusion->fast_path_io = 1;
3690                         } else {
3691                                 fusion->fast_path_io = 0;
3692                         }
3693
3694                         if (instance->adapter_type >= INVADER_SERIES)
3695                                 megasas_set_ld_removed_by_fw(instance);
3696
3697                         megasas_sync_map_info(instance);
3698                         spin_unlock_irqrestore(instance->host->host_lock,
3699                                                flags);
3700
3701                         break;
3702                 }
3703                 if (opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
3704                     opcode == MR_DCMD_CTRL_EVENT_GET) {
3705                         spin_lock_irqsave(&poll_aen_lock, flags);
3706                         megasas_poll_wait_aen = 0;
3707                         spin_unlock_irqrestore(&poll_aen_lock, flags);
3708                 }
3709
3710                 /* FW has an updated PD sequence */
3711                 if ((opcode == MR_DCMD_SYSTEM_PD_MAP_GET_INFO) &&
3712                         (cmd->frame->dcmd.mbox.b[0] == 1)) {
3713
3714                         spin_lock_irqsave(instance->host->host_lock, flags);
3715                         status = cmd->frame->hdr.cmd_status;
3716                         instance->jbod_seq_cmd = NULL;
3717                         megasas_return_cmd(instance, cmd);
3718
3719                         if (status == MFI_STAT_OK) {
3720                                 instance->pd_seq_map_id++;
3721                                 /* Re-register a pd sync seq num cmd */
3722                                 if (megasas_sync_pd_seq_num(instance, true))
3723                                         instance->use_seqnum_jbod_fp = false;
3724                         } else
3725                                 instance->use_seqnum_jbod_fp = false;
3726
3727                         spin_unlock_irqrestore(instance->host->host_lock, flags);
3728                         break;
3729                 }
3730
3731                 /*
3732                  * See if got an event notification
3733                  */
3734                 if (opcode == MR_DCMD_CTRL_EVENT_WAIT)
3735                         megasas_service_aen(instance, cmd);
3736                 else
3737                         megasas_complete_int_cmd(instance, cmd);
3738
3739                 break;
3740
3741         case MFI_CMD_ABORT:
3742                 /*
3743                  * Cmd issued to abort another cmd returned
3744                  */
3745                 megasas_complete_abort(instance, cmd);
3746                 break;
3747
3748         default:
3749                 dev_info(&instance->pdev->dev, "Unknown command completed! [0x%X]\n",
3750                        hdr->cmd);
3751                 megasas_complete_int_cmd(instance, cmd);
3752                 break;
3753         }
3754 }
3755
3756 /**
3757  * megasas_issue_pending_cmds_again -   issue all pending cmds
3758  *                                      in FW again because of the fw reset
3759  * @instance:                           Adapter soft state
3760  */
3761 static inline void
3762 megasas_issue_pending_cmds_again(struct megasas_instance *instance)
3763 {
3764         struct megasas_cmd *cmd;
3765         struct list_head clist_local;
3766         union megasas_evt_class_locale class_locale;
3767         unsigned long flags;
3768         u32 seq_num;
3769
3770         INIT_LIST_HEAD(&clist_local);
3771         spin_lock_irqsave(&instance->hba_lock, flags);
3772         list_splice_init(&instance->internal_reset_pending_q, &clist_local);
3773         spin_unlock_irqrestore(&instance->hba_lock, flags);
3774
3775         while (!list_empty(&clist_local)) {
3776                 cmd = list_entry((&clist_local)->next,
3777                                         struct megasas_cmd, list);
3778                 list_del_init(&cmd->list);
3779
3780                 if (cmd->sync_cmd || cmd->scmd) {
3781                         dev_notice(&instance->pdev->dev, "command %p, %p:%d"
3782                                 "detected to be pending while HBA reset\n",
3783                                         cmd, cmd->scmd, cmd->sync_cmd);
3784
3785                         cmd->retry_for_fw_reset++;
3786
3787                         if (cmd->retry_for_fw_reset == 3) {
3788                                 dev_notice(&instance->pdev->dev, "cmd %p, %p:%d"
3789                                         "was tried multiple times during reset."
3790                                         "Shutting down the HBA\n",
3791                                         cmd, cmd->scmd, cmd->sync_cmd);
3792                                 instance->instancet->disable_intr(instance);
3793                                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3794                                 megaraid_sas_kill_hba(instance);
3795                                 return;
3796                         }
3797                 }
3798
3799                 if (cmd->sync_cmd == 1) {
3800                         if (cmd->scmd) {
3801                                 dev_notice(&instance->pdev->dev, "unexpected"
3802                                         "cmd attached to internal command!\n");
3803                         }
3804                         dev_notice(&instance->pdev->dev, "%p synchronous cmd"
3805                                                 "on the internal reset queue,"
3806                                                 "issue it again.\n", cmd);
3807                         cmd->cmd_status_drv = DCMD_INIT;
3808                         instance->instancet->fire_cmd(instance,
3809                                                         cmd->frame_phys_addr,
3810                                                         0, instance->reg_set);
3811                 } else if (cmd->scmd) {
3812                         dev_notice(&instance->pdev->dev, "%p scsi cmd [%02x]"
3813                         "detected on the internal queue, issue again.\n",
3814                         cmd, cmd->scmd->cmnd[0]);
3815
3816                         atomic_inc(&instance->fw_outstanding);
3817                         instance->instancet->fire_cmd(instance,
3818                                         cmd->frame_phys_addr,
3819                                         cmd->frame_count-1, instance->reg_set);
3820                 } else {
3821                         dev_notice(&instance->pdev->dev, "%p unexpected cmd on the"
3822                                 "internal reset defer list while re-issue!!\n",
3823                                 cmd);
3824                 }
3825         }
3826
3827         if (instance->aen_cmd) {
3828                 dev_notice(&instance->pdev->dev, "aen_cmd in def process\n");
3829                 megasas_return_cmd(instance, instance->aen_cmd);
3830
3831                 instance->aen_cmd = NULL;
3832         }
3833
3834         /*
3835          * Initiate AEN (Asynchronous Event Notification)
3836          */
3837         seq_num = instance->last_seq_num;
3838         class_locale.members.reserved = 0;
3839         class_locale.members.locale = MR_EVT_LOCALE_ALL;
3840         class_locale.members.class = MR_EVT_CLASS_DEBUG;
3841
3842         megasas_register_aen(instance, seq_num, class_locale.word);
3843 }
3844
3845 /*
3846  * Move the internal reset pending commands to a deferred queue.
3847  *
3848  * We move the commands pending at internal reset time to a
3849  * pending queue. This queue would be flushed after successful
3850  * completion of the internal reset sequence. if the internal reset
3851  * did not complete in time, the kernel reset handler would flush
3852  * these commands.
3853  */
3854 static void
3855 megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
3856 {
3857         struct megasas_cmd *cmd;
3858         int i;
3859         u16 max_cmd = instance->max_fw_cmds;
3860         u32 defer_index;
3861         unsigned long flags;
3862
3863         defer_index = 0;
3864         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
3865         for (i = 0; i < max_cmd; i++) {
3866                 cmd = instance->cmd_list[i];
3867                 if (cmd->sync_cmd == 1 || cmd->scmd) {
3868                         dev_notice(&instance->pdev->dev, "moving cmd[%d]:%p:%d:%p"
3869                                         "on the defer queue as internal\n",
3870                                 defer_index, cmd, cmd->sync_cmd, cmd->scmd);
3871
3872                         if (!list_empty(&cmd->list)) {
3873                                 dev_notice(&instance->pdev->dev, "ERROR while"
3874                                         " moving this cmd:%p, %d %p, it was"
3875                                         "discovered on some list?\n",
3876                                         cmd, cmd->sync_cmd, cmd->scmd);
3877
3878                                 list_del_init(&cmd->list);
3879                         }
3880                         defer_index++;
3881                         list_add_tail(&cmd->list,
3882                                 &instance->internal_reset_pending_q);
3883                 }
3884         }
3885         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
3886 }
3887
3888
3889 static void
3890 process_fw_state_change_wq(struct work_struct *work)
3891 {
3892         struct megasas_instance *instance =
3893                 container_of(work, struct megasas_instance, work_init);
3894         u32 wait;
3895         unsigned long flags;
3896
3897     if (atomic_read(&instance->adprecovery) != MEGASAS_ADPRESET_SM_INFAULT) {
3898                 dev_notice(&instance->pdev->dev, "error, recovery st %x\n",
3899                                 atomic_read(&instance->adprecovery));
3900                 return ;
3901         }
3902
3903         if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) {
3904                 dev_notice(&instance->pdev->dev, "FW detected to be in fault"
3905                                         "state, restarting it...\n");
3906
3907                 instance->instancet->disable_intr(instance);
3908                 atomic_set(&instance->fw_outstanding, 0);
3909
3910                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3911                 instance->instancet->adp_reset(instance, instance->reg_set);
3912                 atomic_set(&instance->fw_reset_no_pci_access, 0);
3913
3914                 dev_notice(&instance->pdev->dev, "FW restarted successfully,"
3915                                         "initiating next stage...\n");
3916
3917                 dev_notice(&instance->pdev->dev, "HBA recovery state machine,"
3918                                         "state 2 starting...\n");
3919
3920                 /* waiting for about 20 second before start the second init */
3921                 for (wait = 0; wait < 30; wait++) {
3922                         msleep(1000);
3923                 }
3924
3925                 if (megasas_transition_to_ready(instance, 1)) {
3926                         dev_notice(&instance->pdev->dev, "adapter not ready\n");
3927
3928                         atomic_set(&instance->fw_reset_no_pci_access, 1);
3929                         megaraid_sas_kill_hba(instance);
3930                         return ;
3931                 }
3932
3933                 if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
3934                         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
3935                         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
3936                         ) {
3937                         *instance->consumer = *instance->producer;
3938                 } else {
3939                         *instance->consumer = 0;
3940                         *instance->producer = 0;
3941                 }
3942
3943                 megasas_issue_init_mfi(instance);
3944
3945                 spin_lock_irqsave(&instance->hba_lock, flags);
3946                 atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
3947                 spin_unlock_irqrestore(&instance->hba_lock, flags);
3948                 instance->instancet->enable_intr(instance);
3949
3950                 megasas_issue_pending_cmds_again(instance);
3951                 instance->issuepend_done = 1;
3952         }
3953 }
3954
3955 /**
3956  * megasas_deplete_reply_queue -        Processes all completed commands
3957  * @instance:                           Adapter soft state
3958  * @alt_status:                         Alternate status to be returned to
3959  *                                      SCSI mid-layer instead of the status
3960  *                                      returned by the FW
3961  * Note: this must be called with hba lock held
3962  */
3963 static int
3964 megasas_deplete_reply_queue(struct megasas_instance *instance,
3965                                         u8 alt_status)
3966 {
3967         u32 mfiStatus;
3968         u32 fw_state;
3969
3970         if ((mfiStatus = instance->instancet->check_reset(instance,
3971                                         instance->reg_set)) == 1) {
3972                 return IRQ_HANDLED;
3973         }
3974
3975         mfiStatus = instance->instancet->clear_intr(instance);
3976         if (mfiStatus == 0) {
3977                 /* Hardware may not set outbound_intr_status in MSI-X mode */
3978                 if (!instance->msix_vectors)
3979                         return IRQ_NONE;
3980         }
3981
3982         instance->mfiStatus = mfiStatus;
3983
3984         if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
3985                 fw_state = instance->instancet->read_fw_status_reg(
3986                                 instance) & MFI_STATE_MASK;
3987
3988                 if (fw_state != MFI_STATE_FAULT) {
3989                         dev_notice(&instance->pdev->dev, "fw state:%x\n",
3990                                                 fw_state);
3991                 }
3992
3993                 if ((fw_state == MFI_STATE_FAULT) &&
3994                                 (instance->disableOnlineCtrlReset == 0)) {
3995                         dev_notice(&instance->pdev->dev, "wait adp restart\n");
3996
3997                         if ((instance->pdev->device ==
3998                                         PCI_DEVICE_ID_LSI_SAS1064R) ||
3999                                 (instance->pdev->device ==
4000                                         PCI_DEVICE_ID_DELL_PERC5) ||
4001                                 (instance->pdev->device ==
4002                                         PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
4003
4004                                 *instance->consumer =
4005                                         cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
4006                         }
4007
4008
4009                         instance->instancet->disable_intr(instance);
4010                         atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
4011                         instance->issuepend_done = 0;
4012
4013                         atomic_set(&instance->fw_outstanding, 0);
4014                         megasas_internal_reset_defer_cmds(instance);
4015
4016                         dev_notice(&instance->pdev->dev, "fwState=%x, stage:%d\n",
4017                                         fw_state, atomic_read(&instance->adprecovery));
4018
4019                         schedule_work(&instance->work_init);
4020                         return IRQ_HANDLED;
4021
4022                 } else {
4023                         dev_notice(&instance->pdev->dev, "fwstate:%x, dis_OCR=%x\n",
4024                                 fw_state, instance->disableOnlineCtrlReset);
4025                 }
4026         }
4027
4028         tasklet_schedule(&instance->isr_tasklet);
4029         return IRQ_HANDLED;
4030 }
4031
4032 /**
4033  * megasas_isr - isr entry point
4034  * @irq:        IRQ number
4035  * @devp:       IRQ context address
4036  */
4037 static irqreturn_t megasas_isr(int irq, void *devp)
4038 {
4039         struct megasas_irq_context *irq_context = devp;
4040         struct megasas_instance *instance = irq_context->instance;
4041         unsigned long flags;
4042         irqreturn_t rc;
4043
4044         if (atomic_read(&instance->fw_reset_no_pci_access))
4045                 return IRQ_HANDLED;
4046
4047         spin_lock_irqsave(&instance->hba_lock, flags);
4048         rc = megasas_deplete_reply_queue(instance, DID_OK);
4049         spin_unlock_irqrestore(&instance->hba_lock, flags);
4050
4051         return rc;
4052 }
4053
4054 /**
4055  * megasas_transition_to_ready -        Move the FW to READY state
4056  * @instance:                           Adapter soft state
4057  * @ocr:                                Adapter reset state
4058  *
4059  * During the initialization, FW passes can potentially be in any one of
4060  * several possible states. If the FW in operational, waiting-for-handshake
4061  * states, driver must take steps to bring it to ready state. Otherwise, it
4062  * has to wait for the ready state.
4063  */
4064 int
4065 megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
4066 {
4067         int i;
4068         u8 max_wait;
4069         u32 fw_state;
4070         u32 abs_state, curr_abs_state;
4071
4072         abs_state = instance->instancet->read_fw_status_reg(instance);
4073         fw_state = abs_state & MFI_STATE_MASK;
4074
4075         if (fw_state != MFI_STATE_READY)
4076                 dev_info(&instance->pdev->dev, "Waiting for FW to come to ready"
4077                        " state\n");
4078
4079         while (fw_state != MFI_STATE_READY) {
4080
4081                 switch (fw_state) {
4082
4083                 case MFI_STATE_FAULT:
4084                         dev_printk(KERN_ERR, &instance->pdev->dev,
4085                                    "FW in FAULT state, Fault code:0x%x subcode:0x%x func:%s\n",
4086                                    abs_state & MFI_STATE_FAULT_CODE,
4087                                    abs_state & MFI_STATE_FAULT_SUBCODE, __func__);
4088                         if (ocr) {
4089                                 max_wait = MEGASAS_RESET_WAIT_TIME;
4090                                 break;
4091                         } else {
4092                                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4093                                 megasas_dump_reg_set(instance->reg_set);
4094                                 return -ENODEV;
4095                         }
4096
4097                 case MFI_STATE_WAIT_HANDSHAKE:
4098                         /*
4099                          * Set the CLR bit in inbound doorbell
4100                          */
4101                         if ((instance->pdev->device ==
4102                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4103                                 (instance->pdev->device ==
4104                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
4105                                 (instance->adapter_type != MFI_SERIES))
4106                                 writel(
4107                                   MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
4108                                   &instance->reg_set->doorbell);
4109                         else
4110                                 writel(
4111                                     MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
4112                                         &instance->reg_set->inbound_doorbell);
4113
4114                         max_wait = MEGASAS_RESET_WAIT_TIME;
4115                         break;
4116
4117                 case MFI_STATE_BOOT_MESSAGE_PENDING:
4118                         if ((instance->pdev->device ==
4119                              PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4120                                 (instance->pdev->device ==
4121                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
4122                                 (instance->adapter_type != MFI_SERIES))
4123                                 writel(MFI_INIT_HOTPLUG,
4124                                        &instance->reg_set->doorbell);
4125                         else
4126                                 writel(MFI_INIT_HOTPLUG,
4127                                         &instance->reg_set->inbound_doorbell);
4128
4129                         max_wait = MEGASAS_RESET_WAIT_TIME;
4130                         break;
4131
4132                 case MFI_STATE_OPERATIONAL:
4133                         /*
4134                          * Bring it to READY state; assuming max wait 10 secs
4135                          */
4136                         instance->instancet->disable_intr(instance);
4137                         if ((instance->pdev->device ==
4138                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4139                                 (instance->pdev->device ==
4140                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)  ||
4141                                 (instance->adapter_type != MFI_SERIES)) {
4142                                 writel(MFI_RESET_FLAGS,
4143                                         &instance->reg_set->doorbell);
4144
4145                                 if (instance->adapter_type != MFI_SERIES) {
4146                                         for (i = 0; i < (10 * 1000); i += 20) {
4147                                                 if (megasas_readl(
4148                                                             instance,
4149                                                             &instance->
4150                                                             reg_set->
4151                                                             doorbell) & 1)
4152                                                         msleep(20);
4153                                                 else
4154                                                         break;
4155                                         }
4156                                 }
4157                         } else
4158                                 writel(MFI_RESET_FLAGS,
4159                                         &instance->reg_set->inbound_doorbell);
4160
4161                         max_wait = MEGASAS_RESET_WAIT_TIME;
4162                         break;
4163
4164                 case MFI_STATE_UNDEFINED:
4165                         /*
4166                          * This state should not last for more than 2 seconds
4167                          */
4168                         max_wait = MEGASAS_RESET_WAIT_TIME;
4169                         break;
4170
4171                 case MFI_STATE_BB_INIT:
4172                         max_wait = MEGASAS_RESET_WAIT_TIME;
4173                         break;
4174
4175                 case MFI_STATE_FW_INIT:
4176                         max_wait = MEGASAS_RESET_WAIT_TIME;
4177                         break;
4178
4179                 case MFI_STATE_FW_INIT_2:
4180                         max_wait = MEGASAS_RESET_WAIT_TIME;
4181                         break;
4182
4183                 case MFI_STATE_DEVICE_SCAN:
4184                         max_wait = MEGASAS_RESET_WAIT_TIME;
4185                         break;
4186
4187                 case MFI_STATE_FLUSH_CACHE:
4188                         max_wait = MEGASAS_RESET_WAIT_TIME;
4189                         break;
4190
4191                 default:
4192                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "Unknown state 0x%x\n",
4193                                fw_state);
4194                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4195                         megasas_dump_reg_set(instance->reg_set);
4196                         return -ENODEV;
4197                 }
4198
4199                 /*
4200                  * The cur_state should not last for more than max_wait secs
4201                  */
4202                 for (i = 0; i < max_wait * 50; i++) {
4203                         curr_abs_state = instance->instancet->
4204                                 read_fw_status_reg(instance);
4205
4206                         if (abs_state == curr_abs_state) {
4207                                 msleep(20);
4208                         } else
4209                                 break;
4210                 }
4211
4212                 /*
4213                  * Return error if fw_state hasn't changed after max_wait
4214                  */
4215                 if (curr_abs_state == abs_state) {
4216                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "FW state [%d] hasn't changed "
4217                                "in %d secs\n", fw_state, max_wait);
4218                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4219                         megasas_dump_reg_set(instance->reg_set);
4220                         return -ENODEV;
4221                 }
4222
4223                 abs_state = curr_abs_state;
4224                 fw_state = curr_abs_state & MFI_STATE_MASK;
4225         }
4226         dev_info(&instance->pdev->dev, "FW now in Ready state\n");
4227
4228         return 0;
4229 }
4230
4231 /**
4232  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
4233  * @instance:                           Adapter soft state
4234  */
4235 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
4236 {
4237         int i;
4238         u16 max_cmd = instance->max_mfi_cmds;
4239         struct megasas_cmd *cmd;
4240
4241         if (!instance->frame_dma_pool)
4242                 return;
4243
4244         /*
4245          * Return all frames to pool
4246          */
4247         for (i = 0; i < max_cmd; i++) {
4248
4249                 cmd = instance->cmd_list[i];
4250
4251                 if (cmd->frame)
4252                         dma_pool_free(instance->frame_dma_pool, cmd->frame,
4253                                       cmd->frame_phys_addr);
4254
4255                 if (cmd->sense)
4256                         dma_pool_free(instance->sense_dma_pool, cmd->sense,
4257                                       cmd->sense_phys_addr);
4258         }
4259
4260         /*
4261          * Now destroy the pool itself
4262          */
4263         dma_pool_destroy(instance->frame_dma_pool);
4264         dma_pool_destroy(instance->sense_dma_pool);
4265
4266         instance->frame_dma_pool = NULL;
4267         instance->sense_dma_pool = NULL;
4268 }
4269
4270 /**
4271  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
4272  * @instance:                   Adapter soft state
4273  *
4274  * Each command packet has an embedded DMA memory buffer that is used for
4275  * filling MFI frame and the SG list that immediately follows the frame. This
4276  * function creates those DMA memory buffers for each command packet by using
4277  * PCI pool facility.
4278  */
4279 static int megasas_create_frame_pool(struct megasas_instance *instance)
4280 {
4281         int i;
4282         u16 max_cmd;
4283         u32 frame_count;
4284         struct megasas_cmd *cmd;
4285
4286         max_cmd = instance->max_mfi_cmds;
4287
4288         /*
4289          * For MFI controllers.
4290          * max_num_sge = 60
4291          * max_sge_sz  = 16 byte (sizeof megasas_sge_skinny)
4292          * Total 960 byte (15 MFI frame of 64 byte)
4293          *
4294          * Fusion adapter require only 3 extra frame.
4295          * max_num_sge = 16 (defined as MAX_IOCTL_SGE)
4296          * max_sge_sz  = 12 byte (sizeof  megasas_sge64)
4297          * Total 192 byte (3 MFI frame of 64 byte)
4298          */
4299         frame_count = (instance->adapter_type == MFI_SERIES) ?
4300                         (15 + 1) : (3 + 1);
4301         instance->mfi_frame_size = MEGAMFI_FRAME_SIZE * frame_count;
4302         /*
4303          * Use DMA pool facility provided by PCI layer
4304          */
4305         instance->frame_dma_pool = dma_pool_create("megasas frame pool",
4306                                         &instance->pdev->dev,
4307                                         instance->mfi_frame_size, 256, 0);
4308
4309         if (!instance->frame_dma_pool) {
4310                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup frame pool\n");
4311                 return -ENOMEM;
4312         }
4313
4314         instance->sense_dma_pool = dma_pool_create("megasas sense pool",
4315                                                    &instance->pdev->dev, 128,
4316                                                    4, 0);
4317
4318         if (!instance->sense_dma_pool) {
4319                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup sense pool\n");
4320
4321                 dma_pool_destroy(instance->frame_dma_pool);
4322                 instance->frame_dma_pool = NULL;
4323
4324                 return -ENOMEM;
4325         }
4326
4327         /*
4328          * Allocate and attach a frame to each of the commands in cmd_list.
4329          * By making cmd->index as the context instead of the &cmd, we can
4330          * always use 32bit context regardless of the architecture
4331          */
4332         for (i = 0; i < max_cmd; i++) {
4333
4334                 cmd = instance->cmd_list[i];
4335
4336                 cmd->frame = dma_pool_zalloc(instance->frame_dma_pool,
4337                                             GFP_KERNEL, &cmd->frame_phys_addr);
4338
4339                 cmd->sense = dma_pool_alloc(instance->sense_dma_pool,
4340                                             GFP_KERNEL, &cmd->sense_phys_addr);
4341
4342                 /*
4343                  * megasas_teardown_frame_pool() takes care of freeing
4344                  * whatever has been allocated
4345                  */
4346                 if (!cmd->frame || !cmd->sense) {
4347                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "dma_pool_alloc failed\n");
4348                         megasas_teardown_frame_pool(instance);
4349                         return -ENOMEM;
4350                 }
4351
4352                 cmd->frame->io.context = cpu_to_le32(cmd->index);
4353                 cmd->frame->io.pad_0 = 0;
4354                 if ((instance->adapter_type == MFI_SERIES) && reset_devices)
4355                         cmd->frame->hdr.cmd = MFI_CMD_INVALID;
4356         }
4357
4358         return 0;
4359 }
4360
4361 /**
4362  * megasas_free_cmds -  Free all the cmds in the free cmd pool
4363  * @instance:           Adapter soft state
4364  */
4365 void megasas_free_cmds(struct megasas_instance *instance)
4366 {
4367         int i;
4368
4369         /* First free the MFI frame pool */
4370         megasas_teardown_frame_pool(instance);
4371
4372         /* Free all the commands in the cmd_list */
4373         for (i = 0; i < instance->max_mfi_cmds; i++)
4374
4375                 kfree(instance->cmd_list[i]);
4376
4377         /* Free the cmd_list buffer itself */
4378         kfree(instance->cmd_list);
4379         instance->cmd_list = NULL;
4380
4381         INIT_LIST_HEAD(&instance->cmd_pool);
4382 }
4383
4384 /**
4385  * megasas_alloc_cmds - Allocates the command packets
4386  * @instance:           Adapter soft state
4387  *
4388  * Each command that is issued to the FW, whether IO commands from the OS or
4389  * internal commands like IOCTLs, are wrapped in local data structure called
4390  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
4391  * the FW.
4392  *
4393  * Each frame has a 32-bit field called context (tag). This context is used
4394  * to get back the megasas_cmd from the frame when a frame gets completed in
4395  * the ISR. Typically the address of the megasas_cmd itself would be used as
4396  * the context. But we wanted to keep the differences between 32 and 64 bit
4397  * systems to the mininum. We always use 32 bit integers for the context. In
4398  * this driver, the 32 bit values are the indices into an array cmd_list.
4399  * This array is used only to look up the megasas_cmd given the context. The
4400  * free commands themselves are maintained in a linked list called cmd_pool.
4401  */
4402 int megasas_alloc_cmds(struct megasas_instance *instance)
4403 {
4404         int i;
4405         int j;
4406         u16 max_cmd;
4407         struct megasas_cmd *cmd;
4408
4409         max_cmd = instance->max_mfi_cmds;
4410
4411         /*
4412          * instance->cmd_list is an array of struct megasas_cmd pointers.
4413          * Allocate the dynamic array first and then allocate individual
4414          * commands.
4415          */
4416         instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
4417
4418         if (!instance->cmd_list) {
4419                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
4420                 return -ENOMEM;
4421         }
4422
4423         memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
4424
4425         for (i = 0; i < max_cmd; i++) {
4426                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
4427                                                 GFP_KERNEL);
4428
4429                 if (!instance->cmd_list[i]) {
4430
4431                         for (j = 0; j < i; j++)
4432                                 kfree(instance->cmd_list[j]);
4433
4434                         kfree(instance->cmd_list);
4435                         instance->cmd_list = NULL;
4436
4437                         return -ENOMEM;
4438                 }
4439         }
4440
4441         for (i = 0; i < max_cmd; i++) {
4442                 cmd = instance->cmd_list[i];
4443                 memset(cmd, 0, sizeof(struct megasas_cmd));
4444                 cmd->index = i;
4445                 cmd->scmd = NULL;
4446                 cmd->instance = instance;
4447
4448                 list_add_tail(&cmd->list, &instance->cmd_pool);
4449         }
4450
4451         /*
4452          * Create a frame pool and assign one frame to each cmd
4453          */
4454         if (megasas_create_frame_pool(instance)) {
4455                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
4456                 megasas_free_cmds(instance);
4457                 return -ENOMEM;
4458         }
4459
4460         return 0;
4461 }
4462
4463 /*
4464  * dcmd_timeout_ocr_possible -  Check if OCR is possible based on Driver/FW state.
4465  * @instance:                           Adapter soft state
4466  *
4467  * Return 0 for only Fusion adapter, if driver load/unload is not in progress
4468  * or FW is not under OCR.
4469  */
4470 inline int
4471 dcmd_timeout_ocr_possible(struct megasas_instance *instance) {
4472
4473         if (instance->adapter_type == MFI_SERIES)
4474                 return KILL_ADAPTER;
4475         else if (instance->unload ||
4476                         test_bit(MEGASAS_FUSION_OCR_NOT_POSSIBLE,
4477                                  &instance->reset_flags))
4478                 return IGNORE_TIMEOUT;
4479         else
4480                 return INITIATE_OCR;
4481 }
4482
4483 static void
4484 megasas_get_pd_info(struct megasas_instance *instance, struct scsi_device *sdev)
4485 {
4486         int ret;
4487         struct megasas_cmd *cmd;
4488         struct megasas_dcmd_frame *dcmd;
4489
4490         struct MR_PRIV_DEVICE *mr_device_priv_data;
4491         u16 device_id = 0;
4492
4493         device_id = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id;
4494         cmd = megasas_get_cmd(instance);
4495
4496         if (!cmd) {
4497                 dev_err(&instance->pdev->dev, "Failed to get cmd %s\n", __func__);
4498                 return;
4499         }
4500
4501         dcmd = &cmd->frame->dcmd;
4502
4503         memset(instance->pd_info, 0, sizeof(*instance->pd_info));
4504         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4505
4506         dcmd->mbox.s[0] = cpu_to_le16(device_id);
4507         dcmd->cmd = MFI_CMD_DCMD;
4508         dcmd->cmd_status = 0xFF;
4509         dcmd->sge_count = 1;
4510         dcmd->flags = MFI_FRAME_DIR_READ;
4511         dcmd->timeout = 0;
4512         dcmd->pad_0 = 0;
4513         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_PD_INFO));
4514         dcmd->opcode = cpu_to_le32(MR_DCMD_PD_GET_INFO);
4515
4516         megasas_set_dma_settings(instance, dcmd, instance->pd_info_h,
4517                                  sizeof(struct MR_PD_INFO));
4518
4519         if ((instance->adapter_type != MFI_SERIES) &&
4520             !instance->mask_interrupts)
4521                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4522         else
4523                 ret = megasas_issue_polled(instance, cmd);
4524
4525         switch (ret) {
4526         case DCMD_SUCCESS:
4527                 mr_device_priv_data = sdev->hostdata;
4528                 le16_to_cpus((u16 *)&instance->pd_info->state.ddf.pdType);
4529                 mr_device_priv_data->interface_type =
4530                                 instance->pd_info->state.ddf.pdType.intf;
4531                 break;
4532
4533         case DCMD_TIMEOUT:
4534
4535                 switch (dcmd_timeout_ocr_possible(instance)) {
4536                 case INITIATE_OCR:
4537                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4538                         mutex_unlock(&instance->reset_mutex);
4539                         megasas_reset_fusion(instance->host,
4540                                 MFI_IO_TIMEOUT_OCR);
4541                         mutex_lock(&instance->reset_mutex);
4542                         break;
4543                 case KILL_ADAPTER:
4544                         megaraid_sas_kill_hba(instance);
4545                         break;
4546                 case IGNORE_TIMEOUT:
4547                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4548                                 __func__, __LINE__);
4549                         break;
4550                 }
4551
4552                 break;
4553         }
4554
4555         if (ret != DCMD_TIMEOUT)
4556                 megasas_return_cmd(instance, cmd);
4557
4558         return;
4559 }
4560 /*
4561  * megasas_get_pd_list_info -   Returns FW's pd_list structure
4562  * @instance:                           Adapter soft state
4563  * @pd_list:                            pd_list structure
4564  *
4565  * Issues an internal command (DCMD) to get the FW's controller PD
4566  * list structure.  This information is mainly used to find out SYSTEM
4567  * supported by the FW.
4568  */
4569 static int
4570 megasas_get_pd_list(struct megasas_instance *instance)
4571 {
4572         int ret = 0, pd_index = 0;
4573         struct megasas_cmd *cmd;
4574         struct megasas_dcmd_frame *dcmd;
4575         struct MR_PD_LIST *ci;
4576         struct MR_PD_ADDRESS *pd_addr;
4577
4578         if (instance->pd_list_not_supported) {
4579                 dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4580                 "not supported by firmware\n");
4581                 return ret;
4582         }
4583
4584         ci = instance->pd_list_buf;
4585
4586         cmd = megasas_get_cmd(instance);
4587
4588         if (!cmd) {
4589                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "(get_pd_list): Failed to get cmd\n");
4590                 return -ENOMEM;
4591         }
4592
4593         dcmd = &cmd->frame->dcmd;
4594
4595         memset(ci, 0, sizeof(*ci));
4596         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4597
4598         dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
4599         dcmd->mbox.b[1] = 0;
4600         dcmd->cmd = MFI_CMD_DCMD;
4601         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4602         dcmd->sge_count = 1;
4603         dcmd->flags = MFI_FRAME_DIR_READ;
4604         dcmd->timeout = 0;
4605         dcmd->pad_0 = 0;
4606         dcmd->data_xfer_len = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
4607         dcmd->opcode = cpu_to_le32(MR_DCMD_PD_LIST_QUERY);
4608
4609         megasas_set_dma_settings(instance, dcmd, instance->pd_list_buf_h,
4610                                  (MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST)));
4611
4612         if ((instance->adapter_type != MFI_SERIES) &&
4613             !instance->mask_interrupts)
4614                 ret = megasas_issue_blocked_cmd(instance, cmd,
4615                         MFI_IO_TIMEOUT_SECS);
4616         else
4617                 ret = megasas_issue_polled(instance, cmd);
4618
4619         switch (ret) {
4620         case DCMD_FAILED:
4621                 dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4622                         "failed/not supported by firmware\n");
4623
4624                 if (instance->adapter_type != MFI_SERIES)
4625                         megaraid_sas_kill_hba(instance);
4626                 else
4627                         instance->pd_list_not_supported = 1;
4628                 break;
4629         case DCMD_TIMEOUT:
4630
4631                 switch (dcmd_timeout_ocr_possible(instance)) {
4632                 case INITIATE_OCR:
4633                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4634                         /*
4635                          * DCMD failed from AEN path.
4636                          * AEN path already hold reset_mutex to avoid PCI access
4637                          * while OCR is in progress.
4638                          */
4639                         mutex_unlock(&instance->reset_mutex);
4640                         megasas_reset_fusion(instance->host,
4641                                                 MFI_IO_TIMEOUT_OCR);
4642                         mutex_lock(&instance->reset_mutex);
4643                         break;
4644                 case KILL_ADAPTER:
4645                         megaraid_sas_kill_hba(instance);
4646                         break;
4647                 case IGNORE_TIMEOUT:
4648                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d \n",
4649                                 __func__, __LINE__);
4650                         break;
4651                 }
4652
4653                 break;
4654
4655         case DCMD_SUCCESS:
4656                 pd_addr = ci->addr;
4657                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4658                         dev_info(&instance->pdev->dev, "%s, sysPD count: 0x%x\n",
4659                                  __func__, le32_to_cpu(ci->count));
4660
4661                 if ((le32_to_cpu(ci->count) >
4662                         (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL)))
4663                         break;
4664
4665                 memset(instance->local_pd_list, 0,
4666                                 MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
4667
4668                 for (pd_index = 0; pd_index < le32_to_cpu(ci->count); pd_index++) {
4669                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].tid     =
4670                                         le16_to_cpu(pd_addr->deviceId);
4671                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveType       =
4672                                         pd_addr->scsiDevType;
4673                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveState      =
4674                                         MR_PD_STATE_SYSTEM;
4675                         if (megasas_dbg_lvl & LD_PD_DEBUG)
4676                                 dev_info(&instance->pdev->dev,
4677                                          "PD%d: targetID: 0x%03x deviceType:0x%x\n",
4678                                          pd_index, le16_to_cpu(pd_addr->deviceId),
4679                                          pd_addr->scsiDevType);
4680                         pd_addr++;
4681                 }
4682
4683                 memcpy(instance->pd_list, instance->local_pd_list,
4684                         sizeof(instance->pd_list));
4685                 break;
4686
4687         }
4688
4689         if (ret != DCMD_TIMEOUT)
4690                 megasas_return_cmd(instance, cmd);
4691
4692         return ret;
4693 }
4694
4695 /*
4696  * megasas_get_ld_list_info -   Returns FW's ld_list structure
4697  * @instance:                           Adapter soft state
4698  * @ld_list:                            ld_list structure
4699  *
4700  * Issues an internal command (DCMD) to get the FW's controller PD
4701  * list structure.  This information is mainly used to find out SYSTEM
4702  * supported by the FW.
4703  */
4704 static int
4705 megasas_get_ld_list(struct megasas_instance *instance)
4706 {
4707         int ret = 0, ld_index = 0, ids = 0;
4708         struct megasas_cmd *cmd;
4709         struct megasas_dcmd_frame *dcmd;
4710         struct MR_LD_LIST *ci;
4711         dma_addr_t ci_h = 0;
4712         u32 ld_count;
4713
4714         ci = instance->ld_list_buf;
4715         ci_h = instance->ld_list_buf_h;
4716
4717         cmd = megasas_get_cmd(instance);
4718
4719         if (!cmd) {
4720                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_list: Failed to get cmd\n");
4721                 return -ENOMEM;
4722         }
4723
4724         dcmd = &cmd->frame->dcmd;
4725
4726         memset(ci, 0, sizeof(*ci));
4727         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4728
4729         if (instance->supportmax256vd)
4730                 dcmd->mbox.b[0] = 1;
4731         dcmd->cmd = MFI_CMD_DCMD;
4732         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4733         dcmd->sge_count = 1;
4734         dcmd->flags = MFI_FRAME_DIR_READ;
4735         dcmd->timeout = 0;
4736         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_LIST));
4737         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_GET_LIST);
4738         dcmd->pad_0  = 0;
4739
4740         megasas_set_dma_settings(instance, dcmd, ci_h,
4741                                  sizeof(struct MR_LD_LIST));
4742
4743         if ((instance->adapter_type != MFI_SERIES) &&
4744             !instance->mask_interrupts)
4745                 ret = megasas_issue_blocked_cmd(instance, cmd,
4746                         MFI_IO_TIMEOUT_SECS);
4747         else
4748                 ret = megasas_issue_polled(instance, cmd);
4749
4750         ld_count = le32_to_cpu(ci->ldCount);
4751
4752         switch (ret) {
4753         case DCMD_FAILED:
4754                 megaraid_sas_kill_hba(instance);
4755                 break;
4756         case DCMD_TIMEOUT:
4757
4758                 switch (dcmd_timeout_ocr_possible(instance)) {
4759                 case INITIATE_OCR:
4760                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4761                         /*
4762                          * DCMD failed from AEN path.
4763                          * AEN path already hold reset_mutex to avoid PCI access
4764                          * while OCR is in progress.
4765                          */
4766                         mutex_unlock(&instance->reset_mutex);
4767                         megasas_reset_fusion(instance->host,
4768                                                 MFI_IO_TIMEOUT_OCR);
4769                         mutex_lock(&instance->reset_mutex);
4770                         break;
4771                 case KILL_ADAPTER:
4772                         megaraid_sas_kill_hba(instance);
4773                         break;
4774                 case IGNORE_TIMEOUT:
4775                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4776                                 __func__, __LINE__);
4777                         break;
4778                 }
4779
4780                 break;
4781
4782         case DCMD_SUCCESS:
4783                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4784                         dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4785                                  __func__, ld_count);
4786
4787                 if (ld_count > instance->fw_supported_vd_count)
4788                         break;
4789
4790                 memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
4791
4792                 for (ld_index = 0; ld_index < ld_count; ld_index++) {
4793                         if (ci->ldList[ld_index].state != 0) {
4794                                 ids = ci->ldList[ld_index].ref.targetId;
4795                                 instance->ld_ids[ids] = ci->ldList[ld_index].ref.targetId;
4796                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4797                                         dev_info(&instance->pdev->dev,
4798                                                  "LD%d: targetID: 0x%03x\n",
4799                                                  ld_index, ids);
4800                         }
4801                 }
4802
4803                 break;
4804         }
4805
4806         if (ret != DCMD_TIMEOUT)
4807                 megasas_return_cmd(instance, cmd);
4808
4809         return ret;
4810 }
4811
4812 /**
4813  * megasas_ld_list_query -      Returns FW's ld_list structure
4814  * @instance:                           Adapter soft state
4815  * @query_type:                         ld_list structure type
4816  *
4817  * Issues an internal command (DCMD) to get the FW's controller PD
4818  * list structure.  This information is mainly used to find out SYSTEM
4819  * supported by the FW.
4820  */
4821 static int
4822 megasas_ld_list_query(struct megasas_instance *instance, u8 query_type)
4823 {
4824         int ret = 0, ld_index = 0, ids = 0;
4825         struct megasas_cmd *cmd;
4826         struct megasas_dcmd_frame *dcmd;
4827         struct MR_LD_TARGETID_LIST *ci;
4828         dma_addr_t ci_h = 0;
4829         u32 tgtid_count;
4830
4831         ci = instance->ld_targetid_list_buf;
4832         ci_h = instance->ld_targetid_list_buf_h;
4833
4834         cmd = megasas_get_cmd(instance);
4835
4836         if (!cmd) {
4837                 dev_warn(&instance->pdev->dev,
4838                          "megasas_ld_list_query: Failed to get cmd\n");
4839                 return -ENOMEM;
4840         }
4841
4842         dcmd = &cmd->frame->dcmd;
4843
4844         memset(ci, 0, sizeof(*ci));
4845         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4846
4847         dcmd->mbox.b[0] = query_type;
4848         if (instance->supportmax256vd)
4849                 dcmd->mbox.b[2] = 1;
4850
4851         dcmd->cmd = MFI_CMD_DCMD;
4852         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4853         dcmd->sge_count = 1;
4854         dcmd->flags = MFI_FRAME_DIR_READ;
4855         dcmd->timeout = 0;
4856         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
4857         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_LIST_QUERY);
4858         dcmd->pad_0  = 0;
4859
4860         megasas_set_dma_settings(instance, dcmd, ci_h,
4861                                  sizeof(struct MR_LD_TARGETID_LIST));
4862
4863         if ((instance->adapter_type != MFI_SERIES) &&
4864             !instance->mask_interrupts)
4865                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4866         else
4867                 ret = megasas_issue_polled(instance, cmd);
4868
4869         switch (ret) {
4870         case DCMD_FAILED:
4871                 dev_info(&instance->pdev->dev,
4872                         "DCMD not supported by firmware - %s %d\n",
4873                                 __func__, __LINE__);
4874                 ret = megasas_get_ld_list(instance);
4875                 break;
4876         case DCMD_TIMEOUT:
4877                 switch (dcmd_timeout_ocr_possible(instance)) {
4878                 case INITIATE_OCR:
4879                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4880                         /*
4881                          * DCMD failed from AEN path.
4882                          * AEN path already hold reset_mutex to avoid PCI access
4883                          * while OCR is in progress.
4884                          */
4885                         mutex_unlock(&instance->reset_mutex);
4886                         megasas_reset_fusion(instance->host,
4887                                                 MFI_IO_TIMEOUT_OCR);
4888                         mutex_lock(&instance->reset_mutex);
4889                         break;
4890                 case KILL_ADAPTER:
4891                         megaraid_sas_kill_hba(instance);
4892                         break;
4893                 case IGNORE_TIMEOUT:
4894                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4895                                 __func__, __LINE__);
4896                         break;
4897                 }
4898
4899                 break;
4900         case DCMD_SUCCESS:
4901                 tgtid_count = le32_to_cpu(ci->count);
4902
4903                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4904                         dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4905                                  __func__, tgtid_count);
4906
4907                 if ((tgtid_count > (instance->fw_supported_vd_count)))
4908                         break;
4909
4910                 memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
4911                 for (ld_index = 0; ld_index < tgtid_count; ld_index++) {
4912                         ids = ci->targetId[ld_index];
4913                         instance->ld_ids[ids] = ci->targetId[ld_index];
4914                         if (megasas_dbg_lvl & LD_PD_DEBUG)
4915                                 dev_info(&instance->pdev->dev, "LD%d: targetID: 0x%03x\n",
4916                                          ld_index, ci->targetId[ld_index]);
4917                 }
4918
4919                 break;
4920         }
4921
4922         if (ret != DCMD_TIMEOUT)
4923                 megasas_return_cmd(instance, cmd);
4924
4925         return ret;
4926 }
4927
4928 /**
4929  * dcmd.opcode            - MR_DCMD_CTRL_DEVICE_LIST_GET
4930  * dcmd.mbox              - reserved
4931  * dcmd.sge IN            - ptr to return MR_HOST_DEVICE_LIST structure
4932  * Desc:    This DCMD will return the combined device list
4933  * Status:  MFI_STAT_OK - List returned successfully
4934  *          MFI_STAT_INVALID_CMD - Firmware support for the feature has been
4935  *                                 disabled
4936  * @instance:                   Adapter soft state
4937  * @is_probe:                   Driver probe check
4938  * Return:                      0 if DCMD succeeded
4939  *                               non-zero if failed
4940  */
4941 static int
4942 megasas_host_device_list_query(struct megasas_instance *instance,
4943                                bool is_probe)
4944 {
4945         int ret, i, target_id;
4946         struct megasas_cmd *cmd;
4947         struct megasas_dcmd_frame *dcmd;
4948         struct MR_HOST_DEVICE_LIST *ci;
4949         u32 count;
4950         dma_addr_t ci_h;
4951
4952         ci = instance->host_device_list_buf;
4953         ci_h = instance->host_device_list_buf_h;
4954
4955         cmd = megasas_get_cmd(instance);
4956
4957         if (!cmd) {
4958                 dev_warn(&instance->pdev->dev,
4959                          "%s: failed to get cmd\n",
4960                          __func__);
4961                 return -ENOMEM;
4962         }
4963
4964         dcmd = &cmd->frame->dcmd;
4965
4966         memset(ci, 0, sizeof(*ci));
4967         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4968
4969         dcmd->mbox.b[0] = is_probe ? 0 : 1;
4970         dcmd->cmd = MFI_CMD_DCMD;
4971         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4972         dcmd->sge_count = 1;
4973         dcmd->flags = MFI_FRAME_DIR_READ;
4974         dcmd->timeout = 0;
4975         dcmd->pad_0 = 0;
4976         dcmd->data_xfer_len = cpu_to_le32(HOST_DEVICE_LIST_SZ);
4977         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_DEVICE_LIST_GET);
4978
4979         megasas_set_dma_settings(instance, dcmd, ci_h, HOST_DEVICE_LIST_SZ);
4980
4981         if (!instance->mask_interrupts) {
4982                 ret = megasas_issue_blocked_cmd(instance, cmd,
4983                                                 MFI_IO_TIMEOUT_SECS);
4984         } else {
4985                 ret = megasas_issue_polled(instance, cmd);
4986                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4987         }
4988
4989         switch (ret) {
4990         case DCMD_SUCCESS:
4991                 /* Fill the internal pd_list and ld_ids array based on
4992                  * targetIds returned by FW
4993                  */
4994                 count = le32_to_cpu(ci->count);
4995
4996                 if (count > (MEGASAS_MAX_PD + MAX_LOGICAL_DRIVES_EXT))
4997                         break;
4998
4999                 if (megasas_dbg_lvl & LD_PD_DEBUG)
5000                         dev_info(&instance->pdev->dev, "%s, Device count: 0x%x\n",
5001                                  __func__, count);
5002
5003                 memset(instance->local_pd_list, 0,
5004                        MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
5005                 memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
5006                 for (i = 0; i < count; i++) {
5007                         target_id = le16_to_cpu(ci->host_device_list[i].target_id);
5008                         if (ci->host_device_list[i].flags.u.bits.is_sys_pd) {
5009                                 instance->local_pd_list[target_id].tid = target_id;
5010                                 instance->local_pd_list[target_id].driveType =
5011                                                 ci->host_device_list[i].scsi_type;
5012                                 instance->local_pd_list[target_id].driveState =
5013                                                 MR_PD_STATE_SYSTEM;
5014                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
5015                                         dev_info(&instance->pdev->dev,
5016                                                  "Device %d: PD targetID: 0x%03x deviceType:0x%x\n",
5017                                                  i, target_id, ci->host_device_list[i].scsi_type);
5018                         } else {
5019                                 instance->ld_ids[target_id] = target_id;
5020                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
5021                                         dev_info(&instance->pdev->dev,
5022                                                  "Device %d: LD targetID: 0x%03x\n",
5023                                                  i, target_id);
5024                         }
5025                 }
5026
5027                 memcpy(instance->pd_list, instance->local_pd_list,
5028                        sizeof(instance->pd_list));
5029                 break;
5030
5031         case DCMD_TIMEOUT:
5032                 switch (dcmd_timeout_ocr_possible(instance)) {
5033                 case INITIATE_OCR:
5034                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5035                         mutex_unlock(&instance->reset_mutex);
5036                         megasas_reset_fusion(instance->host,
5037                                 MFI_IO_TIMEOUT_OCR);
5038                         mutex_lock(&instance->reset_mutex);
5039                         break;
5040                 case KILL_ADAPTER:
5041                         megaraid_sas_kill_hba(instance);
5042                         break;
5043                 case IGNORE_TIMEOUT:
5044                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5045                                  __func__, __LINE__);
5046                         break;
5047                 }
5048                 break;
5049         case DCMD_FAILED:
5050                 dev_err(&instance->pdev->dev,
5051                         "%s: MR_DCMD_CTRL_DEVICE_LIST_GET failed\n",
5052                         __func__);
5053                 break;
5054         }
5055
5056         if (ret != DCMD_TIMEOUT)
5057                 megasas_return_cmd(instance, cmd);
5058
5059         return ret;
5060 }
5061
5062 /*
5063  * megasas_update_ext_vd_details : Update details w.r.t Extended VD
5064  * instance                      : Controller's instance
5065 */
5066 static void megasas_update_ext_vd_details(struct megasas_instance *instance)
5067 {
5068         struct fusion_context *fusion;
5069         u32 ventura_map_sz = 0;
5070
5071         fusion = instance->ctrl_context;
5072         /* For MFI based controllers return dummy success */
5073         if (!fusion)
5074                 return;
5075
5076         instance->supportmax256vd =
5077                 instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs;
5078         /* Below is additional check to address future FW enhancement */
5079         if (instance->ctrl_info_buf->max_lds > 64)
5080                 instance->supportmax256vd = 1;
5081
5082         instance->drv_supported_vd_count = MEGASAS_MAX_LD_CHANNELS
5083                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
5084         instance->drv_supported_pd_count = MEGASAS_MAX_PD_CHANNELS
5085                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
5086         if (instance->supportmax256vd) {
5087                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES_EXT;
5088                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
5089         } else {
5090                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
5091                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
5092         }
5093
5094         dev_info(&instance->pdev->dev,
5095                 "FW provided supportMaxExtLDs: %d\tmax_lds: %d\n",
5096                 instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs ? 1 : 0,
5097                 instance->ctrl_info_buf->max_lds);
5098
5099         if (instance->max_raid_mapsize) {
5100                 ventura_map_sz = instance->max_raid_mapsize *
5101                                                 MR_MIN_MAP_SIZE; /* 64k */
5102                 fusion->current_map_sz = ventura_map_sz;
5103                 fusion->max_map_sz = ventura_map_sz;
5104         } else {
5105                 fusion->old_map_sz =  sizeof(struct MR_FW_RAID_MAP) +
5106                                         (sizeof(struct MR_LD_SPAN_MAP) *
5107                                         (instance->fw_supported_vd_count - 1));
5108                 fusion->new_map_sz =  sizeof(struct MR_FW_RAID_MAP_EXT);
5109
5110                 fusion->max_map_sz =
5111                         max(fusion->old_map_sz, fusion->new_map_sz);
5112
5113                 if (instance->supportmax256vd)
5114                         fusion->current_map_sz = fusion->new_map_sz;
5115                 else
5116                         fusion->current_map_sz = fusion->old_map_sz;
5117         }
5118         /* irrespective of FW raid maps, driver raid map is constant */
5119         fusion->drv_map_sz = sizeof(struct MR_DRV_RAID_MAP_ALL);
5120 }
5121
5122 /*
5123  * dcmd.opcode                - MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES
5124  * dcmd.hdr.length            - number of bytes to read
5125  * dcmd.sge                   - Ptr to MR_SNAPDUMP_PROPERTIES
5126  * Desc:                         Fill in snapdump properties
5127  * Status:                       MFI_STAT_OK- Command successful
5128  */
5129 void megasas_get_snapdump_properties(struct megasas_instance *instance)
5130 {
5131         int ret = 0;
5132         struct megasas_cmd *cmd;
5133         struct megasas_dcmd_frame *dcmd;
5134         struct MR_SNAPDUMP_PROPERTIES *ci;
5135         dma_addr_t ci_h = 0;
5136
5137         ci = instance->snapdump_prop;
5138         ci_h = instance->snapdump_prop_h;
5139
5140         if (!ci)
5141                 return;
5142
5143         cmd = megasas_get_cmd(instance);
5144
5145         if (!cmd) {
5146                 dev_dbg(&instance->pdev->dev, "Failed to get a free cmd\n");
5147                 return;
5148         }
5149
5150         dcmd = &cmd->frame->dcmd;
5151
5152         memset(ci, 0, sizeof(*ci));
5153         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5154
5155         dcmd->cmd = MFI_CMD_DCMD;
5156         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5157         dcmd->sge_count = 1;
5158         dcmd->flags = MFI_FRAME_DIR_READ;
5159         dcmd->timeout = 0;
5160         dcmd->pad_0 = 0;
5161         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_SNAPDUMP_PROPERTIES));
5162         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES);
5163
5164         megasas_set_dma_settings(instance, dcmd, ci_h,
5165                                  sizeof(struct MR_SNAPDUMP_PROPERTIES));
5166
5167         if (!instance->mask_interrupts) {
5168                 ret = megasas_issue_blocked_cmd(instance, cmd,
5169                                                 MFI_IO_TIMEOUT_SECS);
5170         } else {
5171                 ret = megasas_issue_polled(instance, cmd);
5172                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5173         }
5174
5175         switch (ret) {
5176         case DCMD_SUCCESS:
5177                 instance->snapdump_wait_time =
5178                         min_t(u8, ci->trigger_min_num_sec_before_ocr,
5179                                 MEGASAS_MAX_SNAP_DUMP_WAIT_TIME);
5180                 break;
5181
5182         case DCMD_TIMEOUT:
5183                 switch (dcmd_timeout_ocr_possible(instance)) {
5184                 case INITIATE_OCR:
5185                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5186                         mutex_unlock(&instance->reset_mutex);
5187                         megasas_reset_fusion(instance->host,
5188                                 MFI_IO_TIMEOUT_OCR);
5189                         mutex_lock(&instance->reset_mutex);
5190                         break;
5191                 case KILL_ADAPTER:
5192                         megaraid_sas_kill_hba(instance);
5193                         break;
5194                 case IGNORE_TIMEOUT:
5195                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5196                                 __func__, __LINE__);
5197                         break;
5198                 }
5199         }
5200
5201         if (ret != DCMD_TIMEOUT)
5202                 megasas_return_cmd(instance, cmd);
5203 }
5204
5205 /**
5206  * megasas_get_controller_info -        Returns FW's controller structure
5207  * @instance:                           Adapter soft state
5208  *
5209  * Issues an internal command (DCMD) to get the FW's controller structure.
5210  * This information is mainly used to find out the maximum IO transfer per
5211  * command supported by the FW.
5212  */
5213 int
5214 megasas_get_ctrl_info(struct megasas_instance *instance)
5215 {
5216         int ret = 0;
5217         struct megasas_cmd *cmd;
5218         struct megasas_dcmd_frame *dcmd;
5219         struct megasas_ctrl_info *ci;
5220         dma_addr_t ci_h = 0;
5221
5222         ci = instance->ctrl_info_buf;
5223         ci_h = instance->ctrl_info_buf_h;
5224
5225         cmd = megasas_get_cmd(instance);
5226
5227         if (!cmd) {
5228                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a free cmd\n");
5229                 return -ENOMEM;
5230         }
5231
5232         dcmd = &cmd->frame->dcmd;
5233
5234         memset(ci, 0, sizeof(*ci));
5235         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5236
5237         dcmd->cmd = MFI_CMD_DCMD;
5238         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5239         dcmd->sge_count = 1;
5240         dcmd->flags = MFI_FRAME_DIR_READ;
5241         dcmd->timeout = 0;
5242         dcmd->pad_0 = 0;
5243         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_ctrl_info));
5244         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_GET_INFO);
5245         dcmd->mbox.b[0] = 1;
5246
5247         megasas_set_dma_settings(instance, dcmd, ci_h,
5248                                  sizeof(struct megasas_ctrl_info));
5249
5250         if ((instance->adapter_type != MFI_SERIES) &&
5251             !instance->mask_interrupts) {
5252                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5253         } else {
5254                 ret = megasas_issue_polled(instance, cmd);
5255                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5256         }
5257
5258         switch (ret) {
5259         case DCMD_SUCCESS:
5260                 /* Save required controller information in
5261                  * CPU endianness format.
5262                  */
5263                 le32_to_cpus((u32 *)&ci->properties.OnOffProperties);
5264                 le16_to_cpus((u16 *)&ci->properties.on_off_properties2);
5265                 le32_to_cpus((u32 *)&ci->adapterOperations2);
5266                 le32_to_cpus((u32 *)&ci->adapterOperations3);
5267                 le16_to_cpus((u16 *)&ci->adapter_operations4);
5268                 le32_to_cpus((u32 *)&ci->adapter_operations5);
5269
5270                 /* Update the latest Ext VD info.
5271                  * From Init path, store current firmware details.
5272                  * From OCR path, detect any firmware properties changes.
5273                  * in case of Firmware upgrade without system reboot.
5274                  */
5275                 megasas_update_ext_vd_details(instance);
5276                 instance->support_seqnum_jbod_fp =
5277                         ci->adapterOperations3.useSeqNumJbodFP;
5278                 instance->support_morethan256jbod =
5279                         ci->adapter_operations4.support_pd_map_target_id;
5280                 instance->support_nvme_passthru =
5281                         ci->adapter_operations4.support_nvme_passthru;
5282                 instance->support_pci_lane_margining =
5283                         ci->adapter_operations5.support_pci_lane_margining;
5284                 instance->task_abort_tmo = ci->TaskAbortTO;
5285                 instance->max_reset_tmo = ci->MaxResetTO;
5286
5287                 /*Check whether controller is iMR or MR */
5288                 instance->is_imr = (ci->memory_size ? 0 : 1);
5289
5290                 instance->snapdump_wait_time =
5291                         (ci->properties.on_off_properties2.enable_snap_dump ?
5292                          MEGASAS_DEFAULT_SNAP_DUMP_WAIT_TIME : 0);
5293
5294                 instance->enable_fw_dev_list =
5295                         ci->properties.on_off_properties2.enable_fw_dev_list;
5296
5297                 dev_info(&instance->pdev->dev,
5298                         "controller type\t: %s(%dMB)\n",
5299                         instance->is_imr ? "iMR" : "MR",
5300                         le16_to_cpu(ci->memory_size));
5301
5302                 instance->disableOnlineCtrlReset =
5303                         ci->properties.OnOffProperties.disableOnlineCtrlReset;
5304                 instance->secure_jbod_support =
5305                         ci->adapterOperations3.supportSecurityonJBOD;
5306                 dev_info(&instance->pdev->dev, "Online Controller Reset(OCR)\t: %s\n",
5307                         instance->disableOnlineCtrlReset ? "Disabled" : "Enabled");
5308                 dev_info(&instance->pdev->dev, "Secure JBOD support\t: %s\n",
5309                         instance->secure_jbod_support ? "Yes" : "No");
5310                 dev_info(&instance->pdev->dev, "NVMe passthru support\t: %s\n",
5311                          instance->support_nvme_passthru ? "Yes" : "No");
5312                 dev_info(&instance->pdev->dev,
5313                          "FW provided TM TaskAbort/Reset timeout\t: %d secs/%d secs\n",
5314                          instance->task_abort_tmo, instance->max_reset_tmo);
5315                 dev_info(&instance->pdev->dev, "JBOD sequence map support\t: %s\n",
5316                          instance->support_seqnum_jbod_fp ? "Yes" : "No");
5317                 dev_info(&instance->pdev->dev, "PCI Lane Margining support\t: %s\n",
5318                          instance->support_pci_lane_margining ? "Yes" : "No");
5319
5320                 break;
5321
5322         case DCMD_TIMEOUT:
5323                 switch (dcmd_timeout_ocr_possible(instance)) {
5324                 case INITIATE_OCR:
5325                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5326                         mutex_unlock(&instance->reset_mutex);
5327                         megasas_reset_fusion(instance->host,
5328                                 MFI_IO_TIMEOUT_OCR);
5329                         mutex_lock(&instance->reset_mutex);
5330                         break;
5331                 case KILL_ADAPTER:
5332                         megaraid_sas_kill_hba(instance);
5333                         break;
5334                 case IGNORE_TIMEOUT:
5335                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5336                                 __func__, __LINE__);
5337                         break;
5338                 }
5339                 break;
5340         case DCMD_FAILED:
5341                 megaraid_sas_kill_hba(instance);
5342                 break;
5343
5344         }
5345
5346         if (ret != DCMD_TIMEOUT)
5347                 megasas_return_cmd(instance, cmd);
5348
5349         return ret;
5350 }
5351
5352 /*
5353  * megasas_set_crash_dump_params -      Sends address of crash dump DMA buffer
5354  *                                      to firmware
5355  *
5356  * @instance:                           Adapter soft state
5357  * @crash_buf_state             -       tell FW to turn ON/OFF crash dump feature
5358                                         MR_CRASH_BUF_TURN_OFF = 0
5359                                         MR_CRASH_BUF_TURN_ON = 1
5360  * @return 0 on success non-zero on failure.
5361  * Issues an internal command (DCMD) to set parameters for crash dump feature.
5362  * Driver will send address of crash dump DMA buffer and set mbox to tell FW
5363  * that driver supports crash dump feature. This DCMD will be sent only if
5364  * crash dump feature is supported by the FW.
5365  *
5366  */
5367 int megasas_set_crash_dump_params(struct megasas_instance *instance,
5368         u8 crash_buf_state)
5369 {
5370         int ret = 0;
5371         struct megasas_cmd *cmd;
5372         struct megasas_dcmd_frame *dcmd;
5373
5374         cmd = megasas_get_cmd(instance);
5375
5376         if (!cmd) {
5377                 dev_err(&instance->pdev->dev, "Failed to get a free cmd\n");
5378                 return -ENOMEM;
5379         }
5380
5381
5382         dcmd = &cmd->frame->dcmd;
5383
5384         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5385         dcmd->mbox.b[0] = crash_buf_state;
5386         dcmd->cmd = MFI_CMD_DCMD;
5387         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5388         dcmd->sge_count = 1;
5389         dcmd->flags = MFI_FRAME_DIR_NONE;
5390         dcmd->timeout = 0;
5391         dcmd->pad_0 = 0;
5392         dcmd->data_xfer_len = cpu_to_le32(CRASH_DMA_BUF_SIZE);
5393         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SET_CRASH_DUMP_PARAMS);
5394
5395         megasas_set_dma_settings(instance, dcmd, instance->crash_dump_h,
5396                                  CRASH_DMA_BUF_SIZE);
5397
5398         if ((instance->adapter_type != MFI_SERIES) &&
5399             !instance->mask_interrupts)
5400                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5401         else
5402                 ret = megasas_issue_polled(instance, cmd);
5403
5404         if (ret == DCMD_TIMEOUT) {
5405                 switch (dcmd_timeout_ocr_possible(instance)) {
5406                 case INITIATE_OCR:
5407                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5408                         megasas_reset_fusion(instance->host,
5409                                         MFI_IO_TIMEOUT_OCR);
5410                         break;
5411                 case KILL_ADAPTER:
5412                         megaraid_sas_kill_hba(instance);
5413                         break;
5414                 case IGNORE_TIMEOUT:
5415                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5416                                 __func__, __LINE__);
5417                         break;
5418                 }
5419         } else
5420                 megasas_return_cmd(instance, cmd);
5421
5422         return ret;
5423 }
5424
5425 /**
5426  * megasas_issue_init_mfi -     Initializes the FW
5427  * @instance:           Adapter soft state
5428  *
5429  * Issues the INIT MFI cmd
5430  */
5431 static int
5432 megasas_issue_init_mfi(struct megasas_instance *instance)
5433 {
5434         __le32 context;
5435         struct megasas_cmd *cmd;
5436         struct megasas_init_frame *init_frame;
5437         struct megasas_init_queue_info *initq_info;
5438         dma_addr_t init_frame_h;
5439         dma_addr_t initq_info_h;
5440
5441         /*
5442          * Prepare a init frame. Note the init frame points to queue info
5443          * structure. Each frame has SGL allocated after first 64 bytes. For
5444          * this frame - since we don't need any SGL - we use SGL's space as
5445          * queue info structure
5446          *
5447          * We will not get a NULL command below. We just created the pool.
5448          */
5449         cmd = megasas_get_cmd(instance);
5450
5451         init_frame = (struct megasas_init_frame *)cmd->frame;
5452         initq_info = (struct megasas_init_queue_info *)
5453                 ((unsigned long)init_frame + 64);
5454
5455         init_frame_h = cmd->frame_phys_addr;
5456         initq_info_h = init_frame_h + 64;
5457
5458         context = init_frame->context;
5459         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
5460         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
5461         init_frame->context = context;
5462
5463         initq_info->reply_queue_entries = cpu_to_le32(instance->max_fw_cmds + 1);
5464         initq_info->reply_queue_start_phys_addr_lo = cpu_to_le32(instance->reply_queue_h);
5465
5466         initq_info->producer_index_phys_addr_lo = cpu_to_le32(instance->producer_h);
5467         initq_info->consumer_index_phys_addr_lo = cpu_to_le32(instance->consumer_h);
5468
5469         init_frame->cmd = MFI_CMD_INIT;
5470         init_frame->cmd_status = MFI_STAT_INVALID_STATUS;
5471         init_frame->queue_info_new_phys_addr_lo =
5472                 cpu_to_le32(lower_32_bits(initq_info_h));
5473         init_frame->queue_info_new_phys_addr_hi =
5474                 cpu_to_le32(upper_32_bits(initq_info_h));
5475
5476         init_frame->data_xfer_len = cpu_to_le32(sizeof(struct megasas_init_queue_info));
5477
5478         /*
5479          * disable the intr before firing the init frame to FW
5480          */
5481         instance->instancet->disable_intr(instance);
5482
5483         /*
5484          * Issue the init frame in polled mode
5485          */
5486
5487         if (megasas_issue_polled(instance, cmd)) {
5488                 dev_err(&instance->pdev->dev, "Failed to init firmware\n");
5489                 megasas_return_cmd(instance, cmd);
5490                 goto fail_fw_init;
5491         }
5492
5493         megasas_return_cmd(instance, cmd);
5494
5495         return 0;
5496
5497 fail_fw_init:
5498         return -EINVAL;
5499 }
5500
5501 static u32
5502 megasas_init_adapter_mfi(struct megasas_instance *instance)
5503 {
5504         u32 context_sz;
5505         u32 reply_q_sz;
5506
5507         /*
5508          * Get various operational parameters from status register
5509          */
5510         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(instance) & 0x00FFFF;
5511         /*
5512          * Reduce the max supported cmds by 1. This is to ensure that the
5513          * reply_q_sz (1 more than the max cmd that driver may send)
5514          * does not exceed max cmds that the FW can support
5515          */
5516         instance->max_fw_cmds = instance->max_fw_cmds-1;
5517         instance->max_mfi_cmds = instance->max_fw_cmds;
5518         instance->max_num_sge = (instance->instancet->read_fw_status_reg(instance) & 0xFF0000) >>
5519                                         0x10;
5520         /*
5521          * For MFI skinny adapters, MEGASAS_SKINNY_INT_CMDS commands
5522          * are reserved for IOCTL + driver's internal DCMDs.
5523          */
5524         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
5525                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
5526                 instance->max_scsi_cmds = (instance->max_fw_cmds -
5527                         MEGASAS_SKINNY_INT_CMDS);
5528                 sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
5529         } else {
5530                 instance->max_scsi_cmds = (instance->max_fw_cmds -
5531                         MEGASAS_INT_CMDS);
5532                 sema_init(&instance->ioctl_sem, (MEGASAS_MFI_IOCTL_CMDS));
5533         }
5534
5535         instance->cur_can_queue = instance->max_scsi_cmds;
5536         /*
5537          * Create a pool of commands
5538          */
5539         if (megasas_alloc_cmds(instance))
5540                 goto fail_alloc_cmds;
5541
5542         /*
5543          * Allocate memory for reply queue. Length of reply queue should
5544          * be _one_ more than the maximum commands handled by the firmware.
5545          *
5546          * Note: When FW completes commands, it places corresponding contex
5547          * values in this circular reply queue. This circular queue is a fairly
5548          * typical producer-consumer queue. FW is the producer (of completed
5549          * commands) and the driver is the consumer.
5550          */
5551         context_sz = sizeof(u32);
5552         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
5553
5554         instance->reply_queue = dma_alloc_coherent(&instance->pdev->dev,
5555                         reply_q_sz, &instance->reply_queue_h, GFP_KERNEL);
5556
5557         if (!instance->reply_queue) {
5558                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Out of DMA mem for reply queue\n");
5559                 goto fail_reply_queue;
5560         }
5561
5562         if (megasas_issue_init_mfi(instance))
5563                 goto fail_fw_init;
5564
5565         if (megasas_get_ctrl_info(instance)) {
5566                 dev_err(&instance->pdev->dev, "(%d): Could get controller info "
5567                         "Fail from %s %d\n", instance->unique_id,
5568                         __func__, __LINE__);
5569                 goto fail_fw_init;
5570         }
5571
5572         instance->fw_support_ieee = 0;
5573         instance->fw_support_ieee =
5574                 (instance->instancet->read_fw_status_reg(instance) &
5575                 0x04000000);
5576
5577         dev_notice(&instance->pdev->dev, "megasas_init_mfi: fw_support_ieee=%d",
5578                         instance->fw_support_ieee);
5579
5580         if (instance->fw_support_ieee)
5581                 instance->flag_ieee = 1;
5582
5583         return 0;
5584
5585 fail_fw_init:
5586
5587         dma_free_coherent(&instance->pdev->dev, reply_q_sz,
5588                             instance->reply_queue, instance->reply_queue_h);
5589 fail_reply_queue:
5590         megasas_free_cmds(instance);
5591
5592 fail_alloc_cmds:
5593         return 1;
5594 }
5595
5596 static
5597 void megasas_setup_irq_poll(struct megasas_instance *instance)
5598 {
5599         struct megasas_irq_context *irq_ctx;
5600         u32 count, i;
5601
5602         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5603
5604         /* Initialize IRQ poll */
5605         for (i = 0; i < count; i++) {
5606                 irq_ctx = &instance->irq_context[i];
5607                 irq_ctx->os_irq = pci_irq_vector(instance->pdev, i);
5608                 irq_ctx->irq_poll_scheduled = false;
5609                 irq_poll_init(&irq_ctx->irqpoll,
5610                               instance->threshold_reply_count,
5611                               megasas_irqpoll);
5612         }
5613 }
5614
5615 /*
5616  * megasas_setup_irqs_ioapic -          register legacy interrupts.
5617  * @instance:                           Adapter soft state
5618  *
5619  * Do not enable interrupt, only setup ISRs.
5620  *
5621  * Return 0 on success.
5622  */
5623 static int
5624 megasas_setup_irqs_ioapic(struct megasas_instance *instance)
5625 {
5626         struct pci_dev *pdev;
5627
5628         pdev = instance->pdev;
5629         instance->irq_context[0].instance = instance;
5630         instance->irq_context[0].MSIxIndex = 0;
5631         snprintf(instance->irq_context->name, MEGASAS_MSIX_NAME_LEN, "%s%u",
5632                 "megasas", instance->host->host_no);
5633         if (request_irq(pci_irq_vector(pdev, 0),
5634                         instance->instancet->service_isr, IRQF_SHARED,
5635                         instance->irq_context->name, &instance->irq_context[0])) {
5636                 dev_err(&instance->pdev->dev,
5637                                 "Failed to register IRQ from %s %d\n",
5638                                 __func__, __LINE__);
5639                 return -1;
5640         }
5641         instance->perf_mode = MR_LATENCY_PERF_MODE;
5642         instance->low_latency_index_start = 0;
5643         return 0;
5644 }
5645
5646 /**
5647  * megasas_setup_irqs_msix -            register MSI-x interrupts.
5648  * @instance:                           Adapter soft state
5649  * @is_probe:                           Driver probe check
5650  *
5651  * Do not enable interrupt, only setup ISRs.
5652  *
5653  * Return 0 on success.
5654  */
5655 static int
5656 megasas_setup_irqs_msix(struct megasas_instance *instance, u8 is_probe)
5657 {
5658         int i, j;
5659         struct pci_dev *pdev;
5660
5661         pdev = instance->pdev;
5662
5663         /* Try MSI-x */
5664         for (i = 0; i < instance->msix_vectors; i++) {
5665                 instance->irq_context[i].instance = instance;
5666                 instance->irq_context[i].MSIxIndex = i;
5667                 snprintf(instance->irq_context[i].name, MEGASAS_MSIX_NAME_LEN, "%s%u-msix%u",
5668                         "megasas", instance->host->host_no, i);
5669                 if (request_irq(pci_irq_vector(pdev, i),
5670                         instance->instancet->service_isr, 0, instance->irq_context[i].name,
5671                         &instance->irq_context[i])) {
5672                         dev_err(&instance->pdev->dev,
5673                                 "Failed to register IRQ for vector %d.\n", i);
5674                         for (j = 0; j < i; j++) {
5675                                 if (j < instance->low_latency_index_start)
5676                                         irq_set_affinity_hint(
5677                                                 pci_irq_vector(pdev, j), NULL);
5678                                 free_irq(pci_irq_vector(pdev, j),
5679                                          &instance->irq_context[j]);
5680                         }
5681                         /* Retry irq register for IO_APIC*/
5682                         instance->msix_vectors = 0;
5683                         instance->msix_load_balance = false;
5684                         if (is_probe) {
5685                                 pci_free_irq_vectors(instance->pdev);
5686                                 return megasas_setup_irqs_ioapic(instance);
5687                         } else {
5688                                 return -1;
5689                         }
5690                 }
5691         }
5692
5693         return 0;
5694 }
5695
5696 /*
5697  * megasas_destroy_irqs-                unregister interrupts.
5698  * @instance:                           Adapter soft state
5699  * return:                              void
5700  */
5701 static void
5702 megasas_destroy_irqs(struct megasas_instance *instance) {
5703
5704         int i;
5705         int count;
5706         struct megasas_irq_context *irq_ctx;
5707
5708         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5709         if (instance->adapter_type != MFI_SERIES) {
5710                 for (i = 0; i < count; i++) {
5711                         irq_ctx = &instance->irq_context[i];
5712                         irq_poll_disable(&irq_ctx->irqpoll);
5713                 }
5714         }
5715
5716         if (instance->msix_vectors)
5717                 for (i = 0; i < instance->msix_vectors; i++) {
5718                         if (i < instance->low_latency_index_start)
5719                                 irq_set_affinity_hint(
5720                                     pci_irq_vector(instance->pdev, i), NULL);
5721                         free_irq(pci_irq_vector(instance->pdev, i),
5722                                  &instance->irq_context[i]);
5723                 }
5724         else
5725                 free_irq(pci_irq_vector(instance->pdev, 0),
5726                          &instance->irq_context[0]);
5727 }
5728
5729 /**
5730  * megasas_setup_jbod_map -     setup jbod map for FP seq_number.
5731  * @instance:                           Adapter soft state
5732  *
5733  * Return 0 on success.
5734  */
5735 void
5736 megasas_setup_jbod_map(struct megasas_instance *instance)
5737 {
5738         int i;
5739         struct fusion_context *fusion = instance->ctrl_context;
5740         u32 pd_seq_map_sz;
5741
5742         pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) +
5743                 (sizeof(struct MR_PD_CFG_SEQ) * (MAX_PHYSICAL_DEVICES - 1));
5744
5745         instance->use_seqnum_jbod_fp =
5746                 instance->support_seqnum_jbod_fp;
5747         if (reset_devices || !fusion ||
5748                 !instance->support_seqnum_jbod_fp) {
5749                 dev_info(&instance->pdev->dev,
5750                         "JBOD sequence map is disabled %s %d\n",
5751                         __func__, __LINE__);
5752                 instance->use_seqnum_jbod_fp = false;
5753                 return;
5754         }
5755
5756         if (fusion->pd_seq_sync[0])
5757                 goto skip_alloc;
5758
5759         for (i = 0; i < JBOD_MAPS_COUNT; i++) {
5760                 fusion->pd_seq_sync[i] = dma_alloc_coherent
5761                         (&instance->pdev->dev, pd_seq_map_sz,
5762                         &fusion->pd_seq_phys[i], GFP_KERNEL);
5763                 if (!fusion->pd_seq_sync[i]) {
5764                         dev_err(&instance->pdev->dev,
5765                                 "Failed to allocate memory from %s %d\n",
5766                                 __func__, __LINE__);
5767                         if (i == 1) {
5768                                 dma_free_coherent(&instance->pdev->dev,
5769                                         pd_seq_map_sz, fusion->pd_seq_sync[0],
5770                                         fusion->pd_seq_phys[0]);
5771                                 fusion->pd_seq_sync[0] = NULL;
5772                         }
5773                         instance->use_seqnum_jbod_fp = false;
5774                         return;
5775                 }
5776         }
5777
5778 skip_alloc:
5779         if (!megasas_sync_pd_seq_num(instance, false) &&
5780                 !megasas_sync_pd_seq_num(instance, true))
5781                 instance->use_seqnum_jbod_fp = true;
5782         else
5783                 instance->use_seqnum_jbod_fp = false;
5784 }
5785
5786 static void megasas_setup_reply_map(struct megasas_instance *instance)
5787 {
5788         const struct cpumask *mask;
5789         unsigned int queue, cpu, low_latency_index_start;
5790
5791         low_latency_index_start = instance->low_latency_index_start;
5792
5793         for (queue = low_latency_index_start; queue < instance->msix_vectors; queue++) {
5794                 mask = pci_irq_get_affinity(instance->pdev, queue);
5795                 if (!mask)
5796                         goto fallback;
5797
5798                 for_each_cpu(cpu, mask)
5799                         instance->reply_map[cpu] = queue;
5800         }
5801         return;
5802
5803 fallback:
5804         queue = low_latency_index_start;
5805         for_each_possible_cpu(cpu) {
5806                 instance->reply_map[cpu] = queue;
5807                 if (queue == (instance->msix_vectors - 1))
5808                         queue = low_latency_index_start;
5809                 else
5810                         queue++;
5811         }
5812 }
5813
5814 /**
5815  * megasas_get_device_list -    Get the PD and LD device list from FW.
5816  * @instance:                   Adapter soft state
5817  * @return:                     Success or failure
5818  *
5819  * Issue DCMDs to Firmware to get the PD and LD list.
5820  * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
5821  * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
5822  */
5823 static
5824 int megasas_get_device_list(struct megasas_instance *instance)
5825 {
5826         memset(instance->pd_list, 0,
5827                (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
5828         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
5829
5830         if (instance->enable_fw_dev_list) {
5831                 if (megasas_host_device_list_query(instance, true))
5832                         return FAILED;
5833         } else {
5834                 if (megasas_get_pd_list(instance) < 0) {
5835                         dev_err(&instance->pdev->dev, "failed to get PD list\n");
5836                         return FAILED;
5837                 }
5838
5839                 if (megasas_ld_list_query(instance,
5840                                           MR_LD_QUERY_TYPE_EXPOSED_TO_HOST)) {
5841                         dev_err(&instance->pdev->dev, "failed to get LD list\n");
5842                         return FAILED;
5843                 }
5844         }
5845
5846         return SUCCESS;
5847 }
5848
5849 /**
5850  * megasas_set_high_iops_queue_affinity_hint -  Set affinity hint for high IOPS queues
5851  * @instance:                                   Adapter soft state
5852  * return:                                      void
5853  */
5854 static inline void
5855 megasas_set_high_iops_queue_affinity_hint(struct megasas_instance *instance)
5856 {
5857         int i;
5858         int local_numa_node;
5859
5860         if (instance->perf_mode == MR_BALANCED_PERF_MODE) {
5861                 local_numa_node = dev_to_node(&instance->pdev->dev);
5862
5863                 for (i = 0; i < instance->low_latency_index_start; i++)
5864                         irq_set_affinity_hint(pci_irq_vector(instance->pdev, i),
5865                                 cpumask_of_node(local_numa_node));
5866         }
5867 }
5868
5869 static int
5870 __megasas_alloc_irq_vectors(struct megasas_instance *instance)
5871 {
5872         int i, irq_flags;
5873         struct irq_affinity desc = { .pre_vectors = instance->low_latency_index_start };
5874         struct irq_affinity *descp = &desc;
5875
5876         irq_flags = PCI_IRQ_MSIX;
5877
5878         if (instance->smp_affinity_enable)
5879                 irq_flags |= PCI_IRQ_AFFINITY;
5880         else
5881                 descp = NULL;
5882
5883         i = pci_alloc_irq_vectors_affinity(instance->pdev,
5884                 instance->low_latency_index_start,
5885                 instance->msix_vectors, irq_flags, descp);
5886
5887         return i;
5888 }
5889
5890 /**
5891  * megasas_alloc_irq_vectors -  Allocate IRQ vectors/enable MSI-x vectors
5892  * @instance:                   Adapter soft state
5893  * return:                      void
5894  */
5895 static void
5896 megasas_alloc_irq_vectors(struct megasas_instance *instance)
5897 {
5898         int i;
5899         unsigned int num_msix_req;
5900
5901         i = __megasas_alloc_irq_vectors(instance);
5902
5903         if ((instance->perf_mode == MR_BALANCED_PERF_MODE) &&
5904             (i != instance->msix_vectors)) {
5905                 if (instance->msix_vectors)
5906                         pci_free_irq_vectors(instance->pdev);
5907                 /* Disable Balanced IOPS mode and try realloc vectors */
5908                 instance->perf_mode = MR_LATENCY_PERF_MODE;
5909                 instance->low_latency_index_start = 1;
5910                 num_msix_req = num_online_cpus() + instance->low_latency_index_start;
5911
5912                 instance->msix_vectors = min(num_msix_req,
5913                                 instance->msix_vectors);
5914
5915                 i = __megasas_alloc_irq_vectors(instance);
5916
5917         }
5918
5919         dev_info(&instance->pdev->dev,
5920                 "requested/available msix %d/%d\n", instance->msix_vectors, i);
5921
5922         if (i > 0)
5923                 instance->msix_vectors = i;
5924         else
5925                 instance->msix_vectors = 0;
5926
5927         if (instance->smp_affinity_enable)
5928                 megasas_set_high_iops_queue_affinity_hint(instance);
5929 }
5930
5931 /**
5932  * megasas_init_fw -    Initializes the FW
5933  * @instance:           Adapter soft state
5934  *
5935  * This is the main function for initializing firmware
5936  */
5937
5938 static int megasas_init_fw(struct megasas_instance *instance)
5939 {
5940         u32 max_sectors_1;
5941         u32 max_sectors_2, tmp_sectors, msix_enable;
5942         u32 scratch_pad_1, scratch_pad_2, scratch_pad_3, status_reg;
5943         resource_size_t base_addr;
5944         void *base_addr_phys;
5945         struct megasas_ctrl_info *ctrl_info = NULL;
5946         unsigned long bar_list;
5947         int i, j, loop;
5948         struct IOV_111 *iovPtr;
5949         struct fusion_context *fusion;
5950         bool intr_coalescing;
5951         unsigned int num_msix_req;
5952         u16 lnksta, speed;
5953
5954         fusion = instance->ctrl_context;
5955
5956         /* Find first memory bar */
5957         bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
5958         instance->bar = find_first_bit(&bar_list, BITS_PER_LONG);
5959         if (pci_request_selected_regions(instance->pdev, 1<<instance->bar,
5960                                          "megasas: LSI")) {
5961                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "IO memory region busy!\n");
5962                 return -EBUSY;
5963         }
5964
5965         base_addr = pci_resource_start(instance->pdev, instance->bar);
5966         instance->reg_set = ioremap(base_addr, 8192);
5967
5968         if (!instance->reg_set) {
5969                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to map IO mem\n");
5970                 goto fail_ioremap;
5971         }
5972
5973         base_addr_phys = &base_addr;
5974         dev_printk(KERN_DEBUG, &instance->pdev->dev,
5975                    "BAR:0x%lx  BAR's base_addr(phys):%pa  mapped virt_addr:0x%p\n",
5976                    instance->bar, base_addr_phys, instance->reg_set);
5977
5978         if (instance->adapter_type != MFI_SERIES)
5979                 instance->instancet = &megasas_instance_template_fusion;
5980         else {
5981                 switch (instance->pdev->device) {
5982                 case PCI_DEVICE_ID_LSI_SAS1078R:
5983                 case PCI_DEVICE_ID_LSI_SAS1078DE:
5984                         instance->instancet = &megasas_instance_template_ppc;
5985                         break;
5986                 case PCI_DEVICE_ID_LSI_SAS1078GEN2:
5987                 case PCI_DEVICE_ID_LSI_SAS0079GEN2:
5988                         instance->instancet = &megasas_instance_template_gen2;
5989                         break;
5990                 case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
5991                 case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
5992                         instance->instancet = &megasas_instance_template_skinny;
5993                         break;
5994                 case PCI_DEVICE_ID_LSI_SAS1064R:
5995                 case PCI_DEVICE_ID_DELL_PERC5:
5996                 default:
5997                         instance->instancet = &megasas_instance_template_xscale;
5998                         instance->pd_list_not_supported = 1;
5999                         break;
6000                 }
6001         }
6002
6003         if (megasas_transition_to_ready(instance, 0)) {
6004                 dev_info(&instance->pdev->dev,
6005                          "Failed to transition controller to ready from %s!\n",
6006                          __func__);
6007                 if (instance->adapter_type != MFI_SERIES) {
6008                         status_reg = instance->instancet->read_fw_status_reg(
6009                                         instance);
6010                         if (status_reg & MFI_RESET_ADAPTER) {
6011                                 if (megasas_adp_reset_wait_for_ready
6012                                         (instance, true, 0) == FAILED)
6013                                         goto fail_ready_state;
6014                         } else {
6015                                 goto fail_ready_state;
6016                         }
6017                 } else {
6018                         atomic_set(&instance->fw_reset_no_pci_access, 1);
6019                         instance->instancet->adp_reset
6020                                 (instance, instance->reg_set);
6021                         atomic_set(&instance->fw_reset_no_pci_access, 0);
6022
6023                         /*waiting for about 30 second before retry*/
6024                         ssleep(30);
6025
6026                         if (megasas_transition_to_ready(instance, 0))
6027                                 goto fail_ready_state;
6028                 }
6029
6030                 dev_info(&instance->pdev->dev,
6031                          "FW restarted successfully from %s!\n",
6032                          __func__);
6033         }
6034
6035         megasas_init_ctrl_params(instance);
6036
6037         if (megasas_set_dma_mask(instance))
6038                 goto fail_ready_state;
6039
6040         if (megasas_alloc_ctrl_mem(instance))
6041                 goto fail_alloc_dma_buf;
6042
6043         if (megasas_alloc_ctrl_dma_buffers(instance))
6044                 goto fail_alloc_dma_buf;
6045
6046         fusion = instance->ctrl_context;
6047
6048         if (instance->adapter_type >= VENTURA_SERIES) {
6049                 scratch_pad_2 =
6050                         megasas_readl(instance,
6051                                       &instance->reg_set->outbound_scratch_pad_2);
6052                 instance->max_raid_mapsize = ((scratch_pad_2 >>
6053                         MR_MAX_RAID_MAP_SIZE_OFFSET_SHIFT) &
6054                         MR_MAX_RAID_MAP_SIZE_MASK);
6055         }
6056
6057         instance->enable_sdev_max_qd = enable_sdev_max_qd;
6058
6059         switch (instance->adapter_type) {
6060         case VENTURA_SERIES:
6061                 fusion->pcie_bw_limitation = true;
6062                 break;
6063         case AERO_SERIES:
6064                 fusion->r56_div_offload = true;
6065                 break;
6066         default:
6067                 break;
6068         }
6069
6070         /* Check if MSI-X is supported while in ready state */
6071         msix_enable = (instance->instancet->read_fw_status_reg(instance) &
6072                        0x4000000) >> 0x1a;
6073         if (msix_enable && !msix_disable) {
6074
6075                 scratch_pad_1 = megasas_readl
6076                         (instance, &instance->reg_set->outbound_scratch_pad_1);
6077                 /* Check max MSI-X vectors */
6078                 if (fusion) {
6079                         if (instance->adapter_type == THUNDERBOLT_SERIES) {
6080                                 /* Thunderbolt Series*/
6081                                 instance->msix_vectors = (scratch_pad_1
6082                                         & MR_MAX_REPLY_QUEUES_OFFSET) + 1;
6083                         } else {
6084                                 instance->msix_vectors = ((scratch_pad_1
6085                                         & MR_MAX_REPLY_QUEUES_EXT_OFFSET)
6086                                         >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1;
6087
6088                                 /*
6089                                  * For Invader series, > 8 MSI-x vectors
6090                                  * supported by FW/HW implies combined
6091                                  * reply queue mode is enabled.
6092                                  * For Ventura series, > 16 MSI-x vectors
6093                                  * supported by FW/HW implies combined
6094                                  * reply queue mode is enabled.
6095                                  */
6096                                 switch (instance->adapter_type) {
6097                                 case INVADER_SERIES:
6098                                         if (instance->msix_vectors > 8)
6099                                                 instance->msix_combined = true;
6100                                         break;
6101                                 case AERO_SERIES:
6102                                 case VENTURA_SERIES:
6103                                         if (instance->msix_vectors > 16)
6104                                                 instance->msix_combined = true;
6105                                         break;
6106                                 }
6107
6108                                 if (rdpq_enable)
6109                                         instance->is_rdpq = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ?
6110                                                                 1 : 0;
6111
6112                                 if (instance->adapter_type >= INVADER_SERIES &&
6113                                     !instance->msix_combined) {
6114                                         instance->msix_load_balance = true;
6115                                         instance->smp_affinity_enable = false;
6116                                 }
6117
6118                                 /* Save 1-15 reply post index address to local memory
6119                                  * Index 0 is already saved from reg offset
6120                                  * MPI2_REPLY_POST_HOST_INDEX_OFFSET
6121                                  */
6122                                 for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) {
6123                                         instance->reply_post_host_index_addr[loop] =
6124                                                 (u32 __iomem *)
6125                                                 ((u8 __iomem *)instance->reg_set +
6126                                                 MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET
6127                                                 + (loop * 0x10));
6128                                 }
6129                         }
6130
6131                         dev_info(&instance->pdev->dev,
6132                                  "firmware supports msix\t: (%d)",
6133                                  instance->msix_vectors);
6134                         if (msix_vectors)
6135                                 instance->msix_vectors = min(msix_vectors,
6136                                         instance->msix_vectors);
6137                 } else /* MFI adapters */
6138                         instance->msix_vectors = 1;
6139
6140
6141                 /*
6142                  * For Aero (if some conditions are met), driver will configure a
6143                  * few additional reply queues with interrupt coalescing enabled.
6144                  * These queues with interrupt coalescing enabled are called
6145                  * High IOPS queues and rest of reply queues (based on number of
6146                  * logical CPUs) are termed as Low latency queues.
6147                  *
6148                  * Total Number of reply queues = High IOPS queues + low latency queues
6149                  *
6150                  * For rest of fusion adapters, 1 additional reply queue will be
6151                  * reserved for management commands, rest of reply queues
6152                  * (based on number of logical CPUs) will be used for IOs and
6153                  * referenced as IO queues.
6154                  * Total Number of reply queues = 1 + IO queues
6155                  *
6156                  * MFI adapters supports single MSI-x so single reply queue
6157                  * will be used for IO and management commands.
6158                  */
6159
6160                 intr_coalescing = (scratch_pad_1 & MR_INTR_COALESCING_SUPPORT_OFFSET) ?
6161                                                                 true : false;
6162                 if (intr_coalescing &&
6163                         (num_online_cpus() >= MR_HIGH_IOPS_QUEUE_COUNT) &&
6164                         (instance->msix_vectors == MEGASAS_MAX_MSIX_QUEUES))
6165                         instance->perf_mode = MR_BALANCED_PERF_MODE;
6166                 else
6167                         instance->perf_mode = MR_LATENCY_PERF_MODE;
6168
6169
6170                 if (instance->adapter_type == AERO_SERIES) {
6171                         pcie_capability_read_word(instance->pdev, PCI_EXP_LNKSTA, &lnksta);
6172                         speed = lnksta & PCI_EXP_LNKSTA_CLS;
6173
6174                         /*
6175                          * For Aero, if PCIe link speed is <16 GT/s, then driver should operate
6176                          * in latency perf mode and enable R1 PCI bandwidth algorithm
6177                          */
6178                         if (speed < 0x4) {
6179                                 instance->perf_mode = MR_LATENCY_PERF_MODE;
6180                                 fusion->pcie_bw_limitation = true;
6181                         }
6182
6183                         /*
6184                          * Performance mode settings provided through module parameter-perf_mode will
6185                          * take affect only for:
6186                          * 1. Aero family of adapters.
6187                          * 2. When user sets module parameter- perf_mode in range of 0-2.
6188                          */
6189                         if ((perf_mode >= MR_BALANCED_PERF_MODE) &&
6190                                 (perf_mode <= MR_LATENCY_PERF_MODE))
6191                                 instance->perf_mode = perf_mode;
6192                         /*
6193                          * If intr coalescing is not supported by controller FW, then IOPS
6194                          * and Balanced modes are not feasible.
6195                          */
6196                         if (!intr_coalescing)
6197                                 instance->perf_mode = MR_LATENCY_PERF_MODE;
6198
6199                 }
6200
6201                 if (instance->perf_mode == MR_BALANCED_PERF_MODE)
6202                         instance->low_latency_index_start =
6203                                 MR_HIGH_IOPS_QUEUE_COUNT;
6204                 else
6205                         instance->low_latency_index_start = 1;
6206
6207                 num_msix_req = num_online_cpus() + instance->low_latency_index_start;
6208
6209                 instance->msix_vectors = min(num_msix_req,
6210                                 instance->msix_vectors);
6211
6212                 megasas_alloc_irq_vectors(instance);
6213                 if (!instance->msix_vectors)
6214                         instance->msix_load_balance = false;
6215         }
6216         /*
6217          * MSI-X host index 0 is common for all adapter.
6218          * It is used for all MPT based Adapters.
6219          */
6220         if (instance->msix_combined) {
6221                 instance->reply_post_host_index_addr[0] =
6222                                 (u32 *)((u8 *)instance->reg_set +
6223                                 MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET);
6224         } else {
6225                 instance->reply_post_host_index_addr[0] =
6226                         (u32 *)((u8 *)instance->reg_set +
6227                         MPI2_REPLY_POST_HOST_INDEX_OFFSET);
6228         }
6229
6230         if (!instance->msix_vectors) {
6231                 i = pci_alloc_irq_vectors(instance->pdev, 1, 1, PCI_IRQ_LEGACY);
6232                 if (i < 0)
6233                         goto fail_init_adapter;
6234         }
6235
6236         megasas_setup_reply_map(instance);
6237
6238         dev_info(&instance->pdev->dev,
6239                 "current msix/online cpus\t: (%d/%d)\n",
6240                 instance->msix_vectors, (unsigned int)num_online_cpus());
6241         dev_info(&instance->pdev->dev,
6242                 "RDPQ mode\t: (%s)\n", instance->is_rdpq ? "enabled" : "disabled");
6243
6244         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
6245                 (unsigned long)instance);
6246
6247         /*
6248          * Below are default value for legacy Firmware.
6249          * non-fusion based controllers
6250          */
6251         instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
6252         instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
6253         /* Get operational params, sge flags, send init cmd to controller */
6254         if (instance->instancet->init_adapter(instance))
6255                 goto fail_init_adapter;
6256
6257         if (instance->adapter_type >= VENTURA_SERIES) {
6258                 scratch_pad_3 =
6259                         megasas_readl(instance,
6260                                       &instance->reg_set->outbound_scratch_pad_3);
6261                 if ((scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK) >=
6262                         MR_DEFAULT_NVME_PAGE_SHIFT)
6263                         instance->nvme_page_size =
6264                                 (1 << (scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK));
6265
6266                 dev_info(&instance->pdev->dev,
6267                          "NVME page size\t: (%d)\n", instance->nvme_page_size);
6268         }
6269
6270         if (instance->msix_vectors ?
6271                 megasas_setup_irqs_msix(instance, 1) :
6272                 megasas_setup_irqs_ioapic(instance))
6273                 goto fail_init_adapter;
6274
6275         if (instance->adapter_type != MFI_SERIES)
6276                 megasas_setup_irq_poll(instance);
6277
6278         instance->instancet->enable_intr(instance);
6279
6280         dev_info(&instance->pdev->dev, "INIT adapter done\n");
6281
6282         megasas_setup_jbod_map(instance);
6283
6284         if (megasas_get_device_list(instance) != SUCCESS) {
6285                 dev_err(&instance->pdev->dev,
6286                         "%s: megasas_get_device_list failed\n",
6287                         __func__);
6288                 goto fail_get_ld_pd_list;
6289         }
6290
6291         /* stream detection initialization */
6292         if (instance->adapter_type >= VENTURA_SERIES) {
6293                 fusion->stream_detect_by_ld =
6294                         kcalloc(MAX_LOGICAL_DRIVES_EXT,
6295                                 sizeof(struct LD_STREAM_DETECT *),
6296                                 GFP_KERNEL);
6297                 if (!fusion->stream_detect_by_ld) {
6298                         dev_err(&instance->pdev->dev,
6299                                 "unable to allocate stream detection for pool of LDs\n");
6300                         goto fail_get_ld_pd_list;
6301                 }
6302                 for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) {
6303                         fusion->stream_detect_by_ld[i] =
6304                                 kzalloc(sizeof(struct LD_STREAM_DETECT),
6305                                 GFP_KERNEL);
6306                         if (!fusion->stream_detect_by_ld[i]) {
6307                                 dev_err(&instance->pdev->dev,
6308                                         "unable to allocate stream detect by LD\n ");
6309                                 for (j = 0; j < i; ++j)
6310                                         kfree(fusion->stream_detect_by_ld[j]);
6311                                 kfree(fusion->stream_detect_by_ld);
6312                                 fusion->stream_detect_by_ld = NULL;
6313                                 goto fail_get_ld_pd_list;
6314                         }
6315                         fusion->stream_detect_by_ld[i]->mru_bit_map
6316                                 = MR_STREAM_BITMAP;
6317                 }
6318         }
6319
6320         /*
6321          * Compute the max allowed sectors per IO: The controller info has two
6322          * limits on max sectors. Driver should use the minimum of these two.
6323          *
6324          * 1 << stripe_sz_ops.min = max sectors per strip
6325          *
6326          * Note that older firmwares ( < FW ver 30) didn't report information
6327          * to calculate max_sectors_1. So the number ended up as zero always.
6328          */
6329         tmp_sectors = 0;
6330         ctrl_info = instance->ctrl_info_buf;
6331
6332         max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
6333                 le16_to_cpu(ctrl_info->max_strips_per_io);
6334         max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size);
6335
6336         tmp_sectors = min_t(u32, max_sectors_1, max_sectors_2);
6337
6338         instance->peerIsPresent = ctrl_info->cluster.peerIsPresent;
6339         instance->passive = ctrl_info->cluster.passive;
6340         memcpy(instance->clusterId, ctrl_info->clusterId, sizeof(instance->clusterId));
6341         instance->UnevenSpanSupport =
6342                 ctrl_info->adapterOperations2.supportUnevenSpans;
6343         if (instance->UnevenSpanSupport) {
6344                 struct fusion_context *fusion = instance->ctrl_context;
6345                 if (MR_ValidateMapInfo(instance, instance->map_id))
6346                         fusion->fast_path_io = 1;
6347                 else
6348                         fusion->fast_path_io = 0;
6349
6350         }
6351         if (ctrl_info->host_interface.SRIOV) {
6352                 instance->requestorId = ctrl_info->iov.requestorId;
6353                 if (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) {
6354                         if (!ctrl_info->adapterOperations2.activePassive)
6355                             instance->PlasmaFW111 = 1;
6356
6357                         dev_info(&instance->pdev->dev, "SR-IOV: firmware type: %s\n",
6358                             instance->PlasmaFW111 ? "1.11" : "new");
6359
6360                         if (instance->PlasmaFW111) {
6361                             iovPtr = (struct IOV_111 *)
6362                                 ((unsigned char *)ctrl_info + IOV_111_OFFSET);
6363                             instance->requestorId = iovPtr->requestorId;
6364                         }
6365                 }
6366                 dev_info(&instance->pdev->dev, "SRIOV: VF requestorId %d\n",
6367                         instance->requestorId);
6368         }
6369
6370         instance->crash_dump_fw_support =
6371                 ctrl_info->adapterOperations3.supportCrashDump;
6372         instance->crash_dump_drv_support =
6373                 (instance->crash_dump_fw_support &&
6374                 instance->crash_dump_buf);
6375         if (instance->crash_dump_drv_support)
6376                 megasas_set_crash_dump_params(instance,
6377                         MR_CRASH_BUF_TURN_OFF);
6378
6379         else {
6380                 if (instance->crash_dump_buf)
6381                         dma_free_coherent(&instance->pdev->dev,
6382                                 CRASH_DMA_BUF_SIZE,
6383                                 instance->crash_dump_buf,
6384                                 instance->crash_dump_h);
6385                 instance->crash_dump_buf = NULL;
6386         }
6387
6388         if (instance->snapdump_wait_time) {
6389                 megasas_get_snapdump_properties(instance);
6390                 dev_info(&instance->pdev->dev, "Snap dump wait time\t: %d\n",
6391                          instance->snapdump_wait_time);
6392         }
6393
6394         dev_info(&instance->pdev->dev,
6395                 "pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n",
6396                 le16_to_cpu(ctrl_info->pci.vendor_id),
6397                 le16_to_cpu(ctrl_info->pci.device_id),
6398                 le16_to_cpu(ctrl_info->pci.sub_vendor_id),
6399                 le16_to_cpu(ctrl_info->pci.sub_device_id));
6400         dev_info(&instance->pdev->dev, "unevenspan support      : %s\n",
6401                 instance->UnevenSpanSupport ? "yes" : "no");
6402         dev_info(&instance->pdev->dev, "firmware crash dump     : %s\n",
6403                 instance->crash_dump_drv_support ? "yes" : "no");
6404         dev_info(&instance->pdev->dev, "JBOD sequence map       : %s\n",
6405                 instance->use_seqnum_jbod_fp ? "enabled" : "disabled");
6406
6407         instance->max_sectors_per_req = instance->max_num_sge *
6408                                                 SGE_BUFFER_SIZE / 512;
6409         if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
6410                 instance->max_sectors_per_req = tmp_sectors;
6411
6412         /* Check for valid throttlequeuedepth module parameter */
6413         if (throttlequeuedepth &&
6414                         throttlequeuedepth <= instance->max_scsi_cmds)
6415                 instance->throttlequeuedepth = throttlequeuedepth;
6416         else
6417                 instance->throttlequeuedepth =
6418                                 MEGASAS_THROTTLE_QUEUE_DEPTH;
6419
6420         if ((resetwaittime < 1) ||
6421             (resetwaittime > MEGASAS_RESET_WAIT_TIME))
6422                 resetwaittime = MEGASAS_RESET_WAIT_TIME;
6423
6424         if ((scmd_timeout < 10) || (scmd_timeout > MEGASAS_DEFAULT_CMD_TIMEOUT))
6425                 scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT;
6426
6427         /* Launch SR-IOV heartbeat timer */
6428         if (instance->requestorId) {
6429                 if (!megasas_sriov_start_heartbeat(instance, 1)) {
6430                         megasas_start_timer(instance);
6431                 } else {
6432                         instance->skip_heartbeat_timer_del = 1;
6433                         goto fail_get_ld_pd_list;
6434                 }
6435         }
6436
6437         /*
6438          * Create and start watchdog thread which will monitor
6439          * controller state every 1 sec and trigger OCR when
6440          * it enters fault state
6441          */
6442         if (instance->adapter_type != MFI_SERIES)
6443                 if (megasas_fusion_start_watchdog(instance) != SUCCESS)
6444                         goto fail_start_watchdog;
6445
6446         return 0;
6447
6448 fail_start_watchdog:
6449         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
6450                 del_timer_sync(&instance->sriov_heartbeat_timer);
6451 fail_get_ld_pd_list:
6452         instance->instancet->disable_intr(instance);
6453         megasas_destroy_irqs(instance);
6454 fail_init_adapter:
6455         if (instance->msix_vectors)
6456                 pci_free_irq_vectors(instance->pdev);
6457         instance->msix_vectors = 0;
6458 fail_alloc_dma_buf:
6459         megasas_free_ctrl_dma_buffers(instance);
6460         megasas_free_ctrl_mem(instance);
6461 fail_ready_state:
6462         iounmap(instance->reg_set);
6463
6464 fail_ioremap:
6465         pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6466
6467         dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6468                 __func__, __LINE__);
6469         return -EINVAL;
6470 }
6471
6472 /**
6473  * megasas_release_mfi -        Reverses the FW initialization
6474  * @instance:                   Adapter soft state
6475  */
6476 static void megasas_release_mfi(struct megasas_instance *instance)
6477 {
6478         u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
6479
6480         if (instance->reply_queue)
6481                 dma_free_coherent(&instance->pdev->dev, reply_q_sz,
6482                             instance->reply_queue, instance->reply_queue_h);
6483
6484         megasas_free_cmds(instance);
6485
6486         iounmap(instance->reg_set);
6487
6488         pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6489 }
6490
6491 /**
6492  * megasas_get_seq_num -        Gets latest event sequence numbers
6493  * @instance:                   Adapter soft state
6494  * @eli:                        FW event log sequence numbers information
6495  *
6496  * FW maintains a log of all events in a non-volatile area. Upper layers would
6497  * usually find out the latest sequence number of the events, the seq number at
6498  * the boot etc. They would "read" all the events below the latest seq number
6499  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
6500  * number), they would subsribe to AEN (asynchronous event notification) and
6501  * wait for the events to happen.
6502  */
6503 static int
6504 megasas_get_seq_num(struct megasas_instance *instance,
6505                     struct megasas_evt_log_info *eli)
6506 {
6507         struct megasas_cmd *cmd;
6508         struct megasas_dcmd_frame *dcmd;
6509         struct megasas_evt_log_info *el_info;
6510         dma_addr_t el_info_h = 0;
6511         int ret;
6512
6513         cmd = megasas_get_cmd(instance);
6514
6515         if (!cmd) {
6516                 return -ENOMEM;
6517         }
6518
6519         dcmd = &cmd->frame->dcmd;
6520         el_info = dma_alloc_coherent(&instance->pdev->dev,
6521                                      sizeof(struct megasas_evt_log_info),
6522                                      &el_info_h, GFP_KERNEL);
6523         if (!el_info) {
6524                 megasas_return_cmd(instance, cmd);
6525                 return -ENOMEM;
6526         }
6527
6528         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6529
6530         dcmd->cmd = MFI_CMD_DCMD;
6531         dcmd->cmd_status = 0x0;
6532         dcmd->sge_count = 1;
6533         dcmd->flags = MFI_FRAME_DIR_READ;
6534         dcmd->timeout = 0;
6535         dcmd->pad_0 = 0;
6536         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_log_info));
6537         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_GET_INFO);
6538
6539         megasas_set_dma_settings(instance, dcmd, el_info_h,
6540                                  sizeof(struct megasas_evt_log_info));
6541
6542         ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
6543         if (ret != DCMD_SUCCESS) {
6544                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6545                         __func__, __LINE__);
6546                 goto dcmd_failed;
6547         }
6548
6549         /*
6550          * Copy the data back into callers buffer
6551          */
6552         eli->newest_seq_num = el_info->newest_seq_num;
6553         eli->oldest_seq_num = el_info->oldest_seq_num;
6554         eli->clear_seq_num = el_info->clear_seq_num;
6555         eli->shutdown_seq_num = el_info->shutdown_seq_num;
6556         eli->boot_seq_num = el_info->boot_seq_num;
6557
6558 dcmd_failed:
6559         dma_free_coherent(&instance->pdev->dev,
6560                         sizeof(struct megasas_evt_log_info),
6561                         el_info, el_info_h);
6562
6563         megasas_return_cmd(instance, cmd);
6564
6565         return ret;
6566 }
6567
6568 /**
6569  * megasas_register_aen -       Registers for asynchronous event notification
6570  * @instance:                   Adapter soft state
6571  * @seq_num:                    The starting sequence number
6572  * @class_locale_word:          Class of the event
6573  *
6574  * This function subscribes for AEN for events beyond the @seq_num. It requests
6575  * to be notified if and only if the event is of type @class_locale
6576  */
6577 static int
6578 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
6579                      u32 class_locale_word)
6580 {
6581         int ret_val;
6582         struct megasas_cmd *cmd;
6583         struct megasas_dcmd_frame *dcmd;
6584         union megasas_evt_class_locale curr_aen;
6585         union megasas_evt_class_locale prev_aen;
6586
6587         /*
6588          * If there an AEN pending already (aen_cmd), check if the
6589          * class_locale of that pending AEN is inclusive of the new
6590          * AEN request we currently have. If it is, then we don't have
6591          * to do anything. In other words, whichever events the current
6592          * AEN request is subscribing to, have already been subscribed
6593          * to.
6594          *
6595          * If the old_cmd is _not_ inclusive, then we have to abort
6596          * that command, form a class_locale that is superset of both
6597          * old and current and re-issue to the FW
6598          */
6599
6600         curr_aen.word = class_locale_word;
6601
6602         if (instance->aen_cmd) {
6603
6604                 prev_aen.word =
6605                         le32_to_cpu(instance->aen_cmd->frame->dcmd.mbox.w[1]);
6606
6607                 if ((curr_aen.members.class < MFI_EVT_CLASS_DEBUG) ||
6608                     (curr_aen.members.class > MFI_EVT_CLASS_DEAD)) {
6609                         dev_info(&instance->pdev->dev,
6610                                  "%s %d out of range class %d send by application\n",
6611                                  __func__, __LINE__, curr_aen.members.class);
6612                         return 0;
6613                 }
6614
6615                 /*
6616                  * A class whose enum value is smaller is inclusive of all
6617                  * higher values. If a PROGRESS (= -1) was previously
6618                  * registered, then a new registration requests for higher
6619                  * classes need not be sent to FW. They are automatically
6620                  * included.
6621                  *
6622                  * Locale numbers don't have such hierarchy. They are bitmap
6623                  * values
6624                  */
6625                 if ((prev_aen.members.class <= curr_aen.members.class) &&
6626                     !((prev_aen.members.locale & curr_aen.members.locale) ^
6627                       curr_aen.members.locale)) {
6628                         /*
6629                          * Previously issued event registration includes
6630                          * current request. Nothing to do.
6631                          */
6632                         return 0;
6633                 } else {
6634                         curr_aen.members.locale |= prev_aen.members.locale;
6635
6636                         if (prev_aen.members.class < curr_aen.members.class)
6637                                 curr_aen.members.class = prev_aen.members.class;
6638
6639                         instance->aen_cmd->abort_aen = 1;
6640                         ret_val = megasas_issue_blocked_abort_cmd(instance,
6641                                                                   instance->
6642                                                                   aen_cmd, 30);
6643
6644                         if (ret_val) {
6645                                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to abort "
6646                                        "previous AEN command\n");
6647                                 return ret_val;
6648                         }
6649                 }
6650         }
6651
6652         cmd = megasas_get_cmd(instance);
6653
6654         if (!cmd)
6655                 return -ENOMEM;
6656
6657         dcmd = &cmd->frame->dcmd;
6658
6659         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
6660
6661         /*
6662          * Prepare DCMD for aen registration
6663          */
6664         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6665
6666         dcmd->cmd = MFI_CMD_DCMD;
6667         dcmd->cmd_status = 0x0;
6668         dcmd->sge_count = 1;
6669         dcmd->flags = MFI_FRAME_DIR_READ;
6670         dcmd->timeout = 0;
6671         dcmd->pad_0 = 0;
6672         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_detail));
6673         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_WAIT);
6674         dcmd->mbox.w[0] = cpu_to_le32(seq_num);
6675         instance->last_seq_num = seq_num;
6676         dcmd->mbox.w[1] = cpu_to_le32(curr_aen.word);
6677
6678         megasas_set_dma_settings(instance, dcmd, instance->evt_detail_h,
6679                                  sizeof(struct megasas_evt_detail));
6680
6681         if (instance->aen_cmd != NULL) {
6682                 megasas_return_cmd(instance, cmd);
6683                 return 0;
6684         }
6685
6686         /*
6687          * Store reference to the cmd used to register for AEN. When an
6688          * application wants us to register for AEN, we have to abort this
6689          * cmd and re-register with a new EVENT LOCALE supplied by that app
6690          */
6691         instance->aen_cmd = cmd;
6692
6693         /*
6694          * Issue the aen registration frame
6695          */
6696         instance->instancet->issue_dcmd(instance, cmd);
6697
6698         return 0;
6699 }
6700
6701 /* megasas_get_target_prop - Send DCMD with below details to firmware.
6702  *
6703  * This DCMD will fetch few properties of LD/system PD defined
6704  * in MR_TARGET_DEV_PROPERTIES. eg. Queue Depth, MDTS value.
6705  *
6706  * DCMD send by drivers whenever new target is added to the OS.
6707  *
6708  * dcmd.opcode         - MR_DCMD_DEV_GET_TARGET_PROP
6709  * dcmd.mbox.b[0]      - DCMD is to be fired for LD or system PD.
6710  *                       0 = system PD, 1 = LD.
6711  * dcmd.mbox.s[1]      - TargetID for LD/system PD.
6712  * dcmd.sge IN         - Pointer to return MR_TARGET_DEV_PROPERTIES.
6713  *
6714  * @instance:           Adapter soft state
6715  * @sdev:               OS provided scsi device
6716  *
6717  * Returns 0 on success non-zero on failure.
6718  */
6719 int
6720 megasas_get_target_prop(struct megasas_instance *instance,
6721                         struct scsi_device *sdev)
6722 {
6723         int ret;
6724         struct megasas_cmd *cmd;
6725         struct megasas_dcmd_frame *dcmd;
6726         u16 targetId = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL) +
6727                         sdev->id;
6728
6729         cmd = megasas_get_cmd(instance);
6730
6731         if (!cmd) {
6732                 dev_err(&instance->pdev->dev,
6733                         "Failed to get cmd %s\n", __func__);
6734                 return -ENOMEM;
6735         }
6736
6737         dcmd = &cmd->frame->dcmd;
6738
6739         memset(instance->tgt_prop, 0, sizeof(*instance->tgt_prop));
6740         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6741         dcmd->mbox.b[0] = MEGASAS_IS_LOGICAL(sdev);
6742
6743         dcmd->mbox.s[1] = cpu_to_le16(targetId);
6744         dcmd->cmd = MFI_CMD_DCMD;
6745         dcmd->cmd_status = 0xFF;
6746         dcmd->sge_count = 1;
6747         dcmd->flags = MFI_FRAME_DIR_READ;
6748         dcmd->timeout = 0;
6749         dcmd->pad_0 = 0;
6750         dcmd->data_xfer_len =
6751                 cpu_to_le32(sizeof(struct MR_TARGET_PROPERTIES));
6752         dcmd->opcode = cpu_to_le32(MR_DCMD_DRV_GET_TARGET_PROP);
6753
6754         megasas_set_dma_settings(instance, dcmd, instance->tgt_prop_h,
6755                                  sizeof(struct MR_TARGET_PROPERTIES));
6756
6757         if ((instance->adapter_type != MFI_SERIES) &&
6758             !instance->mask_interrupts)
6759                 ret = megasas_issue_blocked_cmd(instance,
6760                                                 cmd, MFI_IO_TIMEOUT_SECS);
6761         else
6762                 ret = megasas_issue_polled(instance, cmd);
6763
6764         switch (ret) {
6765         case DCMD_TIMEOUT:
6766                 switch (dcmd_timeout_ocr_possible(instance)) {
6767                 case INITIATE_OCR:
6768                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
6769                         mutex_unlock(&instance->reset_mutex);
6770                         megasas_reset_fusion(instance->host,
6771                                              MFI_IO_TIMEOUT_OCR);
6772                         mutex_lock(&instance->reset_mutex);
6773                         break;
6774                 case KILL_ADAPTER:
6775                         megaraid_sas_kill_hba(instance);
6776                         break;
6777                 case IGNORE_TIMEOUT:
6778                         dev_info(&instance->pdev->dev,
6779                                  "Ignore DCMD timeout: %s %d\n",
6780                                  __func__, __LINE__);
6781                         break;
6782                 }
6783                 break;
6784
6785         default:
6786                 megasas_return_cmd(instance, cmd);
6787         }
6788         if (ret != DCMD_SUCCESS)
6789                 dev_err(&instance->pdev->dev,
6790                         "return from %s %d return value %d\n",
6791                         __func__, __LINE__, ret);
6792
6793         return ret;
6794 }
6795
6796 /**
6797  * megasas_start_aen -  Subscribes to AEN during driver load time
6798  * @instance:           Adapter soft state
6799  */
6800 static int megasas_start_aen(struct megasas_instance *instance)
6801 {
6802         struct megasas_evt_log_info eli;
6803         union megasas_evt_class_locale class_locale;
6804
6805         /*
6806          * Get the latest sequence number from FW
6807          */
6808         memset(&eli, 0, sizeof(eli));
6809
6810         if (megasas_get_seq_num(instance, &eli))
6811                 return -1;
6812
6813         /*
6814          * Register AEN with FW for latest sequence number plus 1
6815          */
6816         class_locale.members.reserved = 0;
6817         class_locale.members.locale = MR_EVT_LOCALE_ALL;
6818         class_locale.members.class = MR_EVT_CLASS_DEBUG;
6819
6820         return megasas_register_aen(instance,
6821                         le32_to_cpu(eli.newest_seq_num) + 1,
6822                         class_locale.word);
6823 }
6824
6825 /**
6826  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
6827  * @instance:           Adapter soft state
6828  */
6829 static int megasas_io_attach(struct megasas_instance *instance)
6830 {
6831         struct Scsi_Host *host = instance->host;
6832
6833         /*
6834          * Export parameters required by SCSI mid-layer
6835          */
6836         host->unique_id = instance->unique_id;
6837         host->can_queue = instance->max_scsi_cmds;
6838         host->this_id = instance->init_id;
6839         host->sg_tablesize = instance->max_num_sge;
6840
6841         if (instance->fw_support_ieee)
6842                 instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
6843
6844         /*
6845          * Check if the module parameter value for max_sectors can be used
6846          */
6847         if (max_sectors && max_sectors < instance->max_sectors_per_req)
6848                 instance->max_sectors_per_req = max_sectors;
6849         else {
6850                 if (max_sectors) {
6851                         if (((instance->pdev->device ==
6852                                 PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
6853                                 (instance->pdev->device ==
6854                                 PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
6855                                 (max_sectors <= MEGASAS_MAX_SECTORS)) {
6856                                 instance->max_sectors_per_req = max_sectors;
6857                         } else {
6858                         dev_info(&instance->pdev->dev, "max_sectors should be > 0"
6859                                 "and <= %d (or < 1MB for GEN2 controller)\n",
6860                                 instance->max_sectors_per_req);
6861                         }
6862                 }
6863         }
6864
6865         host->max_sectors = instance->max_sectors_per_req;
6866         host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
6867         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
6868         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
6869         host->max_lun = MEGASAS_MAX_LUN;
6870         host->max_cmd_len = 16;
6871
6872         /*
6873          * Notify the mid-layer about the new controller
6874          */
6875         if (scsi_add_host(host, &instance->pdev->dev)) {
6876                 dev_err(&instance->pdev->dev,
6877                         "Failed to add host from %s %d\n",
6878                         __func__, __LINE__);
6879                 return -ENODEV;
6880         }
6881
6882         return 0;
6883 }
6884
6885 /**
6886  * megasas_set_dma_mask -       Set DMA mask for supported controllers
6887  *
6888  * @instance:           Adapter soft state
6889  * Description:
6890  *
6891  * For Ventura, driver/FW will operate in 63bit DMA addresses.
6892  *
6893  * For invader-
6894  *      By default, driver/FW will operate in 32bit DMA addresses
6895  *      for consistent DMA mapping but if 32 bit consistent
6896  *      DMA mask fails, driver will try with 63 bit consistent
6897  *      mask provided FW is true 63bit DMA capable
6898  *
6899  * For older controllers(Thunderbolt and MFI based adapters)-
6900  *      driver/FW will operate in 32 bit consistent DMA addresses.
6901  */
6902 static int
6903 megasas_set_dma_mask(struct megasas_instance *instance)
6904 {
6905         u64 consistent_mask;
6906         struct pci_dev *pdev;
6907         u32 scratch_pad_1;
6908
6909         pdev = instance->pdev;
6910         consistent_mask = (instance->adapter_type >= VENTURA_SERIES) ?
6911                                 DMA_BIT_MASK(63) : DMA_BIT_MASK(32);
6912
6913         if (IS_DMA64) {
6914                 if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(63)) &&
6915                     dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
6916                         goto fail_set_dma_mask;
6917
6918                 if ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) &&
6919                     (dma_set_coherent_mask(&pdev->dev, consistent_mask) &&
6920                      dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))) {
6921                         /*
6922                          * If 32 bit DMA mask fails, then try for 64 bit mask
6923                          * for FW capable of handling 64 bit DMA.
6924                          */
6925                         scratch_pad_1 = megasas_readl
6926                                 (instance, &instance->reg_set->outbound_scratch_pad_1);
6927
6928                         if (!(scratch_pad_1 & MR_CAN_HANDLE_64_BIT_DMA_OFFSET))
6929                                 goto fail_set_dma_mask;
6930                         else if (dma_set_mask_and_coherent(&pdev->dev,
6931                                                            DMA_BIT_MASK(63)))
6932                                 goto fail_set_dma_mask;
6933                 }
6934         } else if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
6935                 goto fail_set_dma_mask;
6936
6937         if (pdev->dev.coherent_dma_mask == DMA_BIT_MASK(32))
6938                 instance->consistent_mask_64bit = false;
6939         else
6940                 instance->consistent_mask_64bit = true;
6941
6942         dev_info(&pdev->dev, "%s bit DMA mask and %s bit consistent mask\n",
6943                  ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) ? "63" : "32"),
6944                  (instance->consistent_mask_64bit ? "63" : "32"));
6945
6946         return 0;
6947
6948 fail_set_dma_mask:
6949         dev_err(&pdev->dev, "Failed to set DMA mask\n");
6950         return -1;
6951
6952 }
6953
6954 /*
6955  * megasas_set_adapter_type -   Set adapter type.
6956  *                              Supported controllers can be divided in
6957  *                              different categories-
6958  *                                      enum MR_ADAPTER_TYPE {
6959  *                                              MFI_SERIES = 1,
6960  *                                              THUNDERBOLT_SERIES = 2,
6961  *                                              INVADER_SERIES = 3,
6962  *                                              VENTURA_SERIES = 4,
6963  *                                              AERO_SERIES = 5,
6964  *                                      };
6965  * @instance:                   Adapter soft state
6966  * return:                      void
6967  */
6968 static inline void megasas_set_adapter_type(struct megasas_instance *instance)
6969 {
6970         if ((instance->pdev->vendor == PCI_VENDOR_ID_DELL) &&
6971             (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5)) {
6972                 instance->adapter_type = MFI_SERIES;
6973         } else {
6974                 switch (instance->pdev->device) {
6975                 case PCI_DEVICE_ID_LSI_AERO_10E1:
6976                 case PCI_DEVICE_ID_LSI_AERO_10E2:
6977                 case PCI_DEVICE_ID_LSI_AERO_10E5:
6978                 case PCI_DEVICE_ID_LSI_AERO_10E6:
6979                         instance->adapter_type = AERO_SERIES;
6980                         break;
6981                 case PCI_DEVICE_ID_LSI_VENTURA:
6982                 case PCI_DEVICE_ID_LSI_CRUSADER:
6983                 case PCI_DEVICE_ID_LSI_HARPOON:
6984                 case PCI_DEVICE_ID_LSI_TOMCAT:
6985                 case PCI_DEVICE_ID_LSI_VENTURA_4PORT:
6986                 case PCI_DEVICE_ID_LSI_CRUSADER_4PORT:
6987                         instance->adapter_type = VENTURA_SERIES;
6988                         break;
6989                 case PCI_DEVICE_ID_LSI_FUSION:
6990                 case PCI_DEVICE_ID_LSI_PLASMA:
6991                         instance->adapter_type = THUNDERBOLT_SERIES;
6992                         break;
6993                 case PCI_DEVICE_ID_LSI_INVADER:
6994                 case PCI_DEVICE_ID_LSI_INTRUDER:
6995                 case PCI_DEVICE_ID_LSI_INTRUDER_24:
6996                 case PCI_DEVICE_ID_LSI_CUTLASS_52:
6997                 case PCI_DEVICE_ID_LSI_CUTLASS_53:
6998                 case PCI_DEVICE_ID_LSI_FURY:
6999                         instance->adapter_type = INVADER_SERIES;
7000                         break;
7001                 default: /* For all other supported controllers */
7002                         instance->adapter_type = MFI_SERIES;
7003                         break;
7004                 }
7005         }
7006 }
7007
7008 static inline int megasas_alloc_mfi_ctrl_mem(struct megasas_instance *instance)
7009 {
7010         instance->producer = dma_alloc_coherent(&instance->pdev->dev,
7011                         sizeof(u32), &instance->producer_h, GFP_KERNEL);
7012         instance->consumer = dma_alloc_coherent(&instance->pdev->dev,
7013                         sizeof(u32), &instance->consumer_h, GFP_KERNEL);
7014
7015         if (!instance->producer || !instance->consumer) {
7016                 dev_err(&instance->pdev->dev,
7017                         "Failed to allocate memory for producer, consumer\n");
7018                 return -1;
7019         }
7020
7021         *instance->producer = 0;
7022         *instance->consumer = 0;
7023         return 0;
7024 }
7025
7026 /**
7027  * megasas_alloc_ctrl_mem -     Allocate per controller memory for core data
7028  *                              structures which are not common across MFI
7029  *                              adapters and fusion adapters.
7030  *                              For MFI based adapters, allocate producer and
7031  *                              consumer buffers. For fusion adapters, allocate
7032  *                              memory for fusion context.
7033  * @instance:                   Adapter soft state
7034  * return:                      0 for SUCCESS
7035  */
7036 static int megasas_alloc_ctrl_mem(struct megasas_instance *instance)
7037 {
7038         instance->reply_map = kcalloc(nr_cpu_ids, sizeof(unsigned int),
7039                                       GFP_KERNEL);
7040         if (!instance->reply_map)
7041                 return -ENOMEM;
7042
7043         switch (instance->adapter_type) {
7044         case MFI_SERIES:
7045                 if (megasas_alloc_mfi_ctrl_mem(instance))
7046                         goto fail;
7047                 break;
7048         case AERO_SERIES:
7049         case VENTURA_SERIES:
7050         case THUNDERBOLT_SERIES:
7051         case INVADER_SERIES:
7052                 if (megasas_alloc_fusion_context(instance))
7053                         goto fail;
7054                 break;
7055         }
7056
7057         return 0;
7058  fail:
7059         kfree(instance->reply_map);
7060         instance->reply_map = NULL;
7061         return -ENOMEM;
7062 }
7063
7064 /*
7065  * megasas_free_ctrl_mem -      Free fusion context for fusion adapters and
7066  *                              producer, consumer buffers for MFI adapters
7067  *
7068  * @instance -                  Adapter soft instance
7069  *
7070  */
7071 static inline void megasas_free_ctrl_mem(struct megasas_instance *instance)
7072 {
7073         kfree(instance->reply_map);
7074         if (instance->adapter_type == MFI_SERIES) {
7075                 if (instance->producer)
7076                         dma_free_coherent(&instance->pdev->dev, sizeof(u32),
7077                                             instance->producer,
7078                                             instance->producer_h);
7079                 if (instance->consumer)
7080                         dma_free_coherent(&instance->pdev->dev, sizeof(u32),
7081                                             instance->consumer,
7082                                             instance->consumer_h);
7083         } else {
7084                 megasas_free_fusion_context(instance);
7085         }
7086 }
7087
7088 /**
7089  * megasas_alloc_ctrl_dma_buffers -     Allocate consistent DMA buffers during
7090  *                                      driver load time
7091  *
7092  * @instance:                           Adapter soft instance
7093  *
7094  * @return:                             O for SUCCESS
7095  */
7096 static inline
7097 int megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance)
7098 {
7099         struct pci_dev *pdev = instance->pdev;
7100         struct fusion_context *fusion = instance->ctrl_context;
7101
7102         instance->evt_detail = dma_alloc_coherent(&pdev->dev,
7103                         sizeof(struct megasas_evt_detail),
7104                         &instance->evt_detail_h, GFP_KERNEL);
7105
7106         if (!instance->evt_detail) {
7107                 dev_err(&instance->pdev->dev,
7108                         "Failed to allocate event detail buffer\n");
7109                 return -ENOMEM;
7110         }
7111
7112         if (fusion) {
7113                 fusion->ioc_init_request =
7114                         dma_alloc_coherent(&pdev->dev,
7115                                            sizeof(struct MPI2_IOC_INIT_REQUEST),
7116                                            &fusion->ioc_init_request_phys,
7117                                            GFP_KERNEL);
7118
7119                 if (!fusion->ioc_init_request) {
7120                         dev_err(&pdev->dev,
7121                                 "Failed to allocate PD list buffer\n");
7122                         return -ENOMEM;
7123                 }
7124
7125                 instance->snapdump_prop = dma_alloc_coherent(&pdev->dev,
7126                                 sizeof(struct MR_SNAPDUMP_PROPERTIES),
7127                                 &instance->snapdump_prop_h, GFP_KERNEL);
7128
7129                 if (!instance->snapdump_prop)
7130                         dev_err(&pdev->dev,
7131                                 "Failed to allocate snapdump properties buffer\n");
7132
7133                 instance->host_device_list_buf = dma_alloc_coherent(&pdev->dev,
7134                                                         HOST_DEVICE_LIST_SZ,
7135                                                         &instance->host_device_list_buf_h,
7136                                                         GFP_KERNEL);
7137
7138                 if (!instance->host_device_list_buf) {
7139                         dev_err(&pdev->dev,
7140                                 "Failed to allocate targetid list buffer\n");
7141                         return -ENOMEM;
7142                 }
7143
7144         }
7145
7146         instance->pd_list_buf =
7147                 dma_alloc_coherent(&pdev->dev,
7148                                      MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
7149                                      &instance->pd_list_buf_h, GFP_KERNEL);
7150
7151         if (!instance->pd_list_buf) {
7152                 dev_err(&pdev->dev, "Failed to allocate PD list buffer\n");
7153                 return -ENOMEM;
7154         }
7155
7156         instance->ctrl_info_buf =
7157                 dma_alloc_coherent(&pdev->dev,
7158                                      sizeof(struct megasas_ctrl_info),
7159                                      &instance->ctrl_info_buf_h, GFP_KERNEL);
7160
7161         if (!instance->ctrl_info_buf) {
7162                 dev_err(&pdev->dev,
7163                         "Failed to allocate controller info buffer\n");
7164                 return -ENOMEM;
7165         }
7166
7167         instance->ld_list_buf =
7168                 dma_alloc_coherent(&pdev->dev,
7169                                      sizeof(struct MR_LD_LIST),
7170                                      &instance->ld_list_buf_h, GFP_KERNEL);
7171
7172         if (!instance->ld_list_buf) {
7173                 dev_err(&pdev->dev, "Failed to allocate LD list buffer\n");
7174                 return -ENOMEM;
7175         }
7176
7177         instance->ld_targetid_list_buf =
7178                 dma_alloc_coherent(&pdev->dev,
7179                                 sizeof(struct MR_LD_TARGETID_LIST),
7180                                 &instance->ld_targetid_list_buf_h, GFP_KERNEL);
7181
7182         if (!instance->ld_targetid_list_buf) {
7183                 dev_err(&pdev->dev,
7184                         "Failed to allocate LD targetid list buffer\n");
7185                 return -ENOMEM;
7186         }
7187
7188         if (!reset_devices) {
7189                 instance->system_info_buf =
7190                         dma_alloc_coherent(&pdev->dev,
7191                                         sizeof(struct MR_DRV_SYSTEM_INFO),
7192                                         &instance->system_info_h, GFP_KERNEL);
7193                 instance->pd_info =
7194                         dma_alloc_coherent(&pdev->dev,
7195                                         sizeof(struct MR_PD_INFO),
7196                                         &instance->pd_info_h, GFP_KERNEL);
7197                 instance->tgt_prop =
7198                         dma_alloc_coherent(&pdev->dev,
7199                                         sizeof(struct MR_TARGET_PROPERTIES),
7200                                         &instance->tgt_prop_h, GFP_KERNEL);
7201                 instance->crash_dump_buf =
7202                         dma_alloc_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
7203                                         &instance->crash_dump_h, GFP_KERNEL);
7204
7205                 if (!instance->system_info_buf)
7206                         dev_err(&instance->pdev->dev,
7207                                 "Failed to allocate system info buffer\n");
7208
7209                 if (!instance->pd_info)
7210                         dev_err(&instance->pdev->dev,
7211                                 "Failed to allocate pd_info buffer\n");
7212
7213                 if (!instance->tgt_prop)
7214                         dev_err(&instance->pdev->dev,
7215                                 "Failed to allocate tgt_prop buffer\n");
7216
7217                 if (!instance->crash_dump_buf)
7218                         dev_err(&instance->pdev->dev,
7219                                 "Failed to allocate crash dump buffer\n");
7220         }
7221
7222         return 0;
7223 }
7224
7225 /*
7226  * megasas_free_ctrl_dma_buffers -      Free consistent DMA buffers allocated
7227  *                                      during driver load time
7228  *
7229  * @instance-                           Adapter soft instance
7230  *
7231  */
7232 static inline
7233 void megasas_free_ctrl_dma_buffers(struct megasas_instance *instance)
7234 {
7235         struct pci_dev *pdev = instance->pdev;
7236         struct fusion_context *fusion = instance->ctrl_context;
7237
7238         if (instance->evt_detail)
7239                 dma_free_coherent(&pdev->dev, sizeof(struct megasas_evt_detail),
7240                                     instance->evt_detail,
7241                                     instance->evt_detail_h);
7242
7243         if (fusion && fusion->ioc_init_request)
7244                 dma_free_coherent(&pdev->dev,
7245                                   sizeof(struct MPI2_IOC_INIT_REQUEST),
7246                                   fusion->ioc_init_request,
7247                                   fusion->ioc_init_request_phys);
7248
7249         if (instance->pd_list_buf)
7250                 dma_free_coherent(&pdev->dev,
7251                                     MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
7252                                     instance->pd_list_buf,
7253                                     instance->pd_list_buf_h);
7254
7255         if (instance->ld_list_buf)
7256                 dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_LIST),
7257                                     instance->ld_list_buf,
7258                                     instance->ld_list_buf_h);
7259
7260         if (instance->ld_targetid_list_buf)
7261                 dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_TARGETID_LIST),
7262                                     instance->ld_targetid_list_buf,
7263                                     instance->ld_targetid_list_buf_h);
7264
7265         if (instance->ctrl_info_buf)
7266                 dma_free_coherent(&pdev->dev, sizeof(struct megasas_ctrl_info),
7267                                     instance->ctrl_info_buf,
7268                                     instance->ctrl_info_buf_h);
7269
7270         if (instance->system_info_buf)
7271                 dma_free_coherent(&pdev->dev, sizeof(struct MR_DRV_SYSTEM_INFO),
7272                                     instance->system_info_buf,
7273                                     instance->system_info_h);
7274
7275         if (instance->pd_info)
7276                 dma_free_coherent(&pdev->dev, sizeof(struct MR_PD_INFO),
7277                                     instance->pd_info, instance->pd_info_h);
7278
7279         if (instance->tgt_prop)
7280                 dma_free_coherent(&pdev->dev, sizeof(struct MR_TARGET_PROPERTIES),
7281                                     instance->tgt_prop, instance->tgt_prop_h);
7282
7283         if (instance->crash_dump_buf)
7284                 dma_free_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
7285                                     instance->crash_dump_buf,
7286                                     instance->crash_dump_h);
7287
7288         if (instance->snapdump_prop)
7289                 dma_free_coherent(&pdev->dev,
7290                                   sizeof(struct MR_SNAPDUMP_PROPERTIES),
7291                                   instance->snapdump_prop,
7292                                   instance->snapdump_prop_h);
7293
7294         if (instance->host_device_list_buf)
7295                 dma_free_coherent(&pdev->dev,
7296                                   HOST_DEVICE_LIST_SZ,
7297                                   instance->host_device_list_buf,
7298                                   instance->host_device_list_buf_h);
7299
7300 }
7301
7302 /*
7303  * megasas_init_ctrl_params -           Initialize controller's instance
7304  *                                      parameters before FW init
7305  * @instance -                          Adapter soft instance
7306  * @return -                            void
7307  */
7308 static inline void megasas_init_ctrl_params(struct megasas_instance *instance)
7309 {
7310         instance->fw_crash_state = UNAVAILABLE;
7311
7312         megasas_poll_wait_aen = 0;
7313         instance->issuepend_done = 1;
7314         atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
7315
7316         /*
7317          * Initialize locks and queues
7318          */
7319         INIT_LIST_HEAD(&instance->cmd_pool);
7320         INIT_LIST_HEAD(&instance->internal_reset_pending_q);
7321
7322         atomic_set(&instance->fw_outstanding, 0);
7323         atomic64_set(&instance->total_io_count, 0);
7324
7325         init_waitqueue_head(&instance->int_cmd_wait_q);
7326         init_waitqueue_head(&instance->abort_cmd_wait_q);
7327
7328         spin_lock_init(&instance->crashdump_lock);
7329         spin_lock_init(&instance->mfi_pool_lock);
7330         spin_lock_init(&instance->hba_lock);
7331         spin_lock_init(&instance->stream_lock);
7332         spin_lock_init(&instance->completion_lock);
7333
7334         mutex_init(&instance->reset_mutex);
7335
7336         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
7337             (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY))
7338                 instance->flag_ieee = 1;
7339
7340         megasas_dbg_lvl = 0;
7341         instance->flag = 0;
7342         instance->unload = 1;
7343         instance->last_time = 0;
7344         instance->disableOnlineCtrlReset = 1;
7345         instance->UnevenSpanSupport = 0;
7346         instance->smp_affinity_enable = smp_affinity_enable ? true : false;
7347         instance->msix_load_balance = false;
7348
7349         if (instance->adapter_type != MFI_SERIES)
7350                 INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
7351         else
7352                 INIT_WORK(&instance->work_init, process_fw_state_change_wq);
7353 }
7354
7355 /**
7356  * megasas_probe_one -  PCI hotplug entry point
7357  * @pdev:               PCI device structure
7358  * @id:                 PCI ids of supported hotplugged adapter
7359  */
7360 static int megasas_probe_one(struct pci_dev *pdev,
7361                              const struct pci_device_id *id)
7362 {
7363         int rval, pos;
7364         struct Scsi_Host *host;
7365         struct megasas_instance *instance;
7366         u16 control = 0;
7367
7368         switch (pdev->device) {
7369         case PCI_DEVICE_ID_LSI_AERO_10E0:
7370         case PCI_DEVICE_ID_LSI_AERO_10E3:
7371         case PCI_DEVICE_ID_LSI_AERO_10E4:
7372         case PCI_DEVICE_ID_LSI_AERO_10E7:
7373                 dev_err(&pdev->dev, "Adapter is in non secure mode\n");
7374                 return 1;
7375         case PCI_DEVICE_ID_LSI_AERO_10E1:
7376         case PCI_DEVICE_ID_LSI_AERO_10E5:
7377                 dev_info(&pdev->dev, "Adapter is in configurable secure mode\n");
7378                 break;
7379         }
7380
7381         /* Reset MSI-X in the kdump kernel */
7382         if (reset_devices) {
7383                 pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
7384                 if (pos) {
7385                         pci_read_config_word(pdev, pos + PCI_MSIX_FLAGS,
7386                                              &control);
7387                         if (control & PCI_MSIX_FLAGS_ENABLE) {
7388                                 dev_info(&pdev->dev, "resetting MSI-X\n");
7389                                 pci_write_config_word(pdev,
7390                                                       pos + PCI_MSIX_FLAGS,
7391                                                       control &
7392                                                       ~PCI_MSIX_FLAGS_ENABLE);
7393                         }
7394                 }
7395         }
7396
7397         /*
7398          * PCI prepping: enable device set bus mastering and dma mask
7399          */
7400         rval = pci_enable_device_mem(pdev);
7401
7402         if (rval) {
7403                 return rval;
7404         }
7405
7406         pci_set_master(pdev);
7407
7408         host = scsi_host_alloc(&megasas_template,
7409                                sizeof(struct megasas_instance));
7410
7411         if (!host) {
7412                 dev_printk(KERN_DEBUG, &pdev->dev, "scsi_host_alloc failed\n");
7413                 goto fail_alloc_instance;
7414         }
7415
7416         instance = (struct megasas_instance *)host->hostdata;
7417         memset(instance, 0, sizeof(*instance));
7418         atomic_set(&instance->fw_reset_no_pci_access, 0);
7419
7420         /*
7421          * Initialize PCI related and misc parameters
7422          */
7423         instance->pdev = pdev;
7424         instance->host = host;
7425         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
7426         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
7427
7428         megasas_set_adapter_type(instance);
7429
7430         /*
7431          * Initialize MFI Firmware
7432          */
7433         if (megasas_init_fw(instance))
7434                 goto fail_init_mfi;
7435
7436         if (instance->requestorId) {
7437                 if (instance->PlasmaFW111) {
7438                         instance->vf_affiliation_111 =
7439                                 dma_alloc_coherent(&pdev->dev,
7440                                         sizeof(struct MR_LD_VF_AFFILIATION_111),
7441                                         &instance->vf_affiliation_111_h,
7442                                         GFP_KERNEL);
7443                         if (!instance->vf_affiliation_111)
7444                                 dev_warn(&pdev->dev, "Can't allocate "
7445                                        "memory for VF affiliation buffer\n");
7446                 } else {
7447                         instance->vf_affiliation =
7448                                 dma_alloc_coherent(&pdev->dev,
7449                                         (MAX_LOGICAL_DRIVES + 1) *
7450                                         sizeof(struct MR_LD_VF_AFFILIATION),
7451                                         &instance->vf_affiliation_h,
7452                                         GFP_KERNEL);
7453                         if (!instance->vf_affiliation)
7454                                 dev_warn(&pdev->dev, "Can't allocate "
7455                                        "memory for VF affiliation buffer\n");
7456                 }
7457         }
7458
7459         /*
7460          * Store instance in PCI softstate
7461          */
7462         pci_set_drvdata(pdev, instance);
7463
7464         /*
7465          * Add this controller to megasas_mgmt_info structure so that it
7466          * can be exported to management applications
7467          */
7468         megasas_mgmt_info.count++;
7469         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
7470         megasas_mgmt_info.max_index++;
7471
7472         /*
7473          * Register with SCSI mid-layer
7474          */
7475         if (megasas_io_attach(instance))
7476                 goto fail_io_attach;
7477
7478         instance->unload = 0;
7479         /*
7480          * Trigger SCSI to scan our drives
7481          */
7482         if (!instance->enable_fw_dev_list ||
7483             (instance->host_device_list_buf->count > 0))
7484                 scsi_scan_host(host);
7485
7486         /*
7487          * Initiate AEN (Asynchronous Event Notification)
7488          */
7489         if (megasas_start_aen(instance)) {
7490                 dev_printk(KERN_DEBUG, &pdev->dev, "start aen failed\n");
7491                 goto fail_start_aen;
7492         }
7493
7494         megasas_setup_debugfs(instance);
7495
7496         /* Get current SR-IOV LD/VF affiliation */
7497         if (instance->requestorId)
7498                 megasas_get_ld_vf_affiliation(instance, 1);
7499
7500         return 0;
7501
7502 fail_start_aen:
7503         instance->unload = 1;
7504         scsi_remove_host(instance->host);
7505 fail_io_attach:
7506         megasas_mgmt_info.count--;
7507         megasas_mgmt_info.max_index--;
7508         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
7509
7510         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7511                 del_timer_sync(&instance->sriov_heartbeat_timer);
7512
7513         instance->instancet->disable_intr(instance);
7514         megasas_destroy_irqs(instance);
7515
7516         if (instance->adapter_type != MFI_SERIES)
7517                 megasas_release_fusion(instance);
7518         else
7519                 megasas_release_mfi(instance);
7520
7521         if (instance->msix_vectors)
7522                 pci_free_irq_vectors(instance->pdev);
7523         instance->msix_vectors = 0;
7524
7525         if (instance->fw_crash_state != UNAVAILABLE)
7526                 megasas_free_host_crash_buffer(instance);
7527
7528         if (instance->adapter_type != MFI_SERIES)
7529                 megasas_fusion_stop_watchdog(instance);
7530 fail_init_mfi:
7531         scsi_host_put(host);
7532 fail_alloc_instance:
7533         pci_disable_device(pdev);
7534
7535         return -ENODEV;
7536 }
7537
7538 /**
7539  * megasas_flush_cache -        Requests FW to flush all its caches
7540  * @instance:                   Adapter soft state
7541  */
7542 static void megasas_flush_cache(struct megasas_instance *instance)
7543 {
7544         struct megasas_cmd *cmd;
7545         struct megasas_dcmd_frame *dcmd;
7546
7547         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7548                 return;
7549
7550         cmd = megasas_get_cmd(instance);
7551
7552         if (!cmd)
7553                 return;
7554
7555         dcmd = &cmd->frame->dcmd;
7556
7557         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7558
7559         dcmd->cmd = MFI_CMD_DCMD;
7560         dcmd->cmd_status = 0x0;
7561         dcmd->sge_count = 0;
7562         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7563         dcmd->timeout = 0;
7564         dcmd->pad_0 = 0;
7565         dcmd->data_xfer_len = 0;
7566         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_CACHE_FLUSH);
7567         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
7568
7569         if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7570                         != DCMD_SUCCESS) {
7571                 dev_err(&instance->pdev->dev,
7572                         "return from %s %d\n", __func__, __LINE__);
7573                 return;
7574         }
7575
7576         megasas_return_cmd(instance, cmd);
7577 }
7578
7579 /**
7580  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
7581  * @instance:                           Adapter soft state
7582  * @opcode:                             Shutdown/Hibernate
7583  */
7584 static void megasas_shutdown_controller(struct megasas_instance *instance,
7585                                         u32 opcode)
7586 {
7587         struct megasas_cmd *cmd;
7588         struct megasas_dcmd_frame *dcmd;
7589
7590         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7591                 return;
7592
7593         cmd = megasas_get_cmd(instance);
7594
7595         if (!cmd)
7596                 return;
7597
7598         if (instance->aen_cmd)
7599                 megasas_issue_blocked_abort_cmd(instance,
7600                         instance->aen_cmd, MFI_IO_TIMEOUT_SECS);
7601         if (instance->map_update_cmd)
7602                 megasas_issue_blocked_abort_cmd(instance,
7603                         instance->map_update_cmd, MFI_IO_TIMEOUT_SECS);
7604         if (instance->jbod_seq_cmd)
7605                 megasas_issue_blocked_abort_cmd(instance,
7606                         instance->jbod_seq_cmd, MFI_IO_TIMEOUT_SECS);
7607
7608         dcmd = &cmd->frame->dcmd;
7609
7610         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7611
7612         dcmd->cmd = MFI_CMD_DCMD;
7613         dcmd->cmd_status = 0x0;
7614         dcmd->sge_count = 0;
7615         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7616         dcmd->timeout = 0;
7617         dcmd->pad_0 = 0;
7618         dcmd->data_xfer_len = 0;
7619         dcmd->opcode = cpu_to_le32(opcode);
7620
7621         if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7622                         != DCMD_SUCCESS) {
7623                 dev_err(&instance->pdev->dev,
7624                         "return from %s %d\n", __func__, __LINE__);
7625                 return;
7626         }
7627
7628         megasas_return_cmd(instance, cmd);
7629 }
7630
7631 #ifdef CONFIG_PM
7632 /**
7633  * megasas_suspend -    driver suspend entry point
7634  * @pdev:               PCI device structure
7635  * @state:              PCI power state to suspend routine
7636  */
7637 static int
7638 megasas_suspend(struct pci_dev *pdev, pm_message_t state)
7639 {
7640         struct megasas_instance *instance;
7641
7642         instance = pci_get_drvdata(pdev);
7643
7644         if (!instance)
7645                 return 0;
7646
7647         instance->unload = 1;
7648
7649         dev_info(&pdev->dev, "%s is called\n", __func__);
7650
7651         /* Shutdown SR-IOV heartbeat timer */
7652         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7653                 del_timer_sync(&instance->sriov_heartbeat_timer);
7654
7655         /* Stop the FW fault detection watchdog */
7656         if (instance->adapter_type != MFI_SERIES)
7657                 megasas_fusion_stop_watchdog(instance);
7658
7659         megasas_flush_cache(instance);
7660         megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
7661
7662         /* cancel the delayed work if this work still in queue */
7663         if (instance->ev != NULL) {
7664                 struct megasas_aen_event *ev = instance->ev;
7665                 cancel_delayed_work_sync(&ev->hotplug_work);
7666                 instance->ev = NULL;
7667         }
7668
7669         tasklet_kill(&instance->isr_tasklet);
7670
7671         pci_set_drvdata(instance->pdev, instance);
7672         instance->instancet->disable_intr(instance);
7673
7674         megasas_destroy_irqs(instance);
7675
7676         if (instance->msix_vectors)
7677                 pci_free_irq_vectors(instance->pdev);
7678
7679         pci_save_state(pdev);
7680         pci_disable_device(pdev);
7681
7682         pci_set_power_state(pdev, pci_choose_state(pdev, state));
7683
7684         return 0;
7685 }
7686
7687 /**
7688  * megasas_resume-      driver resume entry point
7689  * @pdev:               PCI device structure
7690  */
7691 static int
7692 megasas_resume(struct pci_dev *pdev)
7693 {
7694         int rval;
7695         struct Scsi_Host *host;
7696         struct megasas_instance *instance;
7697         u32 status_reg;
7698
7699         instance = pci_get_drvdata(pdev);
7700
7701         if (!instance)
7702                 return 0;
7703
7704         host = instance->host;
7705         pci_set_power_state(pdev, PCI_D0);
7706         pci_enable_wake(pdev, PCI_D0, 0);
7707         pci_restore_state(pdev);
7708
7709         dev_info(&pdev->dev, "%s is called\n", __func__);
7710         /*
7711          * PCI prepping: enable device set bus mastering and dma mask
7712          */
7713         rval = pci_enable_device_mem(pdev);
7714
7715         if (rval) {
7716                 dev_err(&pdev->dev, "Enable device failed\n");
7717                 return rval;
7718         }
7719
7720         pci_set_master(pdev);
7721
7722         /*
7723          * We expect the FW state to be READY
7724          */
7725
7726         if (megasas_transition_to_ready(instance, 0)) {
7727                 dev_info(&instance->pdev->dev,
7728                          "Failed to transition controller to ready from %s!\n",
7729                          __func__);
7730                 if (instance->adapter_type != MFI_SERIES) {
7731                         status_reg =
7732                                 instance->instancet->read_fw_status_reg(instance);
7733                         if (!(status_reg & MFI_RESET_ADAPTER) ||
7734                                 ((megasas_adp_reset_wait_for_ready
7735                                 (instance, true, 0)) == FAILED))
7736                                 goto fail_ready_state;
7737                 } else {
7738                         atomic_set(&instance->fw_reset_no_pci_access, 1);
7739                         instance->instancet->adp_reset
7740                                 (instance, instance->reg_set);
7741                         atomic_set(&instance->fw_reset_no_pci_access, 0);
7742
7743                         /* waiting for about 30 seconds before retry */
7744                         ssleep(30);
7745
7746                         if (megasas_transition_to_ready(instance, 0))
7747                                 goto fail_ready_state;
7748                 }
7749
7750                 dev_info(&instance->pdev->dev,
7751                          "FW restarted successfully from %s!\n",
7752                          __func__);
7753         }
7754         if (megasas_set_dma_mask(instance))
7755                 goto fail_set_dma_mask;
7756
7757         /*
7758          * Initialize MFI Firmware
7759          */
7760
7761         atomic_set(&instance->fw_outstanding, 0);
7762         atomic_set(&instance->ldio_outstanding, 0);
7763
7764         /* Now re-enable MSI-X */
7765         if (instance->msix_vectors)
7766                 megasas_alloc_irq_vectors(instance);
7767
7768         if (!instance->msix_vectors) {
7769                 rval = pci_alloc_irq_vectors(instance->pdev, 1, 1,
7770                                              PCI_IRQ_LEGACY);
7771                 if (rval < 0)
7772                         goto fail_reenable_msix;
7773         }
7774
7775         megasas_setup_reply_map(instance);
7776
7777         if (instance->adapter_type != MFI_SERIES) {
7778                 megasas_reset_reply_desc(instance);
7779                 if (megasas_ioc_init_fusion(instance)) {
7780                         megasas_free_cmds(instance);
7781                         megasas_free_cmds_fusion(instance);
7782                         goto fail_init_mfi;
7783                 }
7784                 if (!megasas_get_map_info(instance))
7785                         megasas_sync_map_info(instance);
7786         } else {
7787                 *instance->producer = 0;
7788                 *instance->consumer = 0;
7789                 if (megasas_issue_init_mfi(instance))
7790                         goto fail_init_mfi;
7791         }
7792
7793         if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS)
7794                 goto fail_init_mfi;
7795
7796         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
7797                      (unsigned long)instance);
7798
7799         if (instance->msix_vectors ?
7800                         megasas_setup_irqs_msix(instance, 0) :
7801                         megasas_setup_irqs_ioapic(instance))
7802                 goto fail_init_mfi;
7803
7804         if (instance->adapter_type != MFI_SERIES)
7805                 megasas_setup_irq_poll(instance);
7806
7807         /* Re-launch SR-IOV heartbeat timer */
7808         if (instance->requestorId) {
7809                 if (!megasas_sriov_start_heartbeat(instance, 0))
7810                         megasas_start_timer(instance);
7811                 else {
7812                         instance->skip_heartbeat_timer_del = 1;
7813                         goto fail_init_mfi;
7814                 }
7815         }
7816
7817         instance->instancet->enable_intr(instance);
7818         megasas_setup_jbod_map(instance);
7819         instance->unload = 0;
7820
7821         /*
7822          * Initiate AEN (Asynchronous Event Notification)
7823          */
7824         if (megasas_start_aen(instance))
7825                 dev_err(&instance->pdev->dev, "Start AEN failed\n");
7826
7827         /* Re-launch FW fault watchdog */
7828         if (instance->adapter_type != MFI_SERIES)
7829                 if (megasas_fusion_start_watchdog(instance) != SUCCESS)
7830                         goto fail_start_watchdog;
7831
7832         return 0;
7833
7834 fail_start_watchdog:
7835         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7836                 del_timer_sync(&instance->sriov_heartbeat_timer);
7837 fail_init_mfi:
7838         megasas_free_ctrl_dma_buffers(instance);
7839         megasas_free_ctrl_mem(instance);
7840         scsi_host_put(host);
7841
7842 fail_reenable_msix:
7843 fail_set_dma_mask:
7844 fail_ready_state:
7845
7846         pci_disable_device(pdev);
7847
7848         return -ENODEV;
7849 }
7850 #else
7851 #define megasas_suspend NULL
7852 #define megasas_resume  NULL
7853 #endif
7854
7855 static inline int
7856 megasas_wait_for_adapter_operational(struct megasas_instance *instance)
7857 {
7858         int wait_time = MEGASAS_RESET_WAIT_TIME * 2;
7859         int i;
7860         u8 adp_state;
7861
7862         for (i = 0; i < wait_time; i++) {
7863                 adp_state = atomic_read(&instance->adprecovery);
7864                 if ((adp_state == MEGASAS_HBA_OPERATIONAL) ||
7865                     (adp_state == MEGASAS_HW_CRITICAL_ERROR))
7866                         break;
7867
7868                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL))
7869                         dev_notice(&instance->pdev->dev, "waiting for controller reset to finish\n");
7870
7871                 msleep(1000);
7872         }
7873
7874         if (adp_state != MEGASAS_HBA_OPERATIONAL) {
7875                 dev_info(&instance->pdev->dev,
7876                          "%s HBA failed to become operational, adp_state %d\n",
7877                          __func__, adp_state);
7878                 return 1;
7879         }
7880
7881         return 0;
7882 }
7883
7884 /**
7885  * megasas_detach_one - PCI hot"un"plug entry point
7886  * @pdev:               PCI device structure
7887  */
7888 static void megasas_detach_one(struct pci_dev *pdev)
7889 {
7890         int i;
7891         struct Scsi_Host *host;
7892         struct megasas_instance *instance;
7893         struct fusion_context *fusion;
7894         u32 pd_seq_map_sz;
7895
7896         instance = pci_get_drvdata(pdev);
7897
7898         if (!instance)
7899                 return;
7900
7901         host = instance->host;
7902         fusion = instance->ctrl_context;
7903
7904         /* Shutdown SR-IOV heartbeat timer */
7905         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7906                 del_timer_sync(&instance->sriov_heartbeat_timer);
7907
7908         /* Stop the FW fault detection watchdog */
7909         if (instance->adapter_type != MFI_SERIES)
7910                 megasas_fusion_stop_watchdog(instance);
7911
7912         if (instance->fw_crash_state != UNAVAILABLE)
7913                 megasas_free_host_crash_buffer(instance);
7914         scsi_remove_host(instance->host);
7915         instance->unload = 1;
7916
7917         if (megasas_wait_for_adapter_operational(instance))
7918                 goto skip_firing_dcmds;
7919
7920         megasas_flush_cache(instance);
7921         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
7922
7923 skip_firing_dcmds:
7924         /* cancel the delayed work if this work still in queue*/
7925         if (instance->ev != NULL) {
7926                 struct megasas_aen_event *ev = instance->ev;
7927                 cancel_delayed_work_sync(&ev->hotplug_work);
7928                 instance->ev = NULL;
7929         }
7930
7931         /* cancel all wait events */
7932         wake_up_all(&instance->int_cmd_wait_q);
7933
7934         tasklet_kill(&instance->isr_tasklet);
7935
7936         /*
7937          * Take the instance off the instance array. Note that we will not
7938          * decrement the max_index. We let this array be sparse array
7939          */
7940         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
7941                 if (megasas_mgmt_info.instance[i] == instance) {
7942                         megasas_mgmt_info.count--;
7943                         megasas_mgmt_info.instance[i] = NULL;
7944
7945                         break;
7946                 }
7947         }
7948
7949         instance->instancet->disable_intr(instance);
7950
7951         megasas_destroy_irqs(instance);
7952
7953         if (instance->msix_vectors)
7954                 pci_free_irq_vectors(instance->pdev);
7955
7956         if (instance->adapter_type >= VENTURA_SERIES) {
7957                 for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i)
7958                         kfree(fusion->stream_detect_by_ld[i]);
7959                 kfree(fusion->stream_detect_by_ld);
7960                 fusion->stream_detect_by_ld = NULL;
7961         }
7962
7963
7964         if (instance->adapter_type != MFI_SERIES) {
7965                 megasas_release_fusion(instance);
7966                         pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) +
7967                                 (sizeof(struct MR_PD_CFG_SEQ) *
7968                                         (MAX_PHYSICAL_DEVICES - 1));
7969                 for (i = 0; i < 2 ; i++) {
7970                         if (fusion->ld_map[i])
7971                                 dma_free_coherent(&instance->pdev->dev,
7972                                                   fusion->max_map_sz,
7973                                                   fusion->ld_map[i],
7974                                                   fusion->ld_map_phys[i]);
7975                         if (fusion->ld_drv_map[i]) {
7976                                 if (is_vmalloc_addr(fusion->ld_drv_map[i]))
7977                                         vfree(fusion->ld_drv_map[i]);
7978                                 else
7979                                         free_pages((ulong)fusion->ld_drv_map[i],
7980                                                    fusion->drv_map_pages);
7981                         }
7982
7983                         if (fusion->pd_seq_sync[i])
7984                                 dma_free_coherent(&instance->pdev->dev,
7985                                         pd_seq_map_sz,
7986                                         fusion->pd_seq_sync[i],
7987                                         fusion->pd_seq_phys[i]);
7988                 }
7989         } else {
7990                 megasas_release_mfi(instance);
7991         }
7992
7993         if (instance->vf_affiliation)
7994                 dma_free_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) *
7995                                     sizeof(struct MR_LD_VF_AFFILIATION),
7996                                     instance->vf_affiliation,
7997                                     instance->vf_affiliation_h);
7998
7999         if (instance->vf_affiliation_111)
8000                 dma_free_coherent(&pdev->dev,
8001                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
8002                                     instance->vf_affiliation_111,
8003                                     instance->vf_affiliation_111_h);
8004
8005         if (instance->hb_host_mem)
8006                 dma_free_coherent(&pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM),
8007                                     instance->hb_host_mem,
8008                                     instance->hb_host_mem_h);
8009
8010         megasas_free_ctrl_dma_buffers(instance);
8011
8012         megasas_free_ctrl_mem(instance);
8013
8014         megasas_destroy_debugfs(instance);
8015
8016         scsi_host_put(host);
8017
8018         pci_disable_device(pdev);
8019 }
8020
8021 /**
8022  * megasas_shutdown -   Shutdown entry point
8023  * @pdev:               Generic device structure
8024  */
8025 static void megasas_shutdown(struct pci_dev *pdev)
8026 {
8027         struct megasas_instance *instance = pci_get_drvdata(pdev);
8028
8029         if (!instance)
8030                 return;
8031
8032         instance->unload = 1;
8033
8034         if (megasas_wait_for_adapter_operational(instance))
8035                 goto skip_firing_dcmds;
8036
8037         megasas_flush_cache(instance);
8038         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
8039
8040 skip_firing_dcmds:
8041         instance->instancet->disable_intr(instance);
8042         megasas_destroy_irqs(instance);
8043
8044         if (instance->msix_vectors)
8045                 pci_free_irq_vectors(instance->pdev);
8046 }
8047
8048 /*
8049  * megasas_mgmt_open -  char node "open" entry point
8050  * @inode:      char node inode
8051  * @filep:      char node file
8052  */
8053 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
8054 {
8055         /*
8056          * Allow only those users with admin rights
8057          */
8058         if (!capable(CAP_SYS_ADMIN))
8059                 return -EACCES;
8060
8061         return 0;
8062 }
8063
8064 /*
8065  * megasas_mgmt_fasync -        Async notifier registration from applications
8066  * @fd:         char node file descriptor number
8067  * @filep:      char node file
8068  * @mode:       notifier on/off
8069  *
8070  * This function adds the calling process to a driver global queue. When an
8071  * event occurs, SIGIO will be sent to all processes in this queue.
8072  */
8073 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
8074 {
8075         int rc;
8076
8077         mutex_lock(&megasas_async_queue_mutex);
8078
8079         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
8080
8081         mutex_unlock(&megasas_async_queue_mutex);
8082
8083         if (rc >= 0) {
8084                 /* For sanity check when we get ioctl */
8085                 filep->private_data = filep;
8086                 return 0;
8087         }
8088
8089         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
8090
8091         return rc;
8092 }
8093
8094 /*
8095  * megasas_mgmt_poll -  char node "poll" entry point
8096  * @filep:      char node file
8097  * @wait:       Events to poll for
8098  */
8099 static __poll_t megasas_mgmt_poll(struct file *file, poll_table *wait)
8100 {
8101         __poll_t mask;
8102         unsigned long flags;
8103
8104         poll_wait(file, &megasas_poll_wait, wait);
8105         spin_lock_irqsave(&poll_aen_lock, flags);
8106         if (megasas_poll_wait_aen)
8107                 mask = (EPOLLIN | EPOLLRDNORM);
8108         else
8109                 mask = 0;
8110         megasas_poll_wait_aen = 0;
8111         spin_unlock_irqrestore(&poll_aen_lock, flags);
8112         return mask;
8113 }
8114
8115 /*
8116  * megasas_set_crash_dump_params_ioctl:
8117  *              Send CRASH_DUMP_MODE DCMD to all controllers
8118  * @cmd:        MFI command frame
8119  */
8120
8121 static int megasas_set_crash_dump_params_ioctl(struct megasas_cmd *cmd)
8122 {
8123         struct megasas_instance *local_instance;
8124         int i, error = 0;
8125         int crash_support;
8126
8127         crash_support = cmd->frame->dcmd.mbox.w[0];
8128
8129         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
8130                 local_instance = megasas_mgmt_info.instance[i];
8131                 if (local_instance && local_instance->crash_dump_drv_support) {
8132                         if ((atomic_read(&local_instance->adprecovery) ==
8133                                 MEGASAS_HBA_OPERATIONAL) &&
8134                                 !megasas_set_crash_dump_params(local_instance,
8135                                         crash_support)) {
8136                                 local_instance->crash_dump_app_support =
8137                                         crash_support;
8138                                 dev_info(&local_instance->pdev->dev,
8139                                         "Application firmware crash "
8140                                         "dump mode set success\n");
8141                                 error = 0;
8142                         } else {
8143                                 dev_info(&local_instance->pdev->dev,
8144                                         "Application firmware crash "
8145                                         "dump mode set failed\n");
8146                                 error = -1;
8147                         }
8148                 }
8149         }
8150         return error;
8151 }
8152
8153 /**
8154  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
8155  * @instance:                   Adapter soft state
8156  * @user_ioc:                   User's ioctl packet
8157  * @ioc:                        ioctl packet
8158  */
8159 static int
8160 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
8161                       struct megasas_iocpacket __user * user_ioc,
8162                       struct megasas_iocpacket *ioc)
8163 {
8164         struct megasas_sge64 *kern_sge64 = NULL;
8165         struct megasas_sge32 *kern_sge32 = NULL;
8166         struct megasas_cmd *cmd;
8167         void *kbuff_arr[MAX_IOCTL_SGE];
8168         dma_addr_t buf_handle = 0;
8169         int error = 0, i;
8170         void *sense = NULL;
8171         dma_addr_t sense_handle;
8172         void *sense_ptr;
8173         u32 opcode = 0;
8174         int ret = DCMD_SUCCESS;
8175
8176         memset(kbuff_arr, 0, sizeof(kbuff_arr));
8177
8178         if (ioc->sge_count > MAX_IOCTL_SGE) {
8179                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "SGE count [%d] >  max limit [%d]\n",
8180                        ioc->sge_count, MAX_IOCTL_SGE);
8181                 return -EINVAL;
8182         }
8183
8184         if ((ioc->frame.hdr.cmd >= MFI_CMD_OP_COUNT) ||
8185             ((ioc->frame.hdr.cmd == MFI_CMD_NVME) &&
8186             !instance->support_nvme_passthru) ||
8187             ((ioc->frame.hdr.cmd == MFI_CMD_TOOLBOX) &&
8188             !instance->support_pci_lane_margining)) {
8189                 dev_err(&instance->pdev->dev,
8190                         "Received invalid ioctl command 0x%x\n",
8191                         ioc->frame.hdr.cmd);
8192                 return -ENOTSUPP;
8193         }
8194
8195         cmd = megasas_get_cmd(instance);
8196         if (!cmd) {
8197                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a cmd packet\n");
8198                 return -ENOMEM;
8199         }
8200
8201         /*
8202          * User's IOCTL packet has 2 frames (maximum). Copy those two
8203          * frames into our cmd's frames. cmd->frame's context will get
8204          * overwritten when we copy from user's frames. So set that value
8205          * alone separately
8206          */
8207         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
8208         cmd->frame->hdr.context = cpu_to_le32(cmd->index);
8209         cmd->frame->hdr.pad_0 = 0;
8210
8211         cmd->frame->hdr.flags &= (~MFI_FRAME_IEEE);
8212
8213         if (instance->consistent_mask_64bit)
8214                 cmd->frame->hdr.flags |= cpu_to_le16((MFI_FRAME_SGL64 |
8215                                        MFI_FRAME_SENSE64));
8216         else
8217                 cmd->frame->hdr.flags &= cpu_to_le16(~(MFI_FRAME_SGL64 |
8218                                                MFI_FRAME_SENSE64));
8219
8220         if (cmd->frame->hdr.cmd == MFI_CMD_DCMD)
8221                 opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
8222
8223         if (opcode == MR_DCMD_CTRL_SHUTDOWN) {
8224                 mutex_lock(&instance->reset_mutex);
8225                 if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS) {
8226                         megasas_return_cmd(instance, cmd);
8227                         mutex_unlock(&instance->reset_mutex);
8228                         return -1;
8229                 }
8230                 mutex_unlock(&instance->reset_mutex);
8231         }
8232
8233         if (opcode == MR_DRIVER_SET_APP_CRASHDUMP_MODE) {
8234                 error = megasas_set_crash_dump_params_ioctl(cmd);
8235                 megasas_return_cmd(instance, cmd);
8236                 return error;
8237         }
8238
8239         /*
8240          * The management interface between applications and the fw uses
8241          * MFI frames. E.g, RAID configuration changes, LD property changes
8242          * etc are accomplishes through different kinds of MFI frames. The
8243          * driver needs to care only about substituting user buffers with
8244          * kernel buffers in SGLs. The location of SGL is embedded in the
8245          * struct iocpacket itself.
8246          */
8247         if (instance->consistent_mask_64bit)
8248                 kern_sge64 = (struct megasas_sge64 *)
8249                         ((unsigned long)cmd->frame + ioc->sgl_off);
8250         else
8251                 kern_sge32 = (struct megasas_sge32 *)
8252                         ((unsigned long)cmd->frame + ioc->sgl_off);
8253
8254         /*
8255          * For each user buffer, create a mirror buffer and copy in
8256          */
8257         for (i = 0; i < ioc->sge_count; i++) {
8258                 if (!ioc->sgl[i].iov_len)
8259                         continue;
8260
8261                 kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
8262                                                     ioc->sgl[i].iov_len,
8263                                                     &buf_handle, GFP_KERNEL);
8264                 if (!kbuff_arr[i]) {
8265                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to alloc "
8266                                "kernel SGL buffer for IOCTL\n");
8267                         error = -ENOMEM;
8268                         goto out;
8269                 }
8270
8271                 /*
8272                  * We don't change the dma_coherent_mask, so
8273                  * dma_alloc_coherent only returns 32bit addresses
8274                  */
8275                 if (instance->consistent_mask_64bit) {
8276                         kern_sge64[i].phys_addr = cpu_to_le64(buf_handle);
8277                         kern_sge64[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
8278                 } else {
8279                         kern_sge32[i].phys_addr = cpu_to_le32(buf_handle);
8280                         kern_sge32[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
8281                 }
8282
8283                 /*
8284                  * We created a kernel buffer corresponding to the
8285                  * user buffer. Now copy in from the user buffer
8286                  */
8287                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
8288                                    (u32) (ioc->sgl[i].iov_len))) {
8289                         error = -EFAULT;
8290                         goto out;
8291                 }
8292         }
8293
8294         if (ioc->sense_len) {
8295                 /* make sure the pointer is part of the frame */
8296                 if (ioc->sense_off >
8297                     (sizeof(union megasas_frame) - sizeof(__le64))) {
8298                         error = -EINVAL;
8299                         goto out;
8300                 }
8301
8302                 sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
8303                                              &sense_handle, GFP_KERNEL);
8304                 if (!sense) {
8305                         error = -ENOMEM;
8306                         goto out;
8307                 }
8308
8309                 /* always store 64 bits regardless of addressing */
8310                 sense_ptr = (void *)cmd->frame + ioc->sense_off;
8311                 put_unaligned_le64(sense_handle, sense_ptr);
8312         }
8313
8314         /*
8315          * Set the sync_cmd flag so that the ISR knows not to complete this
8316          * cmd to the SCSI mid-layer
8317          */
8318         cmd->sync_cmd = 1;
8319
8320         ret = megasas_issue_blocked_cmd(instance, cmd, 0);
8321         switch (ret) {
8322         case DCMD_INIT:
8323         case DCMD_BUSY:
8324                 cmd->sync_cmd = 0;
8325                 dev_err(&instance->pdev->dev,
8326                         "return -EBUSY from %s %d cmd 0x%x opcode 0x%x cmd->cmd_status_drv 0x%x\n",
8327                          __func__, __LINE__, cmd->frame->hdr.cmd, opcode,
8328                          cmd->cmd_status_drv);
8329                 error = -EBUSY;
8330                 goto out;
8331         }
8332
8333         cmd->sync_cmd = 0;
8334
8335         if (instance->unload == 1) {
8336                 dev_info(&instance->pdev->dev, "Driver unload is in progress "
8337                         "don't submit data to application\n");
8338                 goto out;
8339         }
8340         /*
8341          * copy out the kernel buffers to user buffers
8342          */
8343         for (i = 0; i < ioc->sge_count; i++) {
8344                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
8345                                  ioc->sgl[i].iov_len)) {
8346                         error = -EFAULT;
8347                         goto out;
8348                 }
8349         }
8350
8351         /*
8352          * copy out the sense
8353          */
8354         if (ioc->sense_len) {
8355                 /*
8356                  * sense_ptr points to the location that has the user
8357                  * sense buffer address
8358                  */
8359                 sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
8360                                 ioc->sense_off);
8361
8362                 if (copy_to_user((void __user *)((unsigned long)
8363                                  get_unaligned((unsigned long *)sense_ptr)),
8364                                  sense, ioc->sense_len)) {
8365                         dev_err(&instance->pdev->dev, "Failed to copy out to user "
8366                                         "sense data\n");
8367                         error = -EFAULT;
8368                         goto out;
8369                 }
8370         }
8371
8372         /*
8373          * copy the status codes returned by the fw
8374          */
8375         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
8376                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
8377                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error copying out cmd_status\n");
8378                 error = -EFAULT;
8379         }
8380
8381 out:
8382         if (sense) {
8383                 dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
8384                                     sense, sense_handle);
8385         }
8386
8387         for (i = 0; i < ioc->sge_count; i++) {
8388                 if (kbuff_arr[i]) {
8389                         if (instance->consistent_mask_64bit)
8390                                 dma_free_coherent(&instance->pdev->dev,
8391                                         le32_to_cpu(kern_sge64[i].length),
8392                                         kbuff_arr[i],
8393                                         le64_to_cpu(kern_sge64[i].phys_addr));
8394                         else
8395                                 dma_free_coherent(&instance->pdev->dev,
8396                                         le32_to_cpu(kern_sge32[i].length),
8397                                         kbuff_arr[i],
8398                                         le32_to_cpu(kern_sge32[i].phys_addr));
8399                         kbuff_arr[i] = NULL;
8400                 }
8401         }
8402
8403         megasas_return_cmd(instance, cmd);
8404         return error;
8405 }
8406
8407 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
8408 {
8409         struct megasas_iocpacket __user *user_ioc =
8410             (struct megasas_iocpacket __user *)arg;
8411         struct megasas_iocpacket *ioc;
8412         struct megasas_instance *instance;
8413         int error;
8414
8415         ioc = memdup_user(user_ioc, sizeof(*ioc));
8416         if (IS_ERR(ioc))
8417                 return PTR_ERR(ioc);
8418
8419         instance = megasas_lookup_instance(ioc->host_no);
8420         if (!instance) {
8421                 error = -ENODEV;
8422                 goto out_kfree_ioc;
8423         }
8424
8425         /* Block ioctls in VF mode */
8426         if (instance->requestorId && !allow_vf_ioctls) {
8427                 error = -ENODEV;
8428                 goto out_kfree_ioc;
8429         }
8430
8431         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8432                 dev_err(&instance->pdev->dev, "Controller in crit error\n");
8433                 error = -ENODEV;
8434                 goto out_kfree_ioc;
8435         }
8436
8437         if (instance->unload == 1) {
8438                 error = -ENODEV;
8439                 goto out_kfree_ioc;
8440         }
8441
8442         if (down_interruptible(&instance->ioctl_sem)) {
8443                 error = -ERESTARTSYS;
8444                 goto out_kfree_ioc;
8445         }
8446
8447         if  (megasas_wait_for_adapter_operational(instance)) {
8448                 error = -ENODEV;
8449                 goto out_up;
8450         }
8451
8452         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
8453 out_up:
8454         up(&instance->ioctl_sem);
8455
8456 out_kfree_ioc:
8457         kfree(ioc);
8458         return error;
8459 }
8460
8461 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
8462 {
8463         struct megasas_instance *instance;
8464         struct megasas_aen aen;
8465         int error;
8466
8467         if (file->private_data != file) {
8468                 printk(KERN_DEBUG "megasas: fasync_helper was not "
8469                        "called first\n");
8470                 return -EINVAL;
8471         }
8472
8473         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
8474                 return -EFAULT;
8475
8476         instance = megasas_lookup_instance(aen.host_no);
8477
8478         if (!instance)
8479                 return -ENODEV;
8480
8481         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8482                 return -ENODEV;
8483         }
8484
8485         if (instance->unload == 1) {
8486                 return -ENODEV;
8487         }
8488
8489         if  (megasas_wait_for_adapter_operational(instance))
8490                 return -ENODEV;
8491
8492         mutex_lock(&instance->reset_mutex);
8493         error = megasas_register_aen(instance, aen.seq_num,
8494                                      aen.class_locale_word);
8495         mutex_unlock(&instance->reset_mutex);
8496         return error;
8497 }
8498
8499 /**
8500  * megasas_mgmt_ioctl - char node ioctl entry point
8501  * @file:       char device file pointer
8502  * @cmd:        ioctl command
8503  * @arg:        ioctl command arguments address
8504  */
8505 static long
8506 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
8507 {
8508         switch (cmd) {
8509         case MEGASAS_IOC_FIRMWARE:
8510                 return megasas_mgmt_ioctl_fw(file, arg);
8511
8512         case MEGASAS_IOC_GET_AEN:
8513                 return megasas_mgmt_ioctl_aen(file, arg);
8514         }
8515
8516         return -ENOTTY;
8517 }
8518
8519 #ifdef CONFIG_COMPAT
8520 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
8521 {
8522         struct compat_megasas_iocpacket __user *cioc =
8523             (struct compat_megasas_iocpacket __user *)arg;
8524         struct megasas_iocpacket __user *ioc =
8525             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
8526         int i;
8527         int error = 0;
8528         compat_uptr_t ptr;
8529         u32 local_sense_off;
8530         u32 local_sense_len;
8531         u32 user_sense_off;
8532
8533         if (clear_user(ioc, sizeof(*ioc)))
8534                 return -EFAULT;
8535
8536         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
8537             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
8538             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
8539             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
8540             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
8541             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
8542                 return -EFAULT;
8543
8544         /*
8545          * The sense_ptr is used in megasas_mgmt_fw_ioctl only when
8546          * sense_len is not null, so prepare the 64bit value under
8547          * the same condition.
8548          */
8549         if (get_user(local_sense_off, &ioc->sense_off) ||
8550                 get_user(local_sense_len, &ioc->sense_len) ||
8551                 get_user(user_sense_off, &cioc->sense_off))
8552                 return -EFAULT;
8553
8554         if (local_sense_off != user_sense_off)
8555                 return -EINVAL;
8556
8557         if (local_sense_len) {
8558                 void __user **sense_ioc_ptr =
8559                         (void __user **)((u8 *)((unsigned long)&ioc->frame.raw) + local_sense_off);
8560                 compat_uptr_t *sense_cioc_ptr =
8561                         (compat_uptr_t *)(((unsigned long)&cioc->frame.raw) + user_sense_off);
8562                 if (get_user(ptr, sense_cioc_ptr) ||
8563                     put_user(compat_ptr(ptr), sense_ioc_ptr))
8564                         return -EFAULT;
8565         }
8566
8567         for (i = 0; i < MAX_IOCTL_SGE; i++) {
8568                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
8569                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
8570                     copy_in_user(&ioc->sgl[i].iov_len,
8571                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
8572                         return -EFAULT;
8573         }
8574
8575         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
8576
8577         if (copy_in_user(&cioc->frame.hdr.cmd_status,
8578                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
8579                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
8580                 return -EFAULT;
8581         }
8582         return error;
8583 }
8584
8585 static long
8586 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
8587                           unsigned long arg)
8588 {
8589         switch (cmd) {
8590         case MEGASAS_IOC_FIRMWARE32:
8591                 return megasas_mgmt_compat_ioctl_fw(file, arg);
8592         case MEGASAS_IOC_GET_AEN:
8593                 return megasas_mgmt_ioctl_aen(file, arg);
8594         }
8595
8596         return -ENOTTY;
8597 }
8598 #endif
8599
8600 /*
8601  * File operations structure for management interface
8602  */
8603 static const struct file_operations megasas_mgmt_fops = {
8604         .owner = THIS_MODULE,
8605         .open = megasas_mgmt_open,
8606         .fasync = megasas_mgmt_fasync,
8607         .unlocked_ioctl = megasas_mgmt_ioctl,
8608         .poll = megasas_mgmt_poll,
8609 #ifdef CONFIG_COMPAT
8610         .compat_ioctl = megasas_mgmt_compat_ioctl,
8611 #endif
8612         .llseek = noop_llseek,
8613 };
8614
8615 /*
8616  * PCI hotplug support registration structure
8617  */
8618 static struct pci_driver megasas_pci_driver = {
8619
8620         .name = "megaraid_sas",
8621         .id_table = megasas_pci_table,
8622         .probe = megasas_probe_one,
8623         .remove = megasas_detach_one,
8624         .suspend = megasas_suspend,
8625         .resume = megasas_resume,
8626         .shutdown = megasas_shutdown,
8627 };
8628
8629 /*
8630  * Sysfs driver attributes
8631  */
8632 static ssize_t version_show(struct device_driver *dd, char *buf)
8633 {
8634         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
8635                         MEGASAS_VERSION);
8636 }
8637 static DRIVER_ATTR_RO(version);
8638
8639 static ssize_t release_date_show(struct device_driver *dd, char *buf)
8640 {
8641         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
8642                 MEGASAS_RELDATE);
8643 }
8644 static DRIVER_ATTR_RO(release_date);
8645
8646 static ssize_t support_poll_for_event_show(struct device_driver *dd, char *buf)
8647 {
8648         return sprintf(buf, "%u\n", support_poll_for_event);
8649 }
8650 static DRIVER_ATTR_RO(support_poll_for_event);
8651
8652 static ssize_t support_device_change_show(struct device_driver *dd, char *buf)
8653 {
8654         return sprintf(buf, "%u\n", support_device_change);
8655 }
8656 static DRIVER_ATTR_RO(support_device_change);
8657
8658 static ssize_t dbg_lvl_show(struct device_driver *dd, char *buf)
8659 {
8660         return sprintf(buf, "%u\n", megasas_dbg_lvl);
8661 }
8662
8663 static ssize_t dbg_lvl_store(struct device_driver *dd, const char *buf,
8664                              size_t count)
8665 {
8666         int retval = count;
8667
8668         if (sscanf(buf, "%u", &megasas_dbg_lvl) < 1) {
8669                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
8670                 retval = -EINVAL;
8671         }
8672         return retval;
8673 }
8674 static DRIVER_ATTR_RW(dbg_lvl);
8675
8676 static ssize_t
8677 support_nvme_encapsulation_show(struct device_driver *dd, char *buf)
8678 {
8679         return sprintf(buf, "%u\n", support_nvme_encapsulation);
8680 }
8681
8682 static DRIVER_ATTR_RO(support_nvme_encapsulation);
8683
8684 static ssize_t
8685 support_pci_lane_margining_show(struct device_driver *dd, char *buf)
8686 {
8687         return sprintf(buf, "%u\n", support_pci_lane_margining);
8688 }
8689
8690 static DRIVER_ATTR_RO(support_pci_lane_margining);
8691
8692 static inline void megasas_remove_scsi_device(struct scsi_device *sdev)
8693 {
8694         sdev_printk(KERN_INFO, sdev, "SCSI device is removed\n");
8695         scsi_remove_device(sdev);
8696         scsi_device_put(sdev);
8697 }
8698
8699 /**
8700  * megasas_update_device_list - Update the PD and LD device list from FW
8701  *                              after an AEN event notification
8702  * @instance:                   Adapter soft state
8703  * @event_type:                 Indicates type of event (PD or LD event)
8704  *
8705  * @return:                     Success or failure
8706  *
8707  * Issue DCMDs to Firmware to update the internal device list in driver.
8708  * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
8709  * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
8710  */
8711 static
8712 int megasas_update_device_list(struct megasas_instance *instance,
8713                                int event_type)
8714 {
8715         int dcmd_ret = DCMD_SUCCESS;
8716
8717         if (instance->enable_fw_dev_list) {
8718                 dcmd_ret = megasas_host_device_list_query(instance, false);
8719                 if (dcmd_ret != DCMD_SUCCESS)
8720                         goto out;
8721         } else {
8722                 if (event_type & SCAN_PD_CHANNEL) {
8723                         dcmd_ret = megasas_get_pd_list(instance);
8724
8725                         if (dcmd_ret != DCMD_SUCCESS)
8726                                 goto out;
8727                 }
8728
8729                 if (event_type & SCAN_VD_CHANNEL) {
8730                         if (!instance->requestorId ||
8731                             (instance->requestorId &&
8732                              megasas_get_ld_vf_affiliation(instance, 0))) {
8733                                 dcmd_ret = megasas_ld_list_query(instance,
8734                                                 MR_LD_QUERY_TYPE_EXPOSED_TO_HOST);
8735                                 if (dcmd_ret != DCMD_SUCCESS)
8736                                         goto out;
8737                         }
8738                 }
8739         }
8740
8741 out:
8742         return dcmd_ret;
8743 }
8744
8745 /**
8746  * megasas_add_remove_devices - Add/remove devices to SCSI mid-layer
8747  *                              after an AEN event notification
8748  * @instance:                   Adapter soft state
8749  * @scan_type:                  Indicates type of devices (PD/LD) to add
8750  * @return                      void
8751  */
8752 static
8753 void megasas_add_remove_devices(struct megasas_instance *instance,
8754                                 int scan_type)
8755 {
8756         int i, j;
8757         u16 pd_index = 0;
8758         u16 ld_index = 0;
8759         u16 channel = 0, id = 0;
8760         struct Scsi_Host *host;
8761         struct scsi_device *sdev1;
8762         struct MR_HOST_DEVICE_LIST *targetid_list = NULL;
8763         struct MR_HOST_DEVICE_LIST_ENTRY *targetid_entry = NULL;
8764
8765         host = instance->host;
8766
8767         if (instance->enable_fw_dev_list) {
8768                 targetid_list = instance->host_device_list_buf;
8769                 for (i = 0; i < targetid_list->count; i++) {
8770                         targetid_entry = &targetid_list->host_device_list[i];
8771                         if (targetid_entry->flags.u.bits.is_sys_pd) {
8772                                 channel = le16_to_cpu(targetid_entry->target_id) /
8773                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8774                                 id = le16_to_cpu(targetid_entry->target_id) %
8775                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8776                         } else {
8777                                 channel = MEGASAS_MAX_PD_CHANNELS +
8778                                           (le16_to_cpu(targetid_entry->target_id) /
8779                                            MEGASAS_MAX_DEV_PER_CHANNEL);
8780                                 id = le16_to_cpu(targetid_entry->target_id) %
8781                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8782                         }
8783                         sdev1 = scsi_device_lookup(host, channel, id, 0);
8784                         if (!sdev1) {
8785                                 scsi_add_device(host, channel, id, 0);
8786                         } else {
8787                                 scsi_device_put(sdev1);
8788                         }
8789                 }
8790         }
8791
8792         if (scan_type & SCAN_PD_CHANNEL) {
8793                 for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
8794                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8795                                 pd_index = i * MEGASAS_MAX_DEV_PER_CHANNEL + j;
8796                                 sdev1 = scsi_device_lookup(host, i, j, 0);
8797                                 if (instance->pd_list[pd_index].driveState ==
8798                                                         MR_PD_STATE_SYSTEM) {
8799                                         if (!sdev1)
8800                                                 scsi_add_device(host, i, j, 0);
8801                                         else
8802                                                 scsi_device_put(sdev1);
8803                                 } else {
8804                                         if (sdev1)
8805                                                 megasas_remove_scsi_device(sdev1);
8806                                 }
8807                         }
8808                 }
8809         }
8810
8811         if (scan_type & SCAN_VD_CHANNEL) {
8812                 for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
8813                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8814                                 ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
8815                                 sdev1 = scsi_device_lookup(host,
8816                                                 MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8817                                 if (instance->ld_ids[ld_index] != 0xff) {
8818                                         if (!sdev1)
8819                                                 scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8820                                         else
8821                                                 scsi_device_put(sdev1);
8822                                 } else {
8823                                         if (sdev1)
8824                                                 megasas_remove_scsi_device(sdev1);
8825                                 }
8826                         }
8827                 }
8828         }
8829
8830 }
8831
8832 static void
8833 megasas_aen_polling(struct work_struct *work)
8834 {
8835         struct megasas_aen_event *ev =
8836                 container_of(work, struct megasas_aen_event, hotplug_work.work);
8837         struct megasas_instance *instance = ev->instance;
8838         union megasas_evt_class_locale class_locale;
8839         int event_type = 0;
8840         u32 seq_num;
8841         u16 ld_target_id;
8842         int error;
8843         u8  dcmd_ret = DCMD_SUCCESS;
8844         struct scsi_device *sdev1;
8845
8846         if (!instance) {
8847                 printk(KERN_ERR "invalid instance!\n");
8848                 kfree(ev);
8849                 return;
8850         }
8851
8852         /* Don't run the event workqueue thread if OCR is running */
8853         mutex_lock(&instance->reset_mutex);
8854
8855         instance->ev = NULL;
8856         if (instance->evt_detail) {
8857                 megasas_decode_evt(instance);
8858
8859                 switch (le32_to_cpu(instance->evt_detail->code)) {
8860
8861                 case MR_EVT_PD_INSERTED:
8862                 case MR_EVT_PD_REMOVED:
8863                         event_type = SCAN_PD_CHANNEL;
8864                         break;
8865
8866                 case MR_EVT_LD_OFFLINE:
8867                 case MR_EVT_LD_DELETED:
8868                         ld_target_id = instance->evt_detail->args.ld.target_id;
8869                         sdev1 = scsi_device_lookup(instance->host,
8870                                                    MEGASAS_MAX_PD_CHANNELS +
8871                                                    (ld_target_id / MEGASAS_MAX_DEV_PER_CHANNEL),
8872                                                    (ld_target_id - MEGASAS_MAX_DEV_PER_CHANNEL),
8873                                                    0);
8874                         if (sdev1)
8875                                 megasas_remove_scsi_device(sdev1);
8876
8877                         event_type = SCAN_VD_CHANNEL;
8878                         break;
8879                 case MR_EVT_LD_CREATED:
8880                         event_type = SCAN_VD_CHANNEL;
8881                         break;
8882
8883                 case MR_EVT_CFG_CLEARED:
8884                 case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
8885                 case MR_EVT_FOREIGN_CFG_IMPORTED:
8886                 case MR_EVT_LD_STATE_CHANGE:
8887                         event_type = SCAN_PD_CHANNEL | SCAN_VD_CHANNEL;
8888                         dev_info(&instance->pdev->dev, "scanning for scsi%d...\n",
8889                                 instance->host->host_no);
8890                         break;
8891
8892                 case MR_EVT_CTRL_PROP_CHANGED:
8893                         dcmd_ret = megasas_get_ctrl_info(instance);
8894                         if (dcmd_ret == DCMD_SUCCESS &&
8895                             instance->snapdump_wait_time) {
8896                                 megasas_get_snapdump_properties(instance);
8897                                 dev_info(&instance->pdev->dev,
8898                                          "Snap dump wait time\t: %d\n",
8899                                          instance->snapdump_wait_time);
8900                         }
8901                         break;
8902                 default:
8903                         event_type = 0;
8904                         break;
8905                 }
8906         } else {
8907                 dev_err(&instance->pdev->dev, "invalid evt_detail!\n");
8908                 mutex_unlock(&instance->reset_mutex);
8909                 kfree(ev);
8910                 return;
8911         }
8912
8913         if (event_type)
8914                 dcmd_ret = megasas_update_device_list(instance, event_type);
8915
8916         mutex_unlock(&instance->reset_mutex);
8917
8918         if (event_type && dcmd_ret == DCMD_SUCCESS)
8919                 megasas_add_remove_devices(instance, event_type);
8920
8921         if (dcmd_ret == DCMD_SUCCESS)
8922                 seq_num = le32_to_cpu(instance->evt_detail->seq_num) + 1;
8923         else
8924                 seq_num = instance->last_seq_num;
8925
8926         /* Register AEN with FW for latest sequence number plus 1 */
8927         class_locale.members.reserved = 0;
8928         class_locale.members.locale = MR_EVT_LOCALE_ALL;
8929         class_locale.members.class = MR_EVT_CLASS_DEBUG;
8930
8931         if (instance->aen_cmd != NULL) {
8932                 kfree(ev);
8933                 return;
8934         }
8935
8936         mutex_lock(&instance->reset_mutex);
8937         error = megasas_register_aen(instance, seq_num,
8938                                         class_locale.word);
8939         if (error)
8940                 dev_err(&instance->pdev->dev,
8941                         "register aen failed error %x\n", error);
8942
8943         mutex_unlock(&instance->reset_mutex);
8944         kfree(ev);
8945 }
8946
8947 /**
8948  * megasas_init - Driver load entry point
8949  */
8950 static int __init megasas_init(void)
8951 {
8952         int rval;
8953
8954         /*
8955          * Booted in kdump kernel, minimize memory footprints by
8956          * disabling few features
8957          */
8958         if (reset_devices) {
8959                 msix_vectors = 1;
8960                 rdpq_enable = 0;
8961                 dual_qdepth_disable = 1;
8962         }
8963
8964         /*
8965          * Announce driver version and other information
8966          */
8967         pr_info("megasas: %s\n", MEGASAS_VERSION);
8968
8969         spin_lock_init(&poll_aen_lock);
8970
8971         support_poll_for_event = 2;
8972         support_device_change = 1;
8973         support_nvme_encapsulation = true;
8974         support_pci_lane_margining = true;
8975
8976         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
8977
8978         /*
8979          * Register character device node
8980          */
8981         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
8982
8983         if (rval < 0) {
8984                 printk(KERN_DEBUG "megasas: failed to open device node\n");
8985                 return rval;
8986         }
8987
8988         megasas_mgmt_majorno = rval;
8989
8990         megasas_init_debugfs();
8991
8992         /*
8993          * Register ourselves as PCI hotplug module
8994          */
8995         rval = pci_register_driver(&megasas_pci_driver);
8996
8997         if (rval) {
8998                 printk(KERN_DEBUG "megasas: PCI hotplug registration failed \n");
8999                 goto err_pcidrv;
9000         }
9001
9002         if ((event_log_level < MFI_EVT_CLASS_DEBUG) ||
9003             (event_log_level > MFI_EVT_CLASS_DEAD)) {
9004                 pr_warn("megaraid_sas: provided event log level is out of range, setting it to default 2(CLASS_CRITICAL), permissible range is: -2 to 4\n");
9005                 event_log_level = MFI_EVT_CLASS_CRITICAL;
9006         }
9007
9008         rval = driver_create_file(&megasas_pci_driver.driver,
9009                                   &driver_attr_version);
9010         if (rval)
9011                 goto err_dcf_attr_ver;
9012
9013         rval = driver_create_file(&megasas_pci_driver.driver,
9014                                   &driver_attr_release_date);
9015         if (rval)
9016                 goto err_dcf_rel_date;
9017
9018         rval = driver_create_file(&megasas_pci_driver.driver,
9019                                 &driver_attr_support_poll_for_event);
9020         if (rval)
9021                 goto err_dcf_support_poll_for_event;
9022
9023         rval = driver_create_file(&megasas_pci_driver.driver,
9024                                   &driver_attr_dbg_lvl);
9025         if (rval)
9026                 goto err_dcf_dbg_lvl;
9027         rval = driver_create_file(&megasas_pci_driver.driver,
9028                                 &driver_attr_support_device_change);
9029         if (rval)
9030                 goto err_dcf_support_device_change;
9031
9032         rval = driver_create_file(&megasas_pci_driver.driver,
9033                                   &driver_attr_support_nvme_encapsulation);
9034         if (rval)
9035                 goto err_dcf_support_nvme_encapsulation;
9036
9037         rval = driver_create_file(&megasas_pci_driver.driver,
9038                                   &driver_attr_support_pci_lane_margining);
9039         if (rval)
9040                 goto err_dcf_support_pci_lane_margining;
9041
9042         return rval;
9043
9044 err_dcf_support_pci_lane_margining:
9045         driver_remove_file(&megasas_pci_driver.driver,
9046                            &driver_attr_support_nvme_encapsulation);
9047
9048 err_dcf_support_nvme_encapsulation:
9049         driver_remove_file(&megasas_pci_driver.driver,
9050                            &driver_attr_support_device_change);
9051
9052 err_dcf_support_device_change:
9053         driver_remove_file(&megasas_pci_driver.driver,
9054                            &driver_attr_dbg_lvl);
9055 err_dcf_dbg_lvl:
9056         driver_remove_file(&megasas_pci_driver.driver,
9057                         &driver_attr_support_poll_for_event);
9058 err_dcf_support_poll_for_event:
9059         driver_remove_file(&megasas_pci_driver.driver,
9060                            &driver_attr_release_date);
9061 err_dcf_rel_date:
9062         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
9063 err_dcf_attr_ver:
9064         pci_unregister_driver(&megasas_pci_driver);
9065 err_pcidrv:
9066         megasas_exit_debugfs();
9067         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
9068         return rval;
9069 }
9070
9071 /**
9072  * megasas_exit - Driver unload entry point
9073  */
9074 static void __exit megasas_exit(void)
9075 {
9076         driver_remove_file(&megasas_pci_driver.driver,
9077                            &driver_attr_dbg_lvl);
9078         driver_remove_file(&megasas_pci_driver.driver,
9079                         &driver_attr_support_poll_for_event);
9080         driver_remove_file(&megasas_pci_driver.driver,
9081                         &driver_attr_support_device_change);
9082         driver_remove_file(&megasas_pci_driver.driver,
9083                            &driver_attr_release_date);
9084         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
9085         driver_remove_file(&megasas_pci_driver.driver,
9086                            &driver_attr_support_nvme_encapsulation);
9087         driver_remove_file(&megasas_pci_driver.driver,
9088                            &driver_attr_support_pci_lane_margining);
9089
9090         pci_unregister_driver(&megasas_pci_driver);
9091         megasas_exit_debugfs();
9092         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
9093 }
9094
9095 module_init(megasas_init);
9096 module_exit(megasas_exit);