GNU Linux-libre 5.10.215-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          * up to thirty 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 < 30);
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
3225         if (kstrtoint(buf, 0, &val) != 0)
3226                 return -EINVAL;
3227
3228         mutex_lock(&instance->crashdump_lock);
3229         instance->fw_crash_buffer_offset = val;
3230         mutex_unlock(&instance->crashdump_lock);
3231         return strlen(buf);
3232 }
3233
3234 static ssize_t
3235 fw_crash_buffer_show(struct device *cdev,
3236         struct device_attribute *attr, char *buf)
3237 {
3238         struct Scsi_Host *shost = class_to_shost(cdev);
3239         struct megasas_instance *instance =
3240                 (struct megasas_instance *) shost->hostdata;
3241         u32 size;
3242         unsigned long dmachunk = CRASH_DMA_BUF_SIZE;
3243         unsigned long chunk_left_bytes;
3244         unsigned long src_addr;
3245         u32 buff_offset;
3246
3247         mutex_lock(&instance->crashdump_lock);
3248         buff_offset = instance->fw_crash_buffer_offset;
3249         if (!instance->crash_dump_buf ||
3250                 !((instance->fw_crash_state == AVAILABLE) ||
3251                 (instance->fw_crash_state == COPYING))) {
3252                 dev_err(&instance->pdev->dev,
3253                         "Firmware crash dump is not available\n");
3254                 mutex_unlock(&instance->crashdump_lock);
3255                 return -EINVAL;
3256         }
3257
3258         if (buff_offset > (instance->fw_crash_buffer_size * dmachunk)) {
3259                 dev_err(&instance->pdev->dev,
3260                         "Firmware crash dump offset is out of range\n");
3261                 mutex_unlock(&instance->crashdump_lock);
3262                 return 0;
3263         }
3264
3265         size = (instance->fw_crash_buffer_size * dmachunk) - buff_offset;
3266         chunk_left_bytes = dmachunk - (buff_offset % dmachunk);
3267         size = (size > chunk_left_bytes) ? chunk_left_bytes : size;
3268         size = (size >= PAGE_SIZE) ? (PAGE_SIZE - 1) : size;
3269
3270         src_addr = (unsigned long)instance->crash_buf[buff_offset / dmachunk] +
3271                 (buff_offset % dmachunk);
3272         memcpy(buf, (void *)src_addr, size);
3273         mutex_unlock(&instance->crashdump_lock);
3274
3275         return size;
3276 }
3277
3278 static ssize_t
3279 fw_crash_buffer_size_show(struct device *cdev,
3280         struct device_attribute *attr, char *buf)
3281 {
3282         struct Scsi_Host *shost = class_to_shost(cdev);
3283         struct megasas_instance *instance =
3284                 (struct megasas_instance *) shost->hostdata;
3285
3286         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)
3287                 ((instance->fw_crash_buffer_size) * 1024 * 1024)/PAGE_SIZE);
3288 }
3289
3290 static ssize_t
3291 fw_crash_state_store(struct device *cdev,
3292         struct device_attribute *attr, const char *buf, size_t count)
3293 {
3294         struct Scsi_Host *shost = class_to_shost(cdev);
3295         struct megasas_instance *instance =
3296                 (struct megasas_instance *) shost->hostdata;
3297         int val = 0;
3298
3299         if (kstrtoint(buf, 0, &val) != 0)
3300                 return -EINVAL;
3301
3302         if ((val <= AVAILABLE || val > COPY_ERROR)) {
3303                 dev_err(&instance->pdev->dev, "application updates invalid "
3304                         "firmware crash state\n");
3305                 return -EINVAL;
3306         }
3307
3308         instance->fw_crash_state = val;
3309
3310         if ((val == COPIED) || (val == COPY_ERROR)) {
3311                 mutex_lock(&instance->crashdump_lock);
3312                 megasas_free_host_crash_buffer(instance);
3313                 mutex_unlock(&instance->crashdump_lock);
3314                 if (val == COPY_ERROR)
3315                         dev_info(&instance->pdev->dev, "application failed to "
3316                                 "copy Firmware crash dump\n");
3317                 else
3318                         dev_info(&instance->pdev->dev, "Firmware crash dump "
3319                                 "copied successfully\n");
3320         }
3321         return strlen(buf);
3322 }
3323
3324 static ssize_t
3325 fw_crash_state_show(struct device *cdev,
3326         struct device_attribute *attr, char *buf)
3327 {
3328         struct Scsi_Host *shost = class_to_shost(cdev);
3329         struct megasas_instance *instance =
3330                 (struct megasas_instance *) shost->hostdata;
3331
3332         return snprintf(buf, PAGE_SIZE, "%d\n", instance->fw_crash_state);
3333 }
3334
3335 static ssize_t
3336 page_size_show(struct device *cdev,
3337         struct device_attribute *attr, char *buf)
3338 {
3339         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)PAGE_SIZE - 1);
3340 }
3341
3342 static ssize_t
3343 ldio_outstanding_show(struct device *cdev, struct device_attribute *attr,
3344         char *buf)
3345 {
3346         struct Scsi_Host *shost = class_to_shost(cdev);
3347         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3348
3349         return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->ldio_outstanding));
3350 }
3351
3352 static ssize_t
3353 fw_cmds_outstanding_show(struct device *cdev,
3354                                  struct device_attribute *attr, char *buf)
3355 {
3356         struct Scsi_Host *shost = class_to_shost(cdev);
3357         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3358
3359         return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->fw_outstanding));
3360 }
3361
3362 static ssize_t
3363 enable_sdev_max_qd_show(struct device *cdev,
3364         struct device_attribute *attr, char *buf)
3365 {
3366         struct Scsi_Host *shost = class_to_shost(cdev);
3367         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3368
3369         return snprintf(buf, PAGE_SIZE, "%d\n", instance->enable_sdev_max_qd);
3370 }
3371
3372 static ssize_t
3373 enable_sdev_max_qd_store(struct device *cdev,
3374         struct device_attribute *attr, const char *buf, size_t count)
3375 {
3376         struct Scsi_Host *shost = class_to_shost(cdev);
3377         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3378         u32 val = 0;
3379         bool is_target_prop;
3380         int ret_target_prop = DCMD_FAILED;
3381         struct scsi_device *sdev;
3382
3383         if (kstrtou32(buf, 0, &val) != 0) {
3384                 pr_err("megasas: could not set enable_sdev_max_qd\n");
3385                 return -EINVAL;
3386         }
3387
3388         mutex_lock(&instance->reset_mutex);
3389         if (val)
3390                 instance->enable_sdev_max_qd = true;
3391         else
3392                 instance->enable_sdev_max_qd = false;
3393
3394         shost_for_each_device(sdev, shost) {
3395                 ret_target_prop = megasas_get_target_prop(instance, sdev);
3396                 is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false;
3397                 megasas_set_fw_assisted_qd(sdev, is_target_prop);
3398         }
3399         mutex_unlock(&instance->reset_mutex);
3400
3401         return strlen(buf);
3402 }
3403
3404 static ssize_t
3405 dump_system_regs_show(struct device *cdev,
3406                                struct device_attribute *attr, char *buf)
3407 {
3408         struct Scsi_Host *shost = class_to_shost(cdev);
3409         struct megasas_instance *instance =
3410                         (struct megasas_instance *)shost->hostdata;
3411
3412         return megasas_dump_sys_regs(instance->reg_set, buf);
3413 }
3414
3415 static ssize_t
3416 raid_map_id_show(struct device *cdev, struct device_attribute *attr,
3417                           char *buf)
3418 {
3419         struct Scsi_Host *shost = class_to_shost(cdev);
3420         struct megasas_instance *instance =
3421                         (struct megasas_instance *)shost->hostdata;
3422
3423         return snprintf(buf, PAGE_SIZE, "%ld\n",
3424                         (unsigned long)instance->map_id);
3425 }
3426
3427 static DEVICE_ATTR_RW(fw_crash_buffer);
3428 static DEVICE_ATTR_RO(fw_crash_buffer_size);
3429 static DEVICE_ATTR_RW(fw_crash_state);
3430 static DEVICE_ATTR_RO(page_size);
3431 static DEVICE_ATTR_RO(ldio_outstanding);
3432 static DEVICE_ATTR_RO(fw_cmds_outstanding);
3433 static DEVICE_ATTR_RW(enable_sdev_max_qd);
3434 static DEVICE_ATTR_RO(dump_system_regs);
3435 static DEVICE_ATTR_RO(raid_map_id);
3436
3437 static struct device_attribute *megaraid_host_attrs[] = {
3438         &dev_attr_fw_crash_buffer_size,
3439         &dev_attr_fw_crash_buffer,
3440         &dev_attr_fw_crash_state,
3441         &dev_attr_page_size,
3442         &dev_attr_ldio_outstanding,
3443         &dev_attr_fw_cmds_outstanding,
3444         &dev_attr_enable_sdev_max_qd,
3445         &dev_attr_dump_system_regs,
3446         &dev_attr_raid_map_id,
3447         NULL,
3448 };
3449
3450 /*
3451  * Scsi host template for megaraid_sas driver
3452  */
3453 static struct scsi_host_template megasas_template = {
3454
3455         .module = THIS_MODULE,
3456         .name = "Avago SAS based MegaRAID driver",
3457         .proc_name = "megaraid_sas",
3458         .slave_configure = megasas_slave_configure,
3459         .slave_alloc = megasas_slave_alloc,
3460         .slave_destroy = megasas_slave_destroy,
3461         .queuecommand = megasas_queue_command,
3462         .eh_target_reset_handler = megasas_reset_target,
3463         .eh_abort_handler = megasas_task_abort,
3464         .eh_host_reset_handler = megasas_reset_bus_host,
3465         .eh_timed_out = megasas_reset_timer,
3466         .shost_attrs = megaraid_host_attrs,
3467         .bios_param = megasas_bios_param,
3468         .change_queue_depth = scsi_change_queue_depth,
3469         .max_segment_size = 0xffffffff,
3470 };
3471
3472 /**
3473  * megasas_complete_int_cmd -   Completes an internal command
3474  * @instance:                   Adapter soft state
3475  * @cmd:                        Command to be completed
3476  *
3477  * The megasas_issue_blocked_cmd() function waits for a command to complete
3478  * after it issues a command. This function wakes up that waiting routine by
3479  * calling wake_up() on the wait queue.
3480  */
3481 static void
3482 megasas_complete_int_cmd(struct megasas_instance *instance,
3483                          struct megasas_cmd *cmd)
3484 {
3485         if (cmd->cmd_status_drv == DCMD_INIT)
3486                 cmd->cmd_status_drv =
3487                 (cmd->frame->io.cmd_status == MFI_STAT_OK) ?
3488                 DCMD_SUCCESS : DCMD_FAILED;
3489
3490         wake_up(&instance->int_cmd_wait_q);
3491 }
3492
3493 /**
3494  * megasas_complete_abort -     Completes aborting a command
3495  * @instance:                   Adapter soft state
3496  * @cmd:                        Cmd that was issued to abort another cmd
3497  *
3498  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
3499  * after it issues an abort on a previously issued command. This function
3500  * wakes up all functions waiting on the same wait queue.
3501  */
3502 static void
3503 megasas_complete_abort(struct megasas_instance *instance,
3504                        struct megasas_cmd *cmd)
3505 {
3506         if (cmd->sync_cmd) {
3507                 cmd->sync_cmd = 0;
3508                 cmd->cmd_status_drv = DCMD_SUCCESS;
3509                 wake_up(&instance->abort_cmd_wait_q);
3510         }
3511 }
3512
3513 static void
3514 megasas_set_ld_removed_by_fw(struct megasas_instance *instance)
3515 {
3516         uint i;
3517
3518         for (i = 0; (i < MEGASAS_MAX_LD_IDS); i++) {
3519                 if (instance->ld_ids_prev[i] != 0xff &&
3520                     instance->ld_ids_from_raidmap[i] == 0xff) {
3521                         if (megasas_dbg_lvl & LD_PD_DEBUG)
3522                                 dev_info(&instance->pdev->dev,
3523                                          "LD target ID %d removed from RAID map\n", i);
3524                         instance->ld_tgtid_status[i] = LD_TARGET_ID_DELETED;
3525                 }
3526         }
3527 }
3528
3529 /**
3530  * megasas_complete_cmd -       Completes a command
3531  * @instance:                   Adapter soft state
3532  * @cmd:                        Command to be completed
3533  * @alt_status:                 If non-zero, use this value as status to
3534  *                              SCSI mid-layer instead of the value returned
3535  *                              by the FW. This should be used if caller wants
3536  *                              an alternate status (as in the case of aborted
3537  *                              commands)
3538  */
3539 void
3540 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
3541                      u8 alt_status)
3542 {
3543         int exception = 0;
3544         struct megasas_header *hdr = &cmd->frame->hdr;
3545         unsigned long flags;
3546         struct fusion_context *fusion = instance->ctrl_context;
3547         u32 opcode, status;
3548
3549         /* flag for the retry reset */
3550         cmd->retry_for_fw_reset = 0;
3551
3552         if (cmd->scmd)
3553                 cmd->scmd->SCp.ptr = NULL;
3554
3555         switch (hdr->cmd) {
3556         case MFI_CMD_INVALID:
3557                 /* Some older 1068 controller FW may keep a pended
3558                    MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
3559                    when booting the kdump kernel.  Ignore this command to
3560                    prevent a kernel panic on shutdown of the kdump kernel. */
3561                 dev_warn(&instance->pdev->dev, "MFI_CMD_INVALID command "
3562                        "completed\n");
3563                 dev_warn(&instance->pdev->dev, "If you have a controller "
3564                        "other than PERC5, please upgrade your firmware\n");
3565                 break;
3566         case MFI_CMD_PD_SCSI_IO:
3567         case MFI_CMD_LD_SCSI_IO:
3568
3569                 /*
3570                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
3571                  * issued either through an IO path or an IOCTL path. If it
3572                  * was via IOCTL, we will send it to internal completion.
3573                  */
3574                 if (cmd->sync_cmd) {
3575                         cmd->sync_cmd = 0;
3576                         megasas_complete_int_cmd(instance, cmd);
3577                         break;
3578                 }
3579                 fallthrough;
3580
3581         case MFI_CMD_LD_READ:
3582         case MFI_CMD_LD_WRITE:
3583
3584                 if (alt_status) {
3585                         cmd->scmd->result = alt_status << 16;
3586                         exception = 1;
3587                 }
3588
3589                 if (exception) {
3590
3591                         atomic_dec(&instance->fw_outstanding);
3592
3593                         scsi_dma_unmap(cmd->scmd);
3594                         cmd->scmd->scsi_done(cmd->scmd);
3595                         megasas_return_cmd(instance, cmd);
3596
3597                         break;
3598                 }
3599
3600                 switch (hdr->cmd_status) {
3601
3602                 case MFI_STAT_OK:
3603                         cmd->scmd->result = DID_OK << 16;
3604                         break;
3605
3606                 case MFI_STAT_SCSI_IO_FAILED:
3607                 case MFI_STAT_LD_INIT_IN_PROGRESS:
3608                         cmd->scmd->result =
3609                             (DID_ERROR << 16) | hdr->scsi_status;
3610                         break;
3611
3612                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
3613
3614                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
3615
3616                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
3617                                 memset(cmd->scmd->sense_buffer, 0,
3618                                        SCSI_SENSE_BUFFERSIZE);
3619                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
3620                                        hdr->sense_len);
3621
3622                                 cmd->scmd->result |= DRIVER_SENSE << 24;
3623                         }
3624
3625                         break;
3626
3627                 case MFI_STAT_LD_OFFLINE:
3628                 case MFI_STAT_DEVICE_NOT_FOUND:
3629                         cmd->scmd->result = DID_BAD_TARGET << 16;
3630                         break;
3631
3632                 default:
3633                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "MFI FW status %#x\n",
3634                                hdr->cmd_status);
3635                         cmd->scmd->result = DID_ERROR << 16;
3636                         break;
3637                 }
3638
3639                 atomic_dec(&instance->fw_outstanding);
3640
3641                 scsi_dma_unmap(cmd->scmd);
3642                 cmd->scmd->scsi_done(cmd->scmd);
3643                 megasas_return_cmd(instance, cmd);
3644
3645                 break;
3646
3647         case MFI_CMD_SMP:
3648         case MFI_CMD_STP:
3649         case MFI_CMD_NVME:
3650         case MFI_CMD_TOOLBOX:
3651                 megasas_complete_int_cmd(instance, cmd);
3652                 break;
3653
3654         case MFI_CMD_DCMD:
3655                 opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
3656                 /* Check for LD map update */
3657                 if ((opcode == MR_DCMD_LD_MAP_GET_INFO)
3658                         && (cmd->frame->dcmd.mbox.b[1] == 1)) {
3659                         fusion->fast_path_io = 0;
3660                         spin_lock_irqsave(instance->host->host_lock, flags);
3661                         status = cmd->frame->hdr.cmd_status;
3662                         instance->map_update_cmd = NULL;
3663                         if (status != MFI_STAT_OK) {
3664                                 if (status != MFI_STAT_NOT_FOUND)
3665                                         dev_warn(&instance->pdev->dev, "map syncfailed, status = 0x%x\n",
3666                                                cmd->frame->hdr.cmd_status);
3667                                 else {
3668                                         megasas_return_cmd(instance, cmd);
3669                                         spin_unlock_irqrestore(
3670                                                 instance->host->host_lock,
3671                                                 flags);
3672                                         break;
3673                                 }
3674                         }
3675
3676                         megasas_return_cmd(instance, cmd);
3677
3678                         /*
3679                          * Set fast path IO to ZERO.
3680                          * Validate Map will set proper value.
3681                          * Meanwhile all IOs will go as LD IO.
3682                          */
3683                         if (status == MFI_STAT_OK &&
3684                             (MR_ValidateMapInfo(instance, (instance->map_id + 1)))) {
3685                                 instance->map_id++;
3686                                 fusion->fast_path_io = 1;
3687                         } else {
3688                                 fusion->fast_path_io = 0;
3689                         }
3690
3691                         if (instance->adapter_type >= INVADER_SERIES)
3692                                 megasas_set_ld_removed_by_fw(instance);
3693
3694                         megasas_sync_map_info(instance);
3695                         spin_unlock_irqrestore(instance->host->host_lock,
3696                                                flags);
3697
3698                         break;
3699                 }
3700                 if (opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
3701                     opcode == MR_DCMD_CTRL_EVENT_GET) {
3702                         spin_lock_irqsave(&poll_aen_lock, flags);
3703                         megasas_poll_wait_aen = 0;
3704                         spin_unlock_irqrestore(&poll_aen_lock, flags);
3705                 }
3706
3707                 /* FW has an updated PD sequence */
3708                 if ((opcode == MR_DCMD_SYSTEM_PD_MAP_GET_INFO) &&
3709                         (cmd->frame->dcmd.mbox.b[0] == 1)) {
3710
3711                         spin_lock_irqsave(instance->host->host_lock, flags);
3712                         status = cmd->frame->hdr.cmd_status;
3713                         instance->jbod_seq_cmd = NULL;
3714                         megasas_return_cmd(instance, cmd);
3715
3716                         if (status == MFI_STAT_OK) {
3717                                 instance->pd_seq_map_id++;
3718                                 /* Re-register a pd sync seq num cmd */
3719                                 if (megasas_sync_pd_seq_num(instance, true))
3720                                         instance->use_seqnum_jbod_fp = false;
3721                         } else
3722                                 instance->use_seqnum_jbod_fp = false;
3723
3724                         spin_unlock_irqrestore(instance->host->host_lock, flags);
3725                         break;
3726                 }
3727
3728                 /*
3729                  * See if got an event notification
3730                  */
3731                 if (opcode == MR_DCMD_CTRL_EVENT_WAIT)
3732                         megasas_service_aen(instance, cmd);
3733                 else
3734                         megasas_complete_int_cmd(instance, cmd);
3735
3736                 break;
3737
3738         case MFI_CMD_ABORT:
3739                 /*
3740                  * Cmd issued to abort another cmd returned
3741                  */
3742                 megasas_complete_abort(instance, cmd);
3743                 break;
3744
3745         default:
3746                 dev_info(&instance->pdev->dev, "Unknown command completed! [0x%X]\n",
3747                        hdr->cmd);
3748                 megasas_complete_int_cmd(instance, cmd);
3749                 break;
3750         }
3751 }
3752
3753 /**
3754  * megasas_issue_pending_cmds_again -   issue all pending cmds
3755  *                                      in FW again because of the fw reset
3756  * @instance:                           Adapter soft state
3757  */
3758 static inline void
3759 megasas_issue_pending_cmds_again(struct megasas_instance *instance)
3760 {
3761         struct megasas_cmd *cmd;
3762         struct list_head clist_local;
3763         union megasas_evt_class_locale class_locale;
3764         unsigned long flags;
3765         u32 seq_num;
3766
3767         INIT_LIST_HEAD(&clist_local);
3768         spin_lock_irqsave(&instance->hba_lock, flags);
3769         list_splice_init(&instance->internal_reset_pending_q, &clist_local);
3770         spin_unlock_irqrestore(&instance->hba_lock, flags);
3771
3772         while (!list_empty(&clist_local)) {
3773                 cmd = list_entry((&clist_local)->next,
3774                                         struct megasas_cmd, list);
3775                 list_del_init(&cmd->list);
3776
3777                 if (cmd->sync_cmd || cmd->scmd) {
3778                         dev_notice(&instance->pdev->dev, "command %p, %p:%d"
3779                                 "detected to be pending while HBA reset\n",
3780                                         cmd, cmd->scmd, cmd->sync_cmd);
3781
3782                         cmd->retry_for_fw_reset++;
3783
3784                         if (cmd->retry_for_fw_reset == 3) {
3785                                 dev_notice(&instance->pdev->dev, "cmd %p, %p:%d"
3786                                         "was tried multiple times during reset."
3787                                         "Shutting down the HBA\n",
3788                                         cmd, cmd->scmd, cmd->sync_cmd);
3789                                 instance->instancet->disable_intr(instance);
3790                                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3791                                 megaraid_sas_kill_hba(instance);
3792                                 return;
3793                         }
3794                 }
3795
3796                 if (cmd->sync_cmd == 1) {
3797                         if (cmd->scmd) {
3798                                 dev_notice(&instance->pdev->dev, "unexpected"
3799                                         "cmd attached to internal command!\n");
3800                         }
3801                         dev_notice(&instance->pdev->dev, "%p synchronous cmd"
3802                                                 "on the internal reset queue,"
3803                                                 "issue it again.\n", cmd);
3804                         cmd->cmd_status_drv = DCMD_INIT;
3805                         instance->instancet->fire_cmd(instance,
3806                                                         cmd->frame_phys_addr,
3807                                                         0, instance->reg_set);
3808                 } else if (cmd->scmd) {
3809                         dev_notice(&instance->pdev->dev, "%p scsi cmd [%02x]"
3810                         "detected on the internal queue, issue again.\n",
3811                         cmd, cmd->scmd->cmnd[0]);
3812
3813                         atomic_inc(&instance->fw_outstanding);
3814                         instance->instancet->fire_cmd(instance,
3815                                         cmd->frame_phys_addr,
3816                                         cmd->frame_count-1, instance->reg_set);
3817                 } else {
3818                         dev_notice(&instance->pdev->dev, "%p unexpected cmd on the"
3819                                 "internal reset defer list while re-issue!!\n",
3820                                 cmd);
3821                 }
3822         }
3823
3824         if (instance->aen_cmd) {
3825                 dev_notice(&instance->pdev->dev, "aen_cmd in def process\n");
3826                 megasas_return_cmd(instance, instance->aen_cmd);
3827
3828                 instance->aen_cmd = NULL;
3829         }
3830
3831         /*
3832          * Initiate AEN (Asynchronous Event Notification)
3833          */
3834         seq_num = instance->last_seq_num;
3835         class_locale.members.reserved = 0;
3836         class_locale.members.locale = MR_EVT_LOCALE_ALL;
3837         class_locale.members.class = MR_EVT_CLASS_DEBUG;
3838
3839         megasas_register_aen(instance, seq_num, class_locale.word);
3840 }
3841
3842 /*
3843  * Move the internal reset pending commands to a deferred queue.
3844  *
3845  * We move the commands pending at internal reset time to a
3846  * pending queue. This queue would be flushed after successful
3847  * completion of the internal reset sequence. if the internal reset
3848  * did not complete in time, the kernel reset handler would flush
3849  * these commands.
3850  */
3851 static void
3852 megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
3853 {
3854         struct megasas_cmd *cmd;
3855         int i;
3856         u16 max_cmd = instance->max_fw_cmds;
3857         u32 defer_index;
3858         unsigned long flags;
3859
3860         defer_index = 0;
3861         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
3862         for (i = 0; i < max_cmd; i++) {
3863                 cmd = instance->cmd_list[i];
3864                 if (cmd->sync_cmd == 1 || cmd->scmd) {
3865                         dev_notice(&instance->pdev->dev, "moving cmd[%d]:%p:%d:%p"
3866                                         "on the defer queue as internal\n",
3867                                 defer_index, cmd, cmd->sync_cmd, cmd->scmd);
3868
3869                         if (!list_empty(&cmd->list)) {
3870                                 dev_notice(&instance->pdev->dev, "ERROR while"
3871                                         " moving this cmd:%p, %d %p, it was"
3872                                         "discovered on some list?\n",
3873                                         cmd, cmd->sync_cmd, cmd->scmd);
3874
3875                                 list_del_init(&cmd->list);
3876                         }
3877                         defer_index++;
3878                         list_add_tail(&cmd->list,
3879                                 &instance->internal_reset_pending_q);
3880                 }
3881         }
3882         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
3883 }
3884
3885
3886 static void
3887 process_fw_state_change_wq(struct work_struct *work)
3888 {
3889         struct megasas_instance *instance =
3890                 container_of(work, struct megasas_instance, work_init);
3891         u32 wait;
3892         unsigned long flags;
3893
3894     if (atomic_read(&instance->adprecovery) != MEGASAS_ADPRESET_SM_INFAULT) {
3895                 dev_notice(&instance->pdev->dev, "error, recovery st %x\n",
3896                                 atomic_read(&instance->adprecovery));
3897                 return ;
3898         }
3899
3900         if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) {
3901                 dev_notice(&instance->pdev->dev, "FW detected to be in fault"
3902                                         "state, restarting it...\n");
3903
3904                 instance->instancet->disable_intr(instance);
3905                 atomic_set(&instance->fw_outstanding, 0);
3906
3907                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3908                 instance->instancet->adp_reset(instance, instance->reg_set);
3909                 atomic_set(&instance->fw_reset_no_pci_access, 0);
3910
3911                 dev_notice(&instance->pdev->dev, "FW restarted successfully,"
3912                                         "initiating next stage...\n");
3913
3914                 dev_notice(&instance->pdev->dev, "HBA recovery state machine,"
3915                                         "state 2 starting...\n");
3916
3917                 /* waiting for about 20 second before start the second init */
3918                 for (wait = 0; wait < 30; wait++) {
3919                         msleep(1000);
3920                 }
3921
3922                 if (megasas_transition_to_ready(instance, 1)) {
3923                         dev_notice(&instance->pdev->dev, "adapter not ready\n");
3924
3925                         atomic_set(&instance->fw_reset_no_pci_access, 1);
3926                         megaraid_sas_kill_hba(instance);
3927                         return ;
3928                 }
3929
3930                 if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
3931                         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
3932                         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
3933                         ) {
3934                         *instance->consumer = *instance->producer;
3935                 } else {
3936                         *instance->consumer = 0;
3937                         *instance->producer = 0;
3938                 }
3939
3940                 megasas_issue_init_mfi(instance);
3941
3942                 spin_lock_irqsave(&instance->hba_lock, flags);
3943                 atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
3944                 spin_unlock_irqrestore(&instance->hba_lock, flags);
3945                 instance->instancet->enable_intr(instance);
3946
3947                 megasas_issue_pending_cmds_again(instance);
3948                 instance->issuepend_done = 1;
3949         }
3950 }
3951
3952 /**
3953  * megasas_deplete_reply_queue -        Processes all completed commands
3954  * @instance:                           Adapter soft state
3955  * @alt_status:                         Alternate status to be returned to
3956  *                                      SCSI mid-layer instead of the status
3957  *                                      returned by the FW
3958  * Note: this must be called with hba lock held
3959  */
3960 static int
3961 megasas_deplete_reply_queue(struct megasas_instance *instance,
3962                                         u8 alt_status)
3963 {
3964         u32 mfiStatus;
3965         u32 fw_state;
3966
3967         if ((mfiStatus = instance->instancet->check_reset(instance,
3968                                         instance->reg_set)) == 1) {
3969                 return IRQ_HANDLED;
3970         }
3971
3972         mfiStatus = instance->instancet->clear_intr(instance);
3973         if (mfiStatus == 0) {
3974                 /* Hardware may not set outbound_intr_status in MSI-X mode */
3975                 if (!instance->msix_vectors)
3976                         return IRQ_NONE;
3977         }
3978
3979         instance->mfiStatus = mfiStatus;
3980
3981         if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
3982                 fw_state = instance->instancet->read_fw_status_reg(
3983                                 instance) & MFI_STATE_MASK;
3984
3985                 if (fw_state != MFI_STATE_FAULT) {
3986                         dev_notice(&instance->pdev->dev, "fw state:%x\n",
3987                                                 fw_state);
3988                 }
3989
3990                 if ((fw_state == MFI_STATE_FAULT) &&
3991                                 (instance->disableOnlineCtrlReset == 0)) {
3992                         dev_notice(&instance->pdev->dev, "wait adp restart\n");
3993
3994                         if ((instance->pdev->device ==
3995                                         PCI_DEVICE_ID_LSI_SAS1064R) ||
3996                                 (instance->pdev->device ==
3997                                         PCI_DEVICE_ID_DELL_PERC5) ||
3998                                 (instance->pdev->device ==
3999                                         PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
4000
4001                                 *instance->consumer =
4002                                         cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
4003                         }
4004
4005
4006                         instance->instancet->disable_intr(instance);
4007                         atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
4008                         instance->issuepend_done = 0;
4009
4010                         atomic_set(&instance->fw_outstanding, 0);
4011                         megasas_internal_reset_defer_cmds(instance);
4012
4013                         dev_notice(&instance->pdev->dev, "fwState=%x, stage:%d\n",
4014                                         fw_state, atomic_read(&instance->adprecovery));
4015
4016                         schedule_work(&instance->work_init);
4017                         return IRQ_HANDLED;
4018
4019                 } else {
4020                         dev_notice(&instance->pdev->dev, "fwstate:%x, dis_OCR=%x\n",
4021                                 fw_state, instance->disableOnlineCtrlReset);
4022                 }
4023         }
4024
4025         tasklet_schedule(&instance->isr_tasklet);
4026         return IRQ_HANDLED;
4027 }
4028
4029 /**
4030  * megasas_isr - isr entry point
4031  * @irq:        IRQ number
4032  * @devp:       IRQ context address
4033  */
4034 static irqreturn_t megasas_isr(int irq, void *devp)
4035 {
4036         struct megasas_irq_context *irq_context = devp;
4037         struct megasas_instance *instance = irq_context->instance;
4038         unsigned long flags;
4039         irqreturn_t rc;
4040
4041         if (atomic_read(&instance->fw_reset_no_pci_access))
4042                 return IRQ_HANDLED;
4043
4044         spin_lock_irqsave(&instance->hba_lock, flags);
4045         rc = megasas_deplete_reply_queue(instance, DID_OK);
4046         spin_unlock_irqrestore(&instance->hba_lock, flags);
4047
4048         return rc;
4049 }
4050
4051 /**
4052  * megasas_transition_to_ready -        Move the FW to READY state
4053  * @instance:                           Adapter soft state
4054  * @ocr:                                Adapter reset state
4055  *
4056  * During the initialization, FW passes can potentially be in any one of
4057  * several possible states. If the FW in operational, waiting-for-handshake
4058  * states, driver must take steps to bring it to ready state. Otherwise, it
4059  * has to wait for the ready state.
4060  */
4061 int
4062 megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
4063 {
4064         int i;
4065         u8 max_wait;
4066         u32 fw_state;
4067         u32 abs_state, curr_abs_state;
4068
4069         abs_state = instance->instancet->read_fw_status_reg(instance);
4070         fw_state = abs_state & MFI_STATE_MASK;
4071
4072         if (fw_state != MFI_STATE_READY)
4073                 dev_info(&instance->pdev->dev, "Waiting for FW to come to ready"
4074                        " state\n");
4075
4076         while (fw_state != MFI_STATE_READY) {
4077
4078                 switch (fw_state) {
4079
4080                 case MFI_STATE_FAULT:
4081                         dev_printk(KERN_ERR, &instance->pdev->dev,
4082                                    "FW in FAULT state, Fault code:0x%x subcode:0x%x func:%s\n",
4083                                    abs_state & MFI_STATE_FAULT_CODE,
4084                                    abs_state & MFI_STATE_FAULT_SUBCODE, __func__);
4085                         if (ocr) {
4086                                 max_wait = MEGASAS_RESET_WAIT_TIME;
4087                                 break;
4088                         } else {
4089                                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4090                                 megasas_dump_reg_set(instance->reg_set);
4091                                 return -ENODEV;
4092                         }
4093
4094                 case MFI_STATE_WAIT_HANDSHAKE:
4095                         /*
4096                          * Set the CLR bit in inbound doorbell
4097                          */
4098                         if ((instance->pdev->device ==
4099                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4100                                 (instance->pdev->device ==
4101                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
4102                                 (instance->adapter_type != MFI_SERIES))
4103                                 writel(
4104                                   MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
4105                                   &instance->reg_set->doorbell);
4106                         else
4107                                 writel(
4108                                     MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
4109                                         &instance->reg_set->inbound_doorbell);
4110
4111                         max_wait = MEGASAS_RESET_WAIT_TIME;
4112                         break;
4113
4114                 case MFI_STATE_BOOT_MESSAGE_PENDING:
4115                         if ((instance->pdev->device ==
4116                              PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4117                                 (instance->pdev->device ==
4118                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
4119                                 (instance->adapter_type != MFI_SERIES))
4120                                 writel(MFI_INIT_HOTPLUG,
4121                                        &instance->reg_set->doorbell);
4122                         else
4123                                 writel(MFI_INIT_HOTPLUG,
4124                                         &instance->reg_set->inbound_doorbell);
4125
4126                         max_wait = MEGASAS_RESET_WAIT_TIME;
4127                         break;
4128
4129                 case MFI_STATE_OPERATIONAL:
4130                         /*
4131                          * Bring it to READY state; assuming max wait 10 secs
4132                          */
4133                         instance->instancet->disable_intr(instance);
4134                         if ((instance->pdev->device ==
4135                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4136                                 (instance->pdev->device ==
4137                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)  ||
4138                                 (instance->adapter_type != MFI_SERIES)) {
4139                                 writel(MFI_RESET_FLAGS,
4140                                         &instance->reg_set->doorbell);
4141
4142                                 if (instance->adapter_type != MFI_SERIES) {
4143                                         for (i = 0; i < (10 * 1000); i += 20) {
4144                                                 if (megasas_readl(
4145                                                             instance,
4146                                                             &instance->
4147                                                             reg_set->
4148                                                             doorbell) & 1)
4149                                                         msleep(20);
4150                                                 else
4151                                                         break;
4152                                         }
4153                                 }
4154                         } else
4155                                 writel(MFI_RESET_FLAGS,
4156                                         &instance->reg_set->inbound_doorbell);
4157
4158                         max_wait = MEGASAS_RESET_WAIT_TIME;
4159                         break;
4160
4161                 case MFI_STATE_UNDEFINED:
4162                         /*
4163                          * This state should not last for more than 2 seconds
4164                          */
4165                         max_wait = MEGASAS_RESET_WAIT_TIME;
4166                         break;
4167
4168                 case MFI_STATE_BB_INIT:
4169                         max_wait = MEGASAS_RESET_WAIT_TIME;
4170                         break;
4171
4172                 case MFI_STATE_FW_INIT:
4173                         max_wait = MEGASAS_RESET_WAIT_TIME;
4174                         break;
4175
4176                 case MFI_STATE_FW_INIT_2:
4177                         max_wait = MEGASAS_RESET_WAIT_TIME;
4178                         break;
4179
4180                 case MFI_STATE_DEVICE_SCAN:
4181                         max_wait = MEGASAS_RESET_WAIT_TIME;
4182                         break;
4183
4184                 case MFI_STATE_FLUSH_CACHE:
4185                         max_wait = MEGASAS_RESET_WAIT_TIME;
4186                         break;
4187
4188                 default:
4189                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "Unknown state 0x%x\n",
4190                                fw_state);
4191                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4192                         megasas_dump_reg_set(instance->reg_set);
4193                         return -ENODEV;
4194                 }
4195
4196                 /*
4197                  * The cur_state should not last for more than max_wait secs
4198                  */
4199                 for (i = 0; i < max_wait * 50; i++) {
4200                         curr_abs_state = instance->instancet->
4201                                 read_fw_status_reg(instance);
4202
4203                         if (abs_state == curr_abs_state) {
4204                                 msleep(20);
4205                         } else
4206                                 break;
4207                 }
4208
4209                 /*
4210                  * Return error if fw_state hasn't changed after max_wait
4211                  */
4212                 if (curr_abs_state == abs_state) {
4213                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "FW state [%d] hasn't changed "
4214                                "in %d secs\n", fw_state, max_wait);
4215                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4216                         megasas_dump_reg_set(instance->reg_set);
4217                         return -ENODEV;
4218                 }
4219
4220                 abs_state = curr_abs_state;
4221                 fw_state = curr_abs_state & MFI_STATE_MASK;
4222         }
4223         dev_info(&instance->pdev->dev, "FW now in Ready state\n");
4224
4225         return 0;
4226 }
4227
4228 /**
4229  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
4230  * @instance:                           Adapter soft state
4231  */
4232 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
4233 {
4234         int i;
4235         u16 max_cmd = instance->max_mfi_cmds;
4236         struct megasas_cmd *cmd;
4237
4238         if (!instance->frame_dma_pool)
4239                 return;
4240
4241         /*
4242          * Return all frames to pool
4243          */
4244         for (i = 0; i < max_cmd; i++) {
4245
4246                 cmd = instance->cmd_list[i];
4247
4248                 if (cmd->frame)
4249                         dma_pool_free(instance->frame_dma_pool, cmd->frame,
4250                                       cmd->frame_phys_addr);
4251
4252                 if (cmd->sense)
4253                         dma_pool_free(instance->sense_dma_pool, cmd->sense,
4254                                       cmd->sense_phys_addr);
4255         }
4256
4257         /*
4258          * Now destroy the pool itself
4259          */
4260         dma_pool_destroy(instance->frame_dma_pool);
4261         dma_pool_destroy(instance->sense_dma_pool);
4262
4263         instance->frame_dma_pool = NULL;
4264         instance->sense_dma_pool = NULL;
4265 }
4266
4267 /**
4268  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
4269  * @instance:                   Adapter soft state
4270  *
4271  * Each command packet has an embedded DMA memory buffer that is used for
4272  * filling MFI frame and the SG list that immediately follows the frame. This
4273  * function creates those DMA memory buffers for each command packet by using
4274  * PCI pool facility.
4275  */
4276 static int megasas_create_frame_pool(struct megasas_instance *instance)
4277 {
4278         int i;
4279         u16 max_cmd;
4280         u32 frame_count;
4281         struct megasas_cmd *cmd;
4282
4283         max_cmd = instance->max_mfi_cmds;
4284
4285         /*
4286          * For MFI controllers.
4287          * max_num_sge = 60
4288          * max_sge_sz  = 16 byte (sizeof megasas_sge_skinny)
4289          * Total 960 byte (15 MFI frame of 64 byte)
4290          *
4291          * Fusion adapter require only 3 extra frame.
4292          * max_num_sge = 16 (defined as MAX_IOCTL_SGE)
4293          * max_sge_sz  = 12 byte (sizeof  megasas_sge64)
4294          * Total 192 byte (3 MFI frame of 64 byte)
4295          */
4296         frame_count = (instance->adapter_type == MFI_SERIES) ?
4297                         (15 + 1) : (3 + 1);
4298         instance->mfi_frame_size = MEGAMFI_FRAME_SIZE * frame_count;
4299         /*
4300          * Use DMA pool facility provided by PCI layer
4301          */
4302         instance->frame_dma_pool = dma_pool_create("megasas frame pool",
4303                                         &instance->pdev->dev,
4304                                         instance->mfi_frame_size, 256, 0);
4305
4306         if (!instance->frame_dma_pool) {
4307                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup frame pool\n");
4308                 return -ENOMEM;
4309         }
4310
4311         instance->sense_dma_pool = dma_pool_create("megasas sense pool",
4312                                                    &instance->pdev->dev, 128,
4313                                                    4, 0);
4314
4315         if (!instance->sense_dma_pool) {
4316                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup sense pool\n");
4317
4318                 dma_pool_destroy(instance->frame_dma_pool);
4319                 instance->frame_dma_pool = NULL;
4320
4321                 return -ENOMEM;
4322         }
4323
4324         /*
4325          * Allocate and attach a frame to each of the commands in cmd_list.
4326          * By making cmd->index as the context instead of the &cmd, we can
4327          * always use 32bit context regardless of the architecture
4328          */
4329         for (i = 0; i < max_cmd; i++) {
4330
4331                 cmd = instance->cmd_list[i];
4332
4333                 cmd->frame = dma_pool_zalloc(instance->frame_dma_pool,
4334                                             GFP_KERNEL, &cmd->frame_phys_addr);
4335
4336                 cmd->sense = dma_pool_alloc(instance->sense_dma_pool,
4337                                             GFP_KERNEL, &cmd->sense_phys_addr);
4338
4339                 /*
4340                  * megasas_teardown_frame_pool() takes care of freeing
4341                  * whatever has been allocated
4342                  */
4343                 if (!cmd->frame || !cmd->sense) {
4344                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "dma_pool_alloc failed\n");
4345                         megasas_teardown_frame_pool(instance);
4346                         return -ENOMEM;
4347                 }
4348
4349                 cmd->frame->io.context = cpu_to_le32(cmd->index);
4350                 cmd->frame->io.pad_0 = 0;
4351                 if ((instance->adapter_type == MFI_SERIES) && reset_devices)
4352                         cmd->frame->hdr.cmd = MFI_CMD_INVALID;
4353         }
4354
4355         return 0;
4356 }
4357
4358 /**
4359  * megasas_free_cmds -  Free all the cmds in the free cmd pool
4360  * @instance:           Adapter soft state
4361  */
4362 void megasas_free_cmds(struct megasas_instance *instance)
4363 {
4364         int i;
4365
4366         /* First free the MFI frame pool */
4367         megasas_teardown_frame_pool(instance);
4368
4369         /* Free all the commands in the cmd_list */
4370         for (i = 0; i < instance->max_mfi_cmds; i++)
4371
4372                 kfree(instance->cmd_list[i]);
4373
4374         /* Free the cmd_list buffer itself */
4375         kfree(instance->cmd_list);
4376         instance->cmd_list = NULL;
4377
4378         INIT_LIST_HEAD(&instance->cmd_pool);
4379 }
4380
4381 /**
4382  * megasas_alloc_cmds - Allocates the command packets
4383  * @instance:           Adapter soft state
4384  *
4385  * Each command that is issued to the FW, whether IO commands from the OS or
4386  * internal commands like IOCTLs, are wrapped in local data structure called
4387  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
4388  * the FW.
4389  *
4390  * Each frame has a 32-bit field called context (tag). This context is used
4391  * to get back the megasas_cmd from the frame when a frame gets completed in
4392  * the ISR. Typically the address of the megasas_cmd itself would be used as
4393  * the context. But we wanted to keep the differences between 32 and 64 bit
4394  * systems to the mininum. We always use 32 bit integers for the context. In
4395  * this driver, the 32 bit values are the indices into an array cmd_list.
4396  * This array is used only to look up the megasas_cmd given the context. The
4397  * free commands themselves are maintained in a linked list called cmd_pool.
4398  */
4399 int megasas_alloc_cmds(struct megasas_instance *instance)
4400 {
4401         int i;
4402         int j;
4403         u16 max_cmd;
4404         struct megasas_cmd *cmd;
4405
4406         max_cmd = instance->max_mfi_cmds;
4407
4408         /*
4409          * instance->cmd_list is an array of struct megasas_cmd pointers.
4410          * Allocate the dynamic array first and then allocate individual
4411          * commands.
4412          */
4413         instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
4414
4415         if (!instance->cmd_list) {
4416                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
4417                 return -ENOMEM;
4418         }
4419
4420         memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
4421
4422         for (i = 0; i < max_cmd; i++) {
4423                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
4424                                                 GFP_KERNEL);
4425
4426                 if (!instance->cmd_list[i]) {
4427
4428                         for (j = 0; j < i; j++)
4429                                 kfree(instance->cmd_list[j]);
4430
4431                         kfree(instance->cmd_list);
4432                         instance->cmd_list = NULL;
4433
4434                         return -ENOMEM;
4435                 }
4436         }
4437
4438         for (i = 0; i < max_cmd; i++) {
4439                 cmd = instance->cmd_list[i];
4440                 memset(cmd, 0, sizeof(struct megasas_cmd));
4441                 cmd->index = i;
4442                 cmd->scmd = NULL;
4443                 cmd->instance = instance;
4444
4445                 list_add_tail(&cmd->list, &instance->cmd_pool);
4446         }
4447
4448         /*
4449          * Create a frame pool and assign one frame to each cmd
4450          */
4451         if (megasas_create_frame_pool(instance)) {
4452                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
4453                 megasas_free_cmds(instance);
4454                 return -ENOMEM;
4455         }
4456
4457         return 0;
4458 }
4459
4460 /*
4461  * dcmd_timeout_ocr_possible -  Check if OCR is possible based on Driver/FW state.
4462  * @instance:                           Adapter soft state
4463  *
4464  * Return 0 for only Fusion adapter, if driver load/unload is not in progress
4465  * or FW is not under OCR.
4466  */
4467 inline int
4468 dcmd_timeout_ocr_possible(struct megasas_instance *instance) {
4469
4470         if (instance->adapter_type == MFI_SERIES)
4471                 return KILL_ADAPTER;
4472         else if (instance->unload ||
4473                         test_bit(MEGASAS_FUSION_OCR_NOT_POSSIBLE,
4474                                  &instance->reset_flags))
4475                 return IGNORE_TIMEOUT;
4476         else
4477                 return INITIATE_OCR;
4478 }
4479
4480 static void
4481 megasas_get_pd_info(struct megasas_instance *instance, struct scsi_device *sdev)
4482 {
4483         int ret;
4484         struct megasas_cmd *cmd;
4485         struct megasas_dcmd_frame *dcmd;
4486
4487         struct MR_PRIV_DEVICE *mr_device_priv_data;
4488         u16 device_id = 0;
4489
4490         device_id = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id;
4491         cmd = megasas_get_cmd(instance);
4492
4493         if (!cmd) {
4494                 dev_err(&instance->pdev->dev, "Failed to get cmd %s\n", __func__);
4495                 return;
4496         }
4497
4498         dcmd = &cmd->frame->dcmd;
4499
4500         memset(instance->pd_info, 0, sizeof(*instance->pd_info));
4501         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4502
4503         dcmd->mbox.s[0] = cpu_to_le16(device_id);
4504         dcmd->cmd = MFI_CMD_DCMD;
4505         dcmd->cmd_status = 0xFF;
4506         dcmd->sge_count = 1;
4507         dcmd->flags = MFI_FRAME_DIR_READ;
4508         dcmd->timeout = 0;
4509         dcmd->pad_0 = 0;
4510         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_PD_INFO));
4511         dcmd->opcode = cpu_to_le32(MR_DCMD_PD_GET_INFO);
4512
4513         megasas_set_dma_settings(instance, dcmd, instance->pd_info_h,
4514                                  sizeof(struct MR_PD_INFO));
4515
4516         if ((instance->adapter_type != MFI_SERIES) &&
4517             !instance->mask_interrupts)
4518                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4519         else
4520                 ret = megasas_issue_polled(instance, cmd);
4521
4522         switch (ret) {
4523         case DCMD_SUCCESS:
4524                 mr_device_priv_data = sdev->hostdata;
4525                 le16_to_cpus((u16 *)&instance->pd_info->state.ddf.pdType);
4526                 mr_device_priv_data->interface_type =
4527                                 instance->pd_info->state.ddf.pdType.intf;
4528                 break;
4529
4530         case DCMD_TIMEOUT:
4531
4532                 switch (dcmd_timeout_ocr_possible(instance)) {
4533                 case INITIATE_OCR:
4534                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4535                         mutex_unlock(&instance->reset_mutex);
4536                         megasas_reset_fusion(instance->host,
4537                                 MFI_IO_TIMEOUT_OCR);
4538                         mutex_lock(&instance->reset_mutex);
4539                         break;
4540                 case KILL_ADAPTER:
4541                         megaraid_sas_kill_hba(instance);
4542                         break;
4543                 case IGNORE_TIMEOUT:
4544                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4545                                 __func__, __LINE__);
4546                         break;
4547                 }
4548
4549                 break;
4550         }
4551
4552         if (ret != DCMD_TIMEOUT)
4553                 megasas_return_cmd(instance, cmd);
4554
4555         return;
4556 }
4557 /*
4558  * megasas_get_pd_list_info -   Returns FW's pd_list structure
4559  * @instance:                           Adapter soft state
4560  * @pd_list:                            pd_list structure
4561  *
4562  * Issues an internal command (DCMD) to get the FW's controller PD
4563  * list structure.  This information is mainly used to find out SYSTEM
4564  * supported by the FW.
4565  */
4566 static int
4567 megasas_get_pd_list(struct megasas_instance *instance)
4568 {
4569         int ret = 0, pd_index = 0;
4570         struct megasas_cmd *cmd;
4571         struct megasas_dcmd_frame *dcmd;
4572         struct MR_PD_LIST *ci;
4573         struct MR_PD_ADDRESS *pd_addr;
4574
4575         if (instance->pd_list_not_supported) {
4576                 dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4577                 "not supported by firmware\n");
4578                 return ret;
4579         }
4580
4581         ci = instance->pd_list_buf;
4582
4583         cmd = megasas_get_cmd(instance);
4584
4585         if (!cmd) {
4586                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "(get_pd_list): Failed to get cmd\n");
4587                 return -ENOMEM;
4588         }
4589
4590         dcmd = &cmd->frame->dcmd;
4591
4592         memset(ci, 0, sizeof(*ci));
4593         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4594
4595         dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
4596         dcmd->mbox.b[1] = 0;
4597         dcmd->cmd = MFI_CMD_DCMD;
4598         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4599         dcmd->sge_count = 1;
4600         dcmd->flags = MFI_FRAME_DIR_READ;
4601         dcmd->timeout = 0;
4602         dcmd->pad_0 = 0;
4603         dcmd->data_xfer_len = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
4604         dcmd->opcode = cpu_to_le32(MR_DCMD_PD_LIST_QUERY);
4605
4606         megasas_set_dma_settings(instance, dcmd, instance->pd_list_buf_h,
4607                                  (MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST)));
4608
4609         if ((instance->adapter_type != MFI_SERIES) &&
4610             !instance->mask_interrupts)
4611                 ret = megasas_issue_blocked_cmd(instance, cmd,
4612                         MFI_IO_TIMEOUT_SECS);
4613         else
4614                 ret = megasas_issue_polled(instance, cmd);
4615
4616         switch (ret) {
4617         case DCMD_FAILED:
4618                 dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4619                         "failed/not supported by firmware\n");
4620
4621                 if (instance->adapter_type != MFI_SERIES)
4622                         megaraid_sas_kill_hba(instance);
4623                 else
4624                         instance->pd_list_not_supported = 1;
4625                 break;
4626         case DCMD_TIMEOUT:
4627
4628                 switch (dcmd_timeout_ocr_possible(instance)) {
4629                 case INITIATE_OCR:
4630                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4631                         /*
4632                          * DCMD failed from AEN path.
4633                          * AEN path already hold reset_mutex to avoid PCI access
4634                          * while OCR is in progress.
4635                          */
4636                         mutex_unlock(&instance->reset_mutex);
4637                         megasas_reset_fusion(instance->host,
4638                                                 MFI_IO_TIMEOUT_OCR);
4639                         mutex_lock(&instance->reset_mutex);
4640                         break;
4641                 case KILL_ADAPTER:
4642                         megaraid_sas_kill_hba(instance);
4643                         break;
4644                 case IGNORE_TIMEOUT:
4645                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d \n",
4646                                 __func__, __LINE__);
4647                         break;
4648                 }
4649
4650                 break;
4651
4652         case DCMD_SUCCESS:
4653                 pd_addr = ci->addr;
4654                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4655                         dev_info(&instance->pdev->dev, "%s, sysPD count: 0x%x\n",
4656                                  __func__, le32_to_cpu(ci->count));
4657
4658                 if ((le32_to_cpu(ci->count) >
4659                         (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL)))
4660                         break;
4661
4662                 memset(instance->local_pd_list, 0,
4663                                 MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
4664
4665                 for (pd_index = 0; pd_index < le32_to_cpu(ci->count); pd_index++) {
4666                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].tid     =
4667                                         le16_to_cpu(pd_addr->deviceId);
4668                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveType       =
4669                                         pd_addr->scsiDevType;
4670                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveState      =
4671                                         MR_PD_STATE_SYSTEM;
4672                         if (megasas_dbg_lvl & LD_PD_DEBUG)
4673                                 dev_info(&instance->pdev->dev,
4674                                          "PD%d: targetID: 0x%03x deviceType:0x%x\n",
4675                                          pd_index, le16_to_cpu(pd_addr->deviceId),
4676                                          pd_addr->scsiDevType);
4677                         pd_addr++;
4678                 }
4679
4680                 memcpy(instance->pd_list, instance->local_pd_list,
4681                         sizeof(instance->pd_list));
4682                 break;
4683
4684         }
4685
4686         if (ret != DCMD_TIMEOUT)
4687                 megasas_return_cmd(instance, cmd);
4688
4689         return ret;
4690 }
4691
4692 /*
4693  * megasas_get_ld_list_info -   Returns FW's ld_list structure
4694  * @instance:                           Adapter soft state
4695  * @ld_list:                            ld_list structure
4696  *
4697  * Issues an internal command (DCMD) to get the FW's controller PD
4698  * list structure.  This information is mainly used to find out SYSTEM
4699  * supported by the FW.
4700  */
4701 static int
4702 megasas_get_ld_list(struct megasas_instance *instance)
4703 {
4704         int ret = 0, ld_index = 0, ids = 0;
4705         struct megasas_cmd *cmd;
4706         struct megasas_dcmd_frame *dcmd;
4707         struct MR_LD_LIST *ci;
4708         dma_addr_t ci_h = 0;
4709         u32 ld_count;
4710
4711         ci = instance->ld_list_buf;
4712         ci_h = instance->ld_list_buf_h;
4713
4714         cmd = megasas_get_cmd(instance);
4715
4716         if (!cmd) {
4717                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_list: Failed to get cmd\n");
4718                 return -ENOMEM;
4719         }
4720
4721         dcmd = &cmd->frame->dcmd;
4722
4723         memset(ci, 0, sizeof(*ci));
4724         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4725
4726         if (instance->supportmax256vd)
4727                 dcmd->mbox.b[0] = 1;
4728         dcmd->cmd = MFI_CMD_DCMD;
4729         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4730         dcmd->sge_count = 1;
4731         dcmd->flags = MFI_FRAME_DIR_READ;
4732         dcmd->timeout = 0;
4733         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_LIST));
4734         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_GET_LIST);
4735         dcmd->pad_0  = 0;
4736
4737         megasas_set_dma_settings(instance, dcmd, ci_h,
4738                                  sizeof(struct MR_LD_LIST));
4739
4740         if ((instance->adapter_type != MFI_SERIES) &&
4741             !instance->mask_interrupts)
4742                 ret = megasas_issue_blocked_cmd(instance, cmd,
4743                         MFI_IO_TIMEOUT_SECS);
4744         else
4745                 ret = megasas_issue_polled(instance, cmd);
4746
4747         ld_count = le32_to_cpu(ci->ldCount);
4748
4749         switch (ret) {
4750         case DCMD_FAILED:
4751                 megaraid_sas_kill_hba(instance);
4752                 break;
4753         case DCMD_TIMEOUT:
4754
4755                 switch (dcmd_timeout_ocr_possible(instance)) {
4756                 case INITIATE_OCR:
4757                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4758                         /*
4759                          * DCMD failed from AEN path.
4760                          * AEN path already hold reset_mutex to avoid PCI access
4761                          * while OCR is in progress.
4762                          */
4763                         mutex_unlock(&instance->reset_mutex);
4764                         megasas_reset_fusion(instance->host,
4765                                                 MFI_IO_TIMEOUT_OCR);
4766                         mutex_lock(&instance->reset_mutex);
4767                         break;
4768                 case KILL_ADAPTER:
4769                         megaraid_sas_kill_hba(instance);
4770                         break;
4771                 case IGNORE_TIMEOUT:
4772                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4773                                 __func__, __LINE__);
4774                         break;
4775                 }
4776
4777                 break;
4778
4779         case DCMD_SUCCESS:
4780                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4781                         dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4782                                  __func__, ld_count);
4783
4784                 if (ld_count > instance->fw_supported_vd_count)
4785                         break;
4786
4787                 memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
4788
4789                 for (ld_index = 0; ld_index < ld_count; ld_index++) {
4790                         if (ci->ldList[ld_index].state != 0) {
4791                                 ids = ci->ldList[ld_index].ref.targetId;
4792                                 instance->ld_ids[ids] = ci->ldList[ld_index].ref.targetId;
4793                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4794                                         dev_info(&instance->pdev->dev,
4795                                                  "LD%d: targetID: 0x%03x\n",
4796                                                  ld_index, ids);
4797                         }
4798                 }
4799
4800                 break;
4801         }
4802
4803         if (ret != DCMD_TIMEOUT)
4804                 megasas_return_cmd(instance, cmd);
4805
4806         return ret;
4807 }
4808
4809 /**
4810  * megasas_ld_list_query -      Returns FW's ld_list structure
4811  * @instance:                           Adapter soft state
4812  * @query_type:                         ld_list structure type
4813  *
4814  * Issues an internal command (DCMD) to get the FW's controller PD
4815  * list structure.  This information is mainly used to find out SYSTEM
4816  * supported by the FW.
4817  */
4818 static int
4819 megasas_ld_list_query(struct megasas_instance *instance, u8 query_type)
4820 {
4821         int ret = 0, ld_index = 0, ids = 0;
4822         struct megasas_cmd *cmd;
4823         struct megasas_dcmd_frame *dcmd;
4824         struct MR_LD_TARGETID_LIST *ci;
4825         dma_addr_t ci_h = 0;
4826         u32 tgtid_count;
4827
4828         ci = instance->ld_targetid_list_buf;
4829         ci_h = instance->ld_targetid_list_buf_h;
4830
4831         cmd = megasas_get_cmd(instance);
4832
4833         if (!cmd) {
4834                 dev_warn(&instance->pdev->dev,
4835                          "megasas_ld_list_query: Failed to get cmd\n");
4836                 return -ENOMEM;
4837         }
4838
4839         dcmd = &cmd->frame->dcmd;
4840
4841         memset(ci, 0, sizeof(*ci));
4842         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4843
4844         dcmd->mbox.b[0] = query_type;
4845         if (instance->supportmax256vd)
4846                 dcmd->mbox.b[2] = 1;
4847
4848         dcmd->cmd = MFI_CMD_DCMD;
4849         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4850         dcmd->sge_count = 1;
4851         dcmd->flags = MFI_FRAME_DIR_READ;
4852         dcmd->timeout = 0;
4853         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
4854         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_LIST_QUERY);
4855         dcmd->pad_0  = 0;
4856
4857         megasas_set_dma_settings(instance, dcmd, ci_h,
4858                                  sizeof(struct MR_LD_TARGETID_LIST));
4859
4860         if ((instance->adapter_type != MFI_SERIES) &&
4861             !instance->mask_interrupts)
4862                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4863         else
4864                 ret = megasas_issue_polled(instance, cmd);
4865
4866         switch (ret) {
4867         case DCMD_FAILED:
4868                 dev_info(&instance->pdev->dev,
4869                         "DCMD not supported by firmware - %s %d\n",
4870                                 __func__, __LINE__);
4871                 ret = megasas_get_ld_list(instance);
4872                 break;
4873         case DCMD_TIMEOUT:
4874                 switch (dcmd_timeout_ocr_possible(instance)) {
4875                 case INITIATE_OCR:
4876                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4877                         /*
4878                          * DCMD failed from AEN path.
4879                          * AEN path already hold reset_mutex to avoid PCI access
4880                          * while OCR is in progress.
4881                          */
4882                         mutex_unlock(&instance->reset_mutex);
4883                         megasas_reset_fusion(instance->host,
4884                                                 MFI_IO_TIMEOUT_OCR);
4885                         mutex_lock(&instance->reset_mutex);
4886                         break;
4887                 case KILL_ADAPTER:
4888                         megaraid_sas_kill_hba(instance);
4889                         break;
4890                 case IGNORE_TIMEOUT:
4891                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4892                                 __func__, __LINE__);
4893                         break;
4894                 }
4895
4896                 break;
4897         case DCMD_SUCCESS:
4898                 tgtid_count = le32_to_cpu(ci->count);
4899
4900                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4901                         dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4902                                  __func__, tgtid_count);
4903
4904                 if ((tgtid_count > (instance->fw_supported_vd_count)))
4905                         break;
4906
4907                 memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
4908                 for (ld_index = 0; ld_index < tgtid_count; ld_index++) {
4909                         ids = ci->targetId[ld_index];
4910                         instance->ld_ids[ids] = ci->targetId[ld_index];
4911                         if (megasas_dbg_lvl & LD_PD_DEBUG)
4912                                 dev_info(&instance->pdev->dev, "LD%d: targetID: 0x%03x\n",
4913                                          ld_index, ci->targetId[ld_index]);
4914                 }
4915
4916                 break;
4917         }
4918
4919         if (ret != DCMD_TIMEOUT)
4920                 megasas_return_cmd(instance, cmd);
4921
4922         return ret;
4923 }
4924
4925 /**
4926  * dcmd.opcode            - MR_DCMD_CTRL_DEVICE_LIST_GET
4927  * dcmd.mbox              - reserved
4928  * dcmd.sge IN            - ptr to return MR_HOST_DEVICE_LIST structure
4929  * Desc:    This DCMD will return the combined device list
4930  * Status:  MFI_STAT_OK - List returned successfully
4931  *          MFI_STAT_INVALID_CMD - Firmware support for the feature has been
4932  *                                 disabled
4933  * @instance:                   Adapter soft state
4934  * @is_probe:                   Driver probe check
4935  * Return:                      0 if DCMD succeeded
4936  *                               non-zero if failed
4937  */
4938 static int
4939 megasas_host_device_list_query(struct megasas_instance *instance,
4940                                bool is_probe)
4941 {
4942         int ret, i, target_id;
4943         struct megasas_cmd *cmd;
4944         struct megasas_dcmd_frame *dcmd;
4945         struct MR_HOST_DEVICE_LIST *ci;
4946         u32 count;
4947         dma_addr_t ci_h;
4948
4949         ci = instance->host_device_list_buf;
4950         ci_h = instance->host_device_list_buf_h;
4951
4952         cmd = megasas_get_cmd(instance);
4953
4954         if (!cmd) {
4955                 dev_warn(&instance->pdev->dev,
4956                          "%s: failed to get cmd\n",
4957                          __func__);
4958                 return -ENOMEM;
4959         }
4960
4961         dcmd = &cmd->frame->dcmd;
4962
4963         memset(ci, 0, sizeof(*ci));
4964         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4965
4966         dcmd->mbox.b[0] = is_probe ? 0 : 1;
4967         dcmd->cmd = MFI_CMD_DCMD;
4968         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4969         dcmd->sge_count = 1;
4970         dcmd->flags = MFI_FRAME_DIR_READ;
4971         dcmd->timeout = 0;
4972         dcmd->pad_0 = 0;
4973         dcmd->data_xfer_len = cpu_to_le32(HOST_DEVICE_LIST_SZ);
4974         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_DEVICE_LIST_GET);
4975
4976         megasas_set_dma_settings(instance, dcmd, ci_h, HOST_DEVICE_LIST_SZ);
4977
4978         if (!instance->mask_interrupts) {
4979                 ret = megasas_issue_blocked_cmd(instance, cmd,
4980                                                 MFI_IO_TIMEOUT_SECS);
4981         } else {
4982                 ret = megasas_issue_polled(instance, cmd);
4983                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4984         }
4985
4986         switch (ret) {
4987         case DCMD_SUCCESS:
4988                 /* Fill the internal pd_list and ld_ids array based on
4989                  * targetIds returned by FW
4990                  */
4991                 count = le32_to_cpu(ci->count);
4992
4993                 if (count > (MEGASAS_MAX_PD + MAX_LOGICAL_DRIVES_EXT))
4994                         break;
4995
4996                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4997                         dev_info(&instance->pdev->dev, "%s, Device count: 0x%x\n",
4998                                  __func__, count);
4999
5000                 memset(instance->local_pd_list, 0,
5001                        MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
5002                 memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
5003                 for (i = 0; i < count; i++) {
5004                         target_id = le16_to_cpu(ci->host_device_list[i].target_id);
5005                         if (ci->host_device_list[i].flags.u.bits.is_sys_pd) {
5006                                 instance->local_pd_list[target_id].tid = target_id;
5007                                 instance->local_pd_list[target_id].driveType =
5008                                                 ci->host_device_list[i].scsi_type;
5009                                 instance->local_pd_list[target_id].driveState =
5010                                                 MR_PD_STATE_SYSTEM;
5011                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
5012                                         dev_info(&instance->pdev->dev,
5013                                                  "Device %d: PD targetID: 0x%03x deviceType:0x%x\n",
5014                                                  i, target_id, ci->host_device_list[i].scsi_type);
5015                         } else {
5016                                 instance->ld_ids[target_id] = target_id;
5017                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
5018                                         dev_info(&instance->pdev->dev,
5019                                                  "Device %d: LD targetID: 0x%03x\n",
5020                                                  i, target_id);
5021                         }
5022                 }
5023
5024                 memcpy(instance->pd_list, instance->local_pd_list,
5025                        sizeof(instance->pd_list));
5026                 break;
5027
5028         case DCMD_TIMEOUT:
5029                 switch (dcmd_timeout_ocr_possible(instance)) {
5030                 case INITIATE_OCR:
5031                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5032                         mutex_unlock(&instance->reset_mutex);
5033                         megasas_reset_fusion(instance->host,
5034                                 MFI_IO_TIMEOUT_OCR);
5035                         mutex_lock(&instance->reset_mutex);
5036                         break;
5037                 case KILL_ADAPTER:
5038                         megaraid_sas_kill_hba(instance);
5039                         break;
5040                 case IGNORE_TIMEOUT:
5041                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5042                                  __func__, __LINE__);
5043                         break;
5044                 }
5045                 break;
5046         case DCMD_FAILED:
5047                 dev_err(&instance->pdev->dev,
5048                         "%s: MR_DCMD_CTRL_DEVICE_LIST_GET failed\n",
5049                         __func__);
5050                 break;
5051         }
5052
5053         if (ret != DCMD_TIMEOUT)
5054                 megasas_return_cmd(instance, cmd);
5055
5056         return ret;
5057 }
5058
5059 /*
5060  * megasas_update_ext_vd_details : Update details w.r.t Extended VD
5061  * instance                      : Controller's instance
5062 */
5063 static void megasas_update_ext_vd_details(struct megasas_instance *instance)
5064 {
5065         struct fusion_context *fusion;
5066         u32 ventura_map_sz = 0;
5067
5068         fusion = instance->ctrl_context;
5069         /* For MFI based controllers return dummy success */
5070         if (!fusion)
5071                 return;
5072
5073         instance->supportmax256vd =
5074                 instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs;
5075         /* Below is additional check to address future FW enhancement */
5076         if (instance->ctrl_info_buf->max_lds > 64)
5077                 instance->supportmax256vd = 1;
5078
5079         instance->drv_supported_vd_count = MEGASAS_MAX_LD_CHANNELS
5080                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
5081         instance->drv_supported_pd_count = MEGASAS_MAX_PD_CHANNELS
5082                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
5083         if (instance->supportmax256vd) {
5084                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES_EXT;
5085                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
5086         } else {
5087                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
5088                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
5089         }
5090
5091         dev_info(&instance->pdev->dev,
5092                 "FW provided supportMaxExtLDs: %d\tmax_lds: %d\n",
5093                 instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs ? 1 : 0,
5094                 instance->ctrl_info_buf->max_lds);
5095
5096         if (instance->max_raid_mapsize) {
5097                 ventura_map_sz = instance->max_raid_mapsize *
5098                                                 MR_MIN_MAP_SIZE; /* 64k */
5099                 fusion->current_map_sz = ventura_map_sz;
5100                 fusion->max_map_sz = ventura_map_sz;
5101         } else {
5102                 fusion->old_map_sz =  sizeof(struct MR_FW_RAID_MAP) +
5103                                         (sizeof(struct MR_LD_SPAN_MAP) *
5104                                         (instance->fw_supported_vd_count - 1));
5105                 fusion->new_map_sz =  sizeof(struct MR_FW_RAID_MAP_EXT);
5106
5107                 fusion->max_map_sz =
5108                         max(fusion->old_map_sz, fusion->new_map_sz);
5109
5110                 if (instance->supportmax256vd)
5111                         fusion->current_map_sz = fusion->new_map_sz;
5112                 else
5113                         fusion->current_map_sz = fusion->old_map_sz;
5114         }
5115         /* irrespective of FW raid maps, driver raid map is constant */
5116         fusion->drv_map_sz = sizeof(struct MR_DRV_RAID_MAP_ALL);
5117 }
5118
5119 /*
5120  * dcmd.opcode                - MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES
5121  * dcmd.hdr.length            - number of bytes to read
5122  * dcmd.sge                   - Ptr to MR_SNAPDUMP_PROPERTIES
5123  * Desc:                         Fill in snapdump properties
5124  * Status:                       MFI_STAT_OK- Command successful
5125  */
5126 void megasas_get_snapdump_properties(struct megasas_instance *instance)
5127 {
5128         int ret = 0;
5129         struct megasas_cmd *cmd;
5130         struct megasas_dcmd_frame *dcmd;
5131         struct MR_SNAPDUMP_PROPERTIES *ci;
5132         dma_addr_t ci_h = 0;
5133
5134         ci = instance->snapdump_prop;
5135         ci_h = instance->snapdump_prop_h;
5136
5137         if (!ci)
5138                 return;
5139
5140         cmd = megasas_get_cmd(instance);
5141
5142         if (!cmd) {
5143                 dev_dbg(&instance->pdev->dev, "Failed to get a free cmd\n");
5144                 return;
5145         }
5146
5147         dcmd = &cmd->frame->dcmd;
5148
5149         memset(ci, 0, sizeof(*ci));
5150         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5151
5152         dcmd->cmd = MFI_CMD_DCMD;
5153         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5154         dcmd->sge_count = 1;
5155         dcmd->flags = MFI_FRAME_DIR_READ;
5156         dcmd->timeout = 0;
5157         dcmd->pad_0 = 0;
5158         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_SNAPDUMP_PROPERTIES));
5159         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES);
5160
5161         megasas_set_dma_settings(instance, dcmd, ci_h,
5162                                  sizeof(struct MR_SNAPDUMP_PROPERTIES));
5163
5164         if (!instance->mask_interrupts) {
5165                 ret = megasas_issue_blocked_cmd(instance, cmd,
5166                                                 MFI_IO_TIMEOUT_SECS);
5167         } else {
5168                 ret = megasas_issue_polled(instance, cmd);
5169                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5170         }
5171
5172         switch (ret) {
5173         case DCMD_SUCCESS:
5174                 instance->snapdump_wait_time =
5175                         min_t(u8, ci->trigger_min_num_sec_before_ocr,
5176                                 MEGASAS_MAX_SNAP_DUMP_WAIT_TIME);
5177                 break;
5178
5179         case DCMD_TIMEOUT:
5180                 switch (dcmd_timeout_ocr_possible(instance)) {
5181                 case INITIATE_OCR:
5182                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5183                         mutex_unlock(&instance->reset_mutex);
5184                         megasas_reset_fusion(instance->host,
5185                                 MFI_IO_TIMEOUT_OCR);
5186                         mutex_lock(&instance->reset_mutex);
5187                         break;
5188                 case KILL_ADAPTER:
5189                         megaraid_sas_kill_hba(instance);
5190                         break;
5191                 case IGNORE_TIMEOUT:
5192                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5193                                 __func__, __LINE__);
5194                         break;
5195                 }
5196         }
5197
5198         if (ret != DCMD_TIMEOUT)
5199                 megasas_return_cmd(instance, cmd);
5200 }
5201
5202 /**
5203  * megasas_get_controller_info -        Returns FW's controller structure
5204  * @instance:                           Adapter soft state
5205  *
5206  * Issues an internal command (DCMD) to get the FW's controller structure.
5207  * This information is mainly used to find out the maximum IO transfer per
5208  * command supported by the FW.
5209  */
5210 int
5211 megasas_get_ctrl_info(struct megasas_instance *instance)
5212 {
5213         int ret = 0;
5214         struct megasas_cmd *cmd;
5215         struct megasas_dcmd_frame *dcmd;
5216         struct megasas_ctrl_info *ci;
5217         dma_addr_t ci_h = 0;
5218
5219         ci = instance->ctrl_info_buf;
5220         ci_h = instance->ctrl_info_buf_h;
5221
5222         cmd = megasas_get_cmd(instance);
5223
5224         if (!cmd) {
5225                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a free cmd\n");
5226                 return -ENOMEM;
5227         }
5228
5229         dcmd = &cmd->frame->dcmd;
5230
5231         memset(ci, 0, sizeof(*ci));
5232         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5233
5234         dcmd->cmd = MFI_CMD_DCMD;
5235         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5236         dcmd->sge_count = 1;
5237         dcmd->flags = MFI_FRAME_DIR_READ;
5238         dcmd->timeout = 0;
5239         dcmd->pad_0 = 0;
5240         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_ctrl_info));
5241         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_GET_INFO);
5242         dcmd->mbox.b[0] = 1;
5243
5244         megasas_set_dma_settings(instance, dcmd, ci_h,
5245                                  sizeof(struct megasas_ctrl_info));
5246
5247         if ((instance->adapter_type != MFI_SERIES) &&
5248             !instance->mask_interrupts) {
5249                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5250         } else {
5251                 ret = megasas_issue_polled(instance, cmd);
5252                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5253         }
5254
5255         switch (ret) {
5256         case DCMD_SUCCESS:
5257                 /* Save required controller information in
5258                  * CPU endianness format.
5259                  */
5260                 le32_to_cpus((u32 *)&ci->properties.OnOffProperties);
5261                 le16_to_cpus((u16 *)&ci->properties.on_off_properties2);
5262                 le32_to_cpus((u32 *)&ci->adapterOperations2);
5263                 le32_to_cpus((u32 *)&ci->adapterOperations3);
5264                 le16_to_cpus((u16 *)&ci->adapter_operations4);
5265                 le32_to_cpus((u32 *)&ci->adapter_operations5);
5266
5267                 /* Update the latest Ext VD info.
5268                  * From Init path, store current firmware details.
5269                  * From OCR path, detect any firmware properties changes.
5270                  * in case of Firmware upgrade without system reboot.
5271                  */
5272                 megasas_update_ext_vd_details(instance);
5273                 instance->support_seqnum_jbod_fp =
5274                         ci->adapterOperations3.useSeqNumJbodFP;
5275                 instance->support_morethan256jbod =
5276                         ci->adapter_operations4.support_pd_map_target_id;
5277                 instance->support_nvme_passthru =
5278                         ci->adapter_operations4.support_nvme_passthru;
5279                 instance->support_pci_lane_margining =
5280                         ci->adapter_operations5.support_pci_lane_margining;
5281                 instance->task_abort_tmo = ci->TaskAbortTO;
5282                 instance->max_reset_tmo = ci->MaxResetTO;
5283
5284                 /*Check whether controller is iMR or MR */
5285                 instance->is_imr = (ci->memory_size ? 0 : 1);
5286
5287                 instance->snapdump_wait_time =
5288                         (ci->properties.on_off_properties2.enable_snap_dump ?
5289                          MEGASAS_DEFAULT_SNAP_DUMP_WAIT_TIME : 0);
5290
5291                 instance->enable_fw_dev_list =
5292                         ci->properties.on_off_properties2.enable_fw_dev_list;
5293
5294                 dev_info(&instance->pdev->dev,
5295                         "controller type\t: %s(%dMB)\n",
5296                         instance->is_imr ? "iMR" : "MR",
5297                         le16_to_cpu(ci->memory_size));
5298
5299                 instance->disableOnlineCtrlReset =
5300                         ci->properties.OnOffProperties.disableOnlineCtrlReset;
5301                 instance->secure_jbod_support =
5302                         ci->adapterOperations3.supportSecurityonJBOD;
5303                 dev_info(&instance->pdev->dev, "Online Controller Reset(OCR)\t: %s\n",
5304                         instance->disableOnlineCtrlReset ? "Disabled" : "Enabled");
5305                 dev_info(&instance->pdev->dev, "Secure JBOD support\t: %s\n",
5306                         instance->secure_jbod_support ? "Yes" : "No");
5307                 dev_info(&instance->pdev->dev, "NVMe passthru support\t: %s\n",
5308                          instance->support_nvme_passthru ? "Yes" : "No");
5309                 dev_info(&instance->pdev->dev,
5310                          "FW provided TM TaskAbort/Reset timeout\t: %d secs/%d secs\n",
5311                          instance->task_abort_tmo, instance->max_reset_tmo);
5312                 dev_info(&instance->pdev->dev, "JBOD sequence map support\t: %s\n",
5313                          instance->support_seqnum_jbod_fp ? "Yes" : "No");
5314                 dev_info(&instance->pdev->dev, "PCI Lane Margining support\t: %s\n",
5315                          instance->support_pci_lane_margining ? "Yes" : "No");
5316
5317                 break;
5318
5319         case DCMD_TIMEOUT:
5320                 switch (dcmd_timeout_ocr_possible(instance)) {
5321                 case INITIATE_OCR:
5322                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5323                         mutex_unlock(&instance->reset_mutex);
5324                         megasas_reset_fusion(instance->host,
5325                                 MFI_IO_TIMEOUT_OCR);
5326                         mutex_lock(&instance->reset_mutex);
5327                         break;
5328                 case KILL_ADAPTER:
5329                         megaraid_sas_kill_hba(instance);
5330                         break;
5331                 case IGNORE_TIMEOUT:
5332                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5333                                 __func__, __LINE__);
5334                         break;
5335                 }
5336                 break;
5337         case DCMD_FAILED:
5338                 megaraid_sas_kill_hba(instance);
5339                 break;
5340
5341         }
5342
5343         if (ret != DCMD_TIMEOUT)
5344                 megasas_return_cmd(instance, cmd);
5345
5346         return ret;
5347 }
5348
5349 /*
5350  * megasas_set_crash_dump_params -      Sends address of crash dump DMA buffer
5351  *                                      to firmware
5352  *
5353  * @instance:                           Adapter soft state
5354  * @crash_buf_state             -       tell FW to turn ON/OFF crash dump feature
5355                                         MR_CRASH_BUF_TURN_OFF = 0
5356                                         MR_CRASH_BUF_TURN_ON = 1
5357  * @return 0 on success non-zero on failure.
5358  * Issues an internal command (DCMD) to set parameters for crash dump feature.
5359  * Driver will send address of crash dump DMA buffer and set mbox to tell FW
5360  * that driver supports crash dump feature. This DCMD will be sent only if
5361  * crash dump feature is supported by the FW.
5362  *
5363  */
5364 int megasas_set_crash_dump_params(struct megasas_instance *instance,
5365         u8 crash_buf_state)
5366 {
5367         int ret = 0;
5368         struct megasas_cmd *cmd;
5369         struct megasas_dcmd_frame *dcmd;
5370
5371         cmd = megasas_get_cmd(instance);
5372
5373         if (!cmd) {
5374                 dev_err(&instance->pdev->dev, "Failed to get a free cmd\n");
5375                 return -ENOMEM;
5376         }
5377
5378
5379         dcmd = &cmd->frame->dcmd;
5380
5381         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5382         dcmd->mbox.b[0] = crash_buf_state;
5383         dcmd->cmd = MFI_CMD_DCMD;
5384         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5385         dcmd->sge_count = 1;
5386         dcmd->flags = MFI_FRAME_DIR_NONE;
5387         dcmd->timeout = 0;
5388         dcmd->pad_0 = 0;
5389         dcmd->data_xfer_len = cpu_to_le32(CRASH_DMA_BUF_SIZE);
5390         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SET_CRASH_DUMP_PARAMS);
5391
5392         megasas_set_dma_settings(instance, dcmd, instance->crash_dump_h,
5393                                  CRASH_DMA_BUF_SIZE);
5394
5395         if ((instance->adapter_type != MFI_SERIES) &&
5396             !instance->mask_interrupts)
5397                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5398         else
5399                 ret = megasas_issue_polled(instance, cmd);
5400
5401         if (ret == DCMD_TIMEOUT) {
5402                 switch (dcmd_timeout_ocr_possible(instance)) {
5403                 case INITIATE_OCR:
5404                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5405                         megasas_reset_fusion(instance->host,
5406                                         MFI_IO_TIMEOUT_OCR);
5407                         break;
5408                 case KILL_ADAPTER:
5409                         megaraid_sas_kill_hba(instance);
5410                         break;
5411                 case IGNORE_TIMEOUT:
5412                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5413                                 __func__, __LINE__);
5414                         break;
5415                 }
5416         } else
5417                 megasas_return_cmd(instance, cmd);
5418
5419         return ret;
5420 }
5421
5422 /**
5423  * megasas_issue_init_mfi -     Initializes the FW
5424  * @instance:           Adapter soft state
5425  *
5426  * Issues the INIT MFI cmd
5427  */
5428 static int
5429 megasas_issue_init_mfi(struct megasas_instance *instance)
5430 {
5431         __le32 context;
5432         struct megasas_cmd *cmd;
5433         struct megasas_init_frame *init_frame;
5434         struct megasas_init_queue_info *initq_info;
5435         dma_addr_t init_frame_h;
5436         dma_addr_t initq_info_h;
5437
5438         /*
5439          * Prepare a init frame. Note the init frame points to queue info
5440          * structure. Each frame has SGL allocated after first 64 bytes. For
5441          * this frame - since we don't need any SGL - we use SGL's space as
5442          * queue info structure
5443          *
5444          * We will not get a NULL command below. We just created the pool.
5445          */
5446         cmd = megasas_get_cmd(instance);
5447
5448         init_frame = (struct megasas_init_frame *)cmd->frame;
5449         initq_info = (struct megasas_init_queue_info *)
5450                 ((unsigned long)init_frame + 64);
5451
5452         init_frame_h = cmd->frame_phys_addr;
5453         initq_info_h = init_frame_h + 64;
5454
5455         context = init_frame->context;
5456         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
5457         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
5458         init_frame->context = context;
5459
5460         initq_info->reply_queue_entries = cpu_to_le32(instance->max_fw_cmds + 1);
5461         initq_info->reply_queue_start_phys_addr_lo = cpu_to_le32(instance->reply_queue_h);
5462
5463         initq_info->producer_index_phys_addr_lo = cpu_to_le32(instance->producer_h);
5464         initq_info->consumer_index_phys_addr_lo = cpu_to_le32(instance->consumer_h);
5465
5466         init_frame->cmd = MFI_CMD_INIT;
5467         init_frame->cmd_status = MFI_STAT_INVALID_STATUS;
5468         init_frame->queue_info_new_phys_addr_lo =
5469                 cpu_to_le32(lower_32_bits(initq_info_h));
5470         init_frame->queue_info_new_phys_addr_hi =
5471                 cpu_to_le32(upper_32_bits(initq_info_h));
5472
5473         init_frame->data_xfer_len = cpu_to_le32(sizeof(struct megasas_init_queue_info));
5474
5475         /*
5476          * disable the intr before firing the init frame to FW
5477          */
5478         instance->instancet->disable_intr(instance);
5479
5480         /*
5481          * Issue the init frame in polled mode
5482          */
5483
5484         if (megasas_issue_polled(instance, cmd)) {
5485                 dev_err(&instance->pdev->dev, "Failed to init firmware\n");
5486                 megasas_return_cmd(instance, cmd);
5487                 goto fail_fw_init;
5488         }
5489
5490         megasas_return_cmd(instance, cmd);
5491
5492         return 0;
5493
5494 fail_fw_init:
5495         return -EINVAL;
5496 }
5497
5498 static u32
5499 megasas_init_adapter_mfi(struct megasas_instance *instance)
5500 {
5501         u32 context_sz;
5502         u32 reply_q_sz;
5503
5504         /*
5505          * Get various operational parameters from status register
5506          */
5507         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(instance) & 0x00FFFF;
5508         /*
5509          * Reduce the max supported cmds by 1. This is to ensure that the
5510          * reply_q_sz (1 more than the max cmd that driver may send)
5511          * does not exceed max cmds that the FW can support
5512          */
5513         instance->max_fw_cmds = instance->max_fw_cmds-1;
5514         instance->max_mfi_cmds = instance->max_fw_cmds;
5515         instance->max_num_sge = (instance->instancet->read_fw_status_reg(instance) & 0xFF0000) >>
5516                                         0x10;
5517         /*
5518          * For MFI skinny adapters, MEGASAS_SKINNY_INT_CMDS commands
5519          * are reserved for IOCTL + driver's internal DCMDs.
5520          */
5521         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
5522                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
5523                 instance->max_scsi_cmds = (instance->max_fw_cmds -
5524                         MEGASAS_SKINNY_INT_CMDS);
5525                 sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
5526         } else {
5527                 instance->max_scsi_cmds = (instance->max_fw_cmds -
5528                         MEGASAS_INT_CMDS);
5529                 sema_init(&instance->ioctl_sem, (MEGASAS_MFI_IOCTL_CMDS));
5530         }
5531
5532         instance->cur_can_queue = instance->max_scsi_cmds;
5533         /*
5534          * Create a pool of commands
5535          */
5536         if (megasas_alloc_cmds(instance))
5537                 goto fail_alloc_cmds;
5538
5539         /*
5540          * Allocate memory for reply queue. Length of reply queue should
5541          * be _one_ more than the maximum commands handled by the firmware.
5542          *
5543          * Note: When FW completes commands, it places corresponding contex
5544          * values in this circular reply queue. This circular queue is a fairly
5545          * typical producer-consumer queue. FW is the producer (of completed
5546          * commands) and the driver is the consumer.
5547          */
5548         context_sz = sizeof(u32);
5549         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
5550
5551         instance->reply_queue = dma_alloc_coherent(&instance->pdev->dev,
5552                         reply_q_sz, &instance->reply_queue_h, GFP_KERNEL);
5553
5554         if (!instance->reply_queue) {
5555                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Out of DMA mem for reply queue\n");
5556                 goto fail_reply_queue;
5557         }
5558
5559         if (megasas_issue_init_mfi(instance))
5560                 goto fail_fw_init;
5561
5562         if (megasas_get_ctrl_info(instance)) {
5563                 dev_err(&instance->pdev->dev, "(%d): Could get controller info "
5564                         "Fail from %s %d\n", instance->unique_id,
5565                         __func__, __LINE__);
5566                 goto fail_fw_init;
5567         }
5568
5569         instance->fw_support_ieee = 0;
5570         instance->fw_support_ieee =
5571                 (instance->instancet->read_fw_status_reg(instance) &
5572                 0x04000000);
5573
5574         dev_notice(&instance->pdev->dev, "megasas_init_mfi: fw_support_ieee=%d",
5575                         instance->fw_support_ieee);
5576
5577         if (instance->fw_support_ieee)
5578                 instance->flag_ieee = 1;
5579
5580         return 0;
5581
5582 fail_fw_init:
5583
5584         dma_free_coherent(&instance->pdev->dev, reply_q_sz,
5585                             instance->reply_queue, instance->reply_queue_h);
5586 fail_reply_queue:
5587         megasas_free_cmds(instance);
5588
5589 fail_alloc_cmds:
5590         return 1;
5591 }
5592
5593 static
5594 void megasas_setup_irq_poll(struct megasas_instance *instance)
5595 {
5596         struct megasas_irq_context *irq_ctx;
5597         u32 count, i;
5598
5599         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5600
5601         /* Initialize IRQ poll */
5602         for (i = 0; i < count; i++) {
5603                 irq_ctx = &instance->irq_context[i];
5604                 irq_ctx->os_irq = pci_irq_vector(instance->pdev, i);
5605                 irq_ctx->irq_poll_scheduled = false;
5606                 irq_poll_init(&irq_ctx->irqpoll,
5607                               instance->threshold_reply_count,
5608                               megasas_irqpoll);
5609         }
5610 }
5611
5612 /*
5613  * megasas_setup_irqs_ioapic -          register legacy interrupts.
5614  * @instance:                           Adapter soft state
5615  *
5616  * Do not enable interrupt, only setup ISRs.
5617  *
5618  * Return 0 on success.
5619  */
5620 static int
5621 megasas_setup_irqs_ioapic(struct megasas_instance *instance)
5622 {
5623         struct pci_dev *pdev;
5624
5625         pdev = instance->pdev;
5626         instance->irq_context[0].instance = instance;
5627         instance->irq_context[0].MSIxIndex = 0;
5628         snprintf(instance->irq_context->name, MEGASAS_MSIX_NAME_LEN, "%s%u",
5629                 "megasas", instance->host->host_no);
5630         if (request_irq(pci_irq_vector(pdev, 0),
5631                         instance->instancet->service_isr, IRQF_SHARED,
5632                         instance->irq_context->name, &instance->irq_context[0])) {
5633                 dev_err(&instance->pdev->dev,
5634                                 "Failed to register IRQ from %s %d\n",
5635                                 __func__, __LINE__);
5636                 return -1;
5637         }
5638         instance->perf_mode = MR_LATENCY_PERF_MODE;
5639         instance->low_latency_index_start = 0;
5640         return 0;
5641 }
5642
5643 /**
5644  * megasas_setup_irqs_msix -            register MSI-x interrupts.
5645  * @instance:                           Adapter soft state
5646  * @is_probe:                           Driver probe check
5647  *
5648  * Do not enable interrupt, only setup ISRs.
5649  *
5650  * Return 0 on success.
5651  */
5652 static int
5653 megasas_setup_irqs_msix(struct megasas_instance *instance, u8 is_probe)
5654 {
5655         int i, j;
5656         struct pci_dev *pdev;
5657
5658         pdev = instance->pdev;
5659
5660         /* Try MSI-x */
5661         for (i = 0; i < instance->msix_vectors; i++) {
5662                 instance->irq_context[i].instance = instance;
5663                 instance->irq_context[i].MSIxIndex = i;
5664                 snprintf(instance->irq_context[i].name, MEGASAS_MSIX_NAME_LEN, "%s%u-msix%u",
5665                         "megasas", instance->host->host_no, i);
5666                 if (request_irq(pci_irq_vector(pdev, i),
5667                         instance->instancet->service_isr, 0, instance->irq_context[i].name,
5668                         &instance->irq_context[i])) {
5669                         dev_err(&instance->pdev->dev,
5670                                 "Failed to register IRQ for vector %d.\n", i);
5671                         for (j = 0; j < i; j++) {
5672                                 if (j < instance->low_latency_index_start)
5673                                         irq_set_affinity_hint(
5674                                                 pci_irq_vector(pdev, j), NULL);
5675                                 free_irq(pci_irq_vector(pdev, j),
5676                                          &instance->irq_context[j]);
5677                         }
5678                         /* Retry irq register for IO_APIC*/
5679                         instance->msix_vectors = 0;
5680                         instance->msix_load_balance = false;
5681                         if (is_probe) {
5682                                 pci_free_irq_vectors(instance->pdev);
5683                                 return megasas_setup_irqs_ioapic(instance);
5684                         } else {
5685                                 return -1;
5686                         }
5687                 }
5688         }
5689
5690         return 0;
5691 }
5692
5693 /*
5694  * megasas_destroy_irqs-                unregister interrupts.
5695  * @instance:                           Adapter soft state
5696  * return:                              void
5697  */
5698 static void
5699 megasas_destroy_irqs(struct megasas_instance *instance) {
5700
5701         int i;
5702         int count;
5703         struct megasas_irq_context *irq_ctx;
5704
5705         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5706         if (instance->adapter_type != MFI_SERIES) {
5707                 for (i = 0; i < count; i++) {
5708                         irq_ctx = &instance->irq_context[i];
5709                         irq_poll_disable(&irq_ctx->irqpoll);
5710                 }
5711         }
5712
5713         if (instance->msix_vectors)
5714                 for (i = 0; i < instance->msix_vectors; i++) {
5715                         if (i < instance->low_latency_index_start)
5716                                 irq_set_affinity_hint(
5717                                     pci_irq_vector(instance->pdev, i), NULL);
5718                         free_irq(pci_irq_vector(instance->pdev, i),
5719                                  &instance->irq_context[i]);
5720                 }
5721         else
5722                 free_irq(pci_irq_vector(instance->pdev, 0),
5723                          &instance->irq_context[0]);
5724 }
5725
5726 /**
5727  * megasas_setup_jbod_map -     setup jbod map for FP seq_number.
5728  * @instance:                           Adapter soft state
5729  *
5730  * Return 0 on success.
5731  */
5732 void
5733 megasas_setup_jbod_map(struct megasas_instance *instance)
5734 {
5735         int i;
5736         struct fusion_context *fusion = instance->ctrl_context;
5737         u32 pd_seq_map_sz;
5738
5739         pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) +
5740                 (sizeof(struct MR_PD_CFG_SEQ) * (MAX_PHYSICAL_DEVICES - 1));
5741
5742         instance->use_seqnum_jbod_fp =
5743                 instance->support_seqnum_jbod_fp;
5744         if (reset_devices || !fusion ||
5745                 !instance->support_seqnum_jbod_fp) {
5746                 dev_info(&instance->pdev->dev,
5747                         "JBOD sequence map is disabled %s %d\n",
5748                         __func__, __LINE__);
5749                 instance->use_seqnum_jbod_fp = false;
5750                 return;
5751         }
5752
5753         if (fusion->pd_seq_sync[0])
5754                 goto skip_alloc;
5755
5756         for (i = 0; i < JBOD_MAPS_COUNT; i++) {
5757                 fusion->pd_seq_sync[i] = dma_alloc_coherent
5758                         (&instance->pdev->dev, pd_seq_map_sz,
5759                         &fusion->pd_seq_phys[i], GFP_KERNEL);
5760                 if (!fusion->pd_seq_sync[i]) {
5761                         dev_err(&instance->pdev->dev,
5762                                 "Failed to allocate memory from %s %d\n",
5763                                 __func__, __LINE__);
5764                         if (i == 1) {
5765                                 dma_free_coherent(&instance->pdev->dev,
5766                                         pd_seq_map_sz, fusion->pd_seq_sync[0],
5767                                         fusion->pd_seq_phys[0]);
5768                                 fusion->pd_seq_sync[0] = NULL;
5769                         }
5770                         instance->use_seqnum_jbod_fp = false;
5771                         return;
5772                 }
5773         }
5774
5775 skip_alloc:
5776         if (!megasas_sync_pd_seq_num(instance, false) &&
5777                 !megasas_sync_pd_seq_num(instance, true))
5778                 instance->use_seqnum_jbod_fp = true;
5779         else
5780                 instance->use_seqnum_jbod_fp = false;
5781 }
5782
5783 static void megasas_setup_reply_map(struct megasas_instance *instance)
5784 {
5785         const struct cpumask *mask;
5786         unsigned int queue, cpu, low_latency_index_start;
5787
5788         low_latency_index_start = instance->low_latency_index_start;
5789
5790         for (queue = low_latency_index_start; queue < instance->msix_vectors; queue++) {
5791                 mask = pci_irq_get_affinity(instance->pdev, queue);
5792                 if (!mask)
5793                         goto fallback;
5794
5795                 for_each_cpu(cpu, mask)
5796                         instance->reply_map[cpu] = queue;
5797         }
5798         return;
5799
5800 fallback:
5801         queue = low_latency_index_start;
5802         for_each_possible_cpu(cpu) {
5803                 instance->reply_map[cpu] = queue;
5804                 if (queue == (instance->msix_vectors - 1))
5805                         queue = low_latency_index_start;
5806                 else
5807                         queue++;
5808         }
5809 }
5810
5811 /**
5812  * megasas_get_device_list -    Get the PD and LD device list from FW.
5813  * @instance:                   Adapter soft state
5814  * @return:                     Success or failure
5815  *
5816  * Issue DCMDs to Firmware to get the PD and LD list.
5817  * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
5818  * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
5819  */
5820 static
5821 int megasas_get_device_list(struct megasas_instance *instance)
5822 {
5823         memset(instance->pd_list, 0,
5824                (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
5825         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
5826
5827         if (instance->enable_fw_dev_list) {
5828                 if (megasas_host_device_list_query(instance, true))
5829                         return FAILED;
5830         } else {
5831                 if (megasas_get_pd_list(instance) < 0) {
5832                         dev_err(&instance->pdev->dev, "failed to get PD list\n");
5833                         return FAILED;
5834                 }
5835
5836                 if (megasas_ld_list_query(instance,
5837                                           MR_LD_QUERY_TYPE_EXPOSED_TO_HOST)) {
5838                         dev_err(&instance->pdev->dev, "failed to get LD list\n");
5839                         return FAILED;
5840                 }
5841         }
5842
5843         return SUCCESS;
5844 }
5845
5846 /**
5847  * megasas_set_high_iops_queue_affinity_hint -  Set affinity hint for high IOPS queues
5848  * @instance:                                   Adapter soft state
5849  * return:                                      void
5850  */
5851 static inline void
5852 megasas_set_high_iops_queue_affinity_hint(struct megasas_instance *instance)
5853 {
5854         int i;
5855         int local_numa_node;
5856
5857         if (instance->perf_mode == MR_BALANCED_PERF_MODE) {
5858                 local_numa_node = dev_to_node(&instance->pdev->dev);
5859
5860                 for (i = 0; i < instance->low_latency_index_start; i++)
5861                         irq_set_affinity_hint(pci_irq_vector(instance->pdev, i),
5862                                 cpumask_of_node(local_numa_node));
5863         }
5864 }
5865
5866 static int
5867 __megasas_alloc_irq_vectors(struct megasas_instance *instance)
5868 {
5869         int i, irq_flags;
5870         struct irq_affinity desc = { .pre_vectors = instance->low_latency_index_start };
5871         struct irq_affinity *descp = &desc;
5872
5873         irq_flags = PCI_IRQ_MSIX;
5874
5875         if (instance->smp_affinity_enable)
5876                 irq_flags |= PCI_IRQ_AFFINITY;
5877         else
5878                 descp = NULL;
5879
5880         i = pci_alloc_irq_vectors_affinity(instance->pdev,
5881                 instance->low_latency_index_start,
5882                 instance->msix_vectors, irq_flags, descp);
5883
5884         return i;
5885 }
5886
5887 /**
5888  * megasas_alloc_irq_vectors -  Allocate IRQ vectors/enable MSI-x vectors
5889  * @instance:                   Adapter soft state
5890  * return:                      void
5891  */
5892 static void
5893 megasas_alloc_irq_vectors(struct megasas_instance *instance)
5894 {
5895         int i;
5896         unsigned int num_msix_req;
5897
5898         i = __megasas_alloc_irq_vectors(instance);
5899
5900         if ((instance->perf_mode == MR_BALANCED_PERF_MODE) &&
5901             (i != instance->msix_vectors)) {
5902                 if (instance->msix_vectors)
5903                         pci_free_irq_vectors(instance->pdev);
5904                 /* Disable Balanced IOPS mode and try realloc vectors */
5905                 instance->perf_mode = MR_LATENCY_PERF_MODE;
5906                 instance->low_latency_index_start = 1;
5907                 num_msix_req = num_online_cpus() + instance->low_latency_index_start;
5908
5909                 instance->msix_vectors = min(num_msix_req,
5910                                 instance->msix_vectors);
5911
5912                 i = __megasas_alloc_irq_vectors(instance);
5913
5914         }
5915
5916         dev_info(&instance->pdev->dev,
5917                 "requested/available msix %d/%d\n", instance->msix_vectors, i);
5918
5919         if (i > 0)
5920                 instance->msix_vectors = i;
5921         else
5922                 instance->msix_vectors = 0;
5923
5924         if (instance->smp_affinity_enable)
5925                 megasas_set_high_iops_queue_affinity_hint(instance);
5926 }
5927
5928 /**
5929  * megasas_init_fw -    Initializes the FW
5930  * @instance:           Adapter soft state
5931  *
5932  * This is the main function for initializing firmware
5933  */
5934
5935 static int megasas_init_fw(struct megasas_instance *instance)
5936 {
5937         u32 max_sectors_1;
5938         u32 max_sectors_2, tmp_sectors, msix_enable;
5939         u32 scratch_pad_1, scratch_pad_2, scratch_pad_3, status_reg;
5940         resource_size_t base_addr;
5941         void *base_addr_phys;
5942         struct megasas_ctrl_info *ctrl_info = NULL;
5943         unsigned long bar_list;
5944         int i, j, loop;
5945         struct IOV_111 *iovPtr;
5946         struct fusion_context *fusion;
5947         bool intr_coalescing;
5948         unsigned int num_msix_req;
5949         u16 lnksta, speed;
5950
5951         fusion = instance->ctrl_context;
5952
5953         /* Find first memory bar */
5954         bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
5955         instance->bar = find_first_bit(&bar_list, BITS_PER_LONG);
5956         if (pci_request_selected_regions(instance->pdev, 1<<instance->bar,
5957                                          "megasas: LSI")) {
5958                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "IO memory region busy!\n");
5959                 return -EBUSY;
5960         }
5961
5962         base_addr = pci_resource_start(instance->pdev, instance->bar);
5963         instance->reg_set = ioremap(base_addr, 8192);
5964
5965         if (!instance->reg_set) {
5966                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to map IO mem\n");
5967                 goto fail_ioremap;
5968         }
5969
5970         base_addr_phys = &base_addr;
5971         dev_printk(KERN_DEBUG, &instance->pdev->dev,
5972                    "BAR:0x%lx  BAR's base_addr(phys):%pa  mapped virt_addr:0x%p\n",
5973                    instance->bar, base_addr_phys, instance->reg_set);
5974
5975         if (instance->adapter_type != MFI_SERIES)
5976                 instance->instancet = &megasas_instance_template_fusion;
5977         else {
5978                 switch (instance->pdev->device) {
5979                 case PCI_DEVICE_ID_LSI_SAS1078R:
5980                 case PCI_DEVICE_ID_LSI_SAS1078DE:
5981                         instance->instancet = &megasas_instance_template_ppc;
5982                         break;
5983                 case PCI_DEVICE_ID_LSI_SAS1078GEN2:
5984                 case PCI_DEVICE_ID_LSI_SAS0079GEN2:
5985                         instance->instancet = &megasas_instance_template_gen2;
5986                         break;
5987                 case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
5988                 case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
5989                         instance->instancet = &megasas_instance_template_skinny;
5990                         break;
5991                 case PCI_DEVICE_ID_LSI_SAS1064R:
5992                 case PCI_DEVICE_ID_DELL_PERC5:
5993                 default:
5994                         instance->instancet = &megasas_instance_template_xscale;
5995                         instance->pd_list_not_supported = 1;
5996                         break;
5997                 }
5998         }
5999
6000         if (megasas_transition_to_ready(instance, 0)) {
6001                 dev_info(&instance->pdev->dev,
6002                          "Failed to transition controller to ready from %s!\n",
6003                          __func__);
6004                 if (instance->adapter_type != MFI_SERIES) {
6005                         status_reg = instance->instancet->read_fw_status_reg(
6006                                         instance);
6007                         if (status_reg & MFI_RESET_ADAPTER) {
6008                                 if (megasas_adp_reset_wait_for_ready
6009                                         (instance, true, 0) == FAILED)
6010                                         goto fail_ready_state;
6011                         } else {
6012                                 goto fail_ready_state;
6013                         }
6014                 } else {
6015                         atomic_set(&instance->fw_reset_no_pci_access, 1);
6016                         instance->instancet->adp_reset
6017                                 (instance, instance->reg_set);
6018                         atomic_set(&instance->fw_reset_no_pci_access, 0);
6019
6020                         /*waiting for about 30 second before retry*/
6021                         ssleep(30);
6022
6023                         if (megasas_transition_to_ready(instance, 0))
6024                                 goto fail_ready_state;
6025                 }
6026
6027                 dev_info(&instance->pdev->dev,
6028                          "FW restarted successfully from %s!\n",
6029                          __func__);
6030         }
6031
6032         megasas_init_ctrl_params(instance);
6033
6034         if (megasas_set_dma_mask(instance))
6035                 goto fail_ready_state;
6036
6037         if (megasas_alloc_ctrl_mem(instance))
6038                 goto fail_alloc_dma_buf;
6039
6040         if (megasas_alloc_ctrl_dma_buffers(instance))
6041                 goto fail_alloc_dma_buf;
6042
6043         fusion = instance->ctrl_context;
6044
6045         if (instance->adapter_type >= VENTURA_SERIES) {
6046                 scratch_pad_2 =
6047                         megasas_readl(instance,
6048                                       &instance->reg_set->outbound_scratch_pad_2);
6049                 instance->max_raid_mapsize = ((scratch_pad_2 >>
6050                         MR_MAX_RAID_MAP_SIZE_OFFSET_SHIFT) &
6051                         MR_MAX_RAID_MAP_SIZE_MASK);
6052         }
6053
6054         instance->enable_sdev_max_qd = enable_sdev_max_qd;
6055
6056         switch (instance->adapter_type) {
6057         case VENTURA_SERIES:
6058                 fusion->pcie_bw_limitation = true;
6059                 break;
6060         case AERO_SERIES:
6061                 fusion->r56_div_offload = true;
6062                 break;
6063         default:
6064                 break;
6065         }
6066
6067         /* Check if MSI-X is supported while in ready state */
6068         msix_enable = (instance->instancet->read_fw_status_reg(instance) &
6069                        0x4000000) >> 0x1a;
6070         if (msix_enable && !msix_disable) {
6071
6072                 scratch_pad_1 = megasas_readl
6073                         (instance, &instance->reg_set->outbound_scratch_pad_1);
6074                 /* Check max MSI-X vectors */
6075                 if (fusion) {
6076                         if (instance->adapter_type == THUNDERBOLT_SERIES) {
6077                                 /* Thunderbolt Series*/
6078                                 instance->msix_vectors = (scratch_pad_1
6079                                         & MR_MAX_REPLY_QUEUES_OFFSET) + 1;
6080                         } else {
6081                                 instance->msix_vectors = ((scratch_pad_1
6082                                         & MR_MAX_REPLY_QUEUES_EXT_OFFSET)
6083                                         >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1;
6084
6085                                 /*
6086                                  * For Invader series, > 8 MSI-x vectors
6087                                  * supported by FW/HW implies combined
6088                                  * reply queue mode is enabled.
6089                                  * For Ventura series, > 16 MSI-x vectors
6090                                  * supported by FW/HW implies combined
6091                                  * reply queue mode is enabled.
6092                                  */
6093                                 switch (instance->adapter_type) {
6094                                 case INVADER_SERIES:
6095                                         if (instance->msix_vectors > 8)
6096                                                 instance->msix_combined = true;
6097                                         break;
6098                                 case AERO_SERIES:
6099                                 case VENTURA_SERIES:
6100                                         if (instance->msix_vectors > 16)
6101                                                 instance->msix_combined = true;
6102                                         break;
6103                                 }
6104
6105                                 if (rdpq_enable)
6106                                         instance->is_rdpq = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ?
6107                                                                 1 : 0;
6108
6109                                 if (instance->adapter_type >= INVADER_SERIES &&
6110                                     !instance->msix_combined) {
6111                                         instance->msix_load_balance = true;
6112                                         instance->smp_affinity_enable = false;
6113                                 }
6114
6115                                 /* Save 1-15 reply post index address to local memory
6116                                  * Index 0 is already saved from reg offset
6117                                  * MPI2_REPLY_POST_HOST_INDEX_OFFSET
6118                                  */
6119                                 for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) {
6120                                         instance->reply_post_host_index_addr[loop] =
6121                                                 (u32 __iomem *)
6122                                                 ((u8 __iomem *)instance->reg_set +
6123                                                 MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET
6124                                                 + (loop * 0x10));
6125                                 }
6126                         }
6127
6128                         dev_info(&instance->pdev->dev,
6129                                  "firmware supports msix\t: (%d)",
6130                                  instance->msix_vectors);
6131                         if (msix_vectors)
6132                                 instance->msix_vectors = min(msix_vectors,
6133                                         instance->msix_vectors);
6134                 } else /* MFI adapters */
6135                         instance->msix_vectors = 1;
6136
6137
6138                 /*
6139                  * For Aero (if some conditions are met), driver will configure a
6140                  * few additional reply queues with interrupt coalescing enabled.
6141                  * These queues with interrupt coalescing enabled are called
6142                  * High IOPS queues and rest of reply queues (based on number of
6143                  * logical CPUs) are termed as Low latency queues.
6144                  *
6145                  * Total Number of reply queues = High IOPS queues + low latency queues
6146                  *
6147                  * For rest of fusion adapters, 1 additional reply queue will be
6148                  * reserved for management commands, rest of reply queues
6149                  * (based on number of logical CPUs) will be used for IOs and
6150                  * referenced as IO queues.
6151                  * Total Number of reply queues = 1 + IO queues
6152                  *
6153                  * MFI adapters supports single MSI-x so single reply queue
6154                  * will be used for IO and management commands.
6155                  */
6156
6157                 intr_coalescing = (scratch_pad_1 & MR_INTR_COALESCING_SUPPORT_OFFSET) ?
6158                                                                 true : false;
6159                 if (intr_coalescing &&
6160                         (num_online_cpus() >= MR_HIGH_IOPS_QUEUE_COUNT) &&
6161                         (instance->msix_vectors == MEGASAS_MAX_MSIX_QUEUES))
6162                         instance->perf_mode = MR_BALANCED_PERF_MODE;
6163                 else
6164                         instance->perf_mode = MR_LATENCY_PERF_MODE;
6165
6166
6167                 if (instance->adapter_type == AERO_SERIES) {
6168                         pcie_capability_read_word(instance->pdev, PCI_EXP_LNKSTA, &lnksta);
6169                         speed = lnksta & PCI_EXP_LNKSTA_CLS;
6170
6171                         /*
6172                          * For Aero, if PCIe link speed is <16 GT/s, then driver should operate
6173                          * in latency perf mode and enable R1 PCI bandwidth algorithm
6174                          */
6175                         if (speed < 0x4) {
6176                                 instance->perf_mode = MR_LATENCY_PERF_MODE;
6177                                 fusion->pcie_bw_limitation = true;
6178                         }
6179
6180                         /*
6181                          * Performance mode settings provided through module parameter-perf_mode will
6182                          * take affect only for:
6183                          * 1. Aero family of adapters.
6184                          * 2. When user sets module parameter- perf_mode in range of 0-2.
6185                          */
6186                         if ((perf_mode >= MR_BALANCED_PERF_MODE) &&
6187                                 (perf_mode <= MR_LATENCY_PERF_MODE))
6188                                 instance->perf_mode = perf_mode;
6189                         /*
6190                          * If intr coalescing is not supported by controller FW, then IOPS
6191                          * and Balanced modes are not feasible.
6192                          */
6193                         if (!intr_coalescing)
6194                                 instance->perf_mode = MR_LATENCY_PERF_MODE;
6195
6196                 }
6197
6198                 if (instance->perf_mode == MR_BALANCED_PERF_MODE)
6199                         instance->low_latency_index_start =
6200                                 MR_HIGH_IOPS_QUEUE_COUNT;
6201                 else
6202                         instance->low_latency_index_start = 1;
6203
6204                 num_msix_req = num_online_cpus() + instance->low_latency_index_start;
6205
6206                 instance->msix_vectors = min(num_msix_req,
6207                                 instance->msix_vectors);
6208
6209                 megasas_alloc_irq_vectors(instance);
6210                 if (!instance->msix_vectors)
6211                         instance->msix_load_balance = false;
6212         }
6213         /*
6214          * MSI-X host index 0 is common for all adapter.
6215          * It is used for all MPT based Adapters.
6216          */
6217         if (instance->msix_combined) {
6218                 instance->reply_post_host_index_addr[0] =
6219                                 (u32 *)((u8 *)instance->reg_set +
6220                                 MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET);
6221         } else {
6222                 instance->reply_post_host_index_addr[0] =
6223                         (u32 *)((u8 *)instance->reg_set +
6224                         MPI2_REPLY_POST_HOST_INDEX_OFFSET);
6225         }
6226
6227         if (!instance->msix_vectors) {
6228                 i = pci_alloc_irq_vectors(instance->pdev, 1, 1, PCI_IRQ_LEGACY);
6229                 if (i < 0)
6230                         goto fail_init_adapter;
6231         }
6232
6233         megasas_setup_reply_map(instance);
6234
6235         dev_info(&instance->pdev->dev,
6236                 "current msix/online cpus\t: (%d/%d)\n",
6237                 instance->msix_vectors, (unsigned int)num_online_cpus());
6238         dev_info(&instance->pdev->dev,
6239                 "RDPQ mode\t: (%s)\n", instance->is_rdpq ? "enabled" : "disabled");
6240
6241         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
6242                 (unsigned long)instance);
6243
6244         /*
6245          * Below are default value for legacy Firmware.
6246          * non-fusion based controllers
6247          */
6248         instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
6249         instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
6250         /* Get operational params, sge flags, send init cmd to controller */
6251         if (instance->instancet->init_adapter(instance))
6252                 goto fail_init_adapter;
6253
6254         if (instance->adapter_type >= VENTURA_SERIES) {
6255                 scratch_pad_3 =
6256                         megasas_readl(instance,
6257                                       &instance->reg_set->outbound_scratch_pad_3);
6258                 if ((scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK) >=
6259                         MR_DEFAULT_NVME_PAGE_SHIFT)
6260                         instance->nvme_page_size =
6261                                 (1 << (scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK));
6262
6263                 dev_info(&instance->pdev->dev,
6264                          "NVME page size\t: (%d)\n", instance->nvme_page_size);
6265         }
6266
6267         if (instance->msix_vectors ?
6268                 megasas_setup_irqs_msix(instance, 1) :
6269                 megasas_setup_irqs_ioapic(instance))
6270                 goto fail_init_adapter;
6271
6272         if (instance->adapter_type != MFI_SERIES)
6273                 megasas_setup_irq_poll(instance);
6274
6275         instance->instancet->enable_intr(instance);
6276
6277         dev_info(&instance->pdev->dev, "INIT adapter done\n");
6278
6279         megasas_setup_jbod_map(instance);
6280
6281         if (megasas_get_device_list(instance) != SUCCESS) {
6282                 dev_err(&instance->pdev->dev,
6283                         "%s: megasas_get_device_list failed\n",
6284                         __func__);
6285                 goto fail_get_ld_pd_list;
6286         }
6287
6288         /* stream detection initialization */
6289         if (instance->adapter_type >= VENTURA_SERIES) {
6290                 fusion->stream_detect_by_ld =
6291                         kcalloc(MAX_LOGICAL_DRIVES_EXT,
6292                                 sizeof(struct LD_STREAM_DETECT *),
6293                                 GFP_KERNEL);
6294                 if (!fusion->stream_detect_by_ld) {
6295                         dev_err(&instance->pdev->dev,
6296                                 "unable to allocate stream detection for pool of LDs\n");
6297                         goto fail_get_ld_pd_list;
6298                 }
6299                 for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) {
6300                         fusion->stream_detect_by_ld[i] =
6301                                 kzalloc(sizeof(struct LD_STREAM_DETECT),
6302                                 GFP_KERNEL);
6303                         if (!fusion->stream_detect_by_ld[i]) {
6304                                 dev_err(&instance->pdev->dev,
6305                                         "unable to allocate stream detect by LD\n ");
6306                                 for (j = 0; j < i; ++j)
6307                                         kfree(fusion->stream_detect_by_ld[j]);
6308                                 kfree(fusion->stream_detect_by_ld);
6309                                 fusion->stream_detect_by_ld = NULL;
6310                                 goto fail_get_ld_pd_list;
6311                         }
6312                         fusion->stream_detect_by_ld[i]->mru_bit_map
6313                                 = MR_STREAM_BITMAP;
6314                 }
6315         }
6316
6317         /*
6318          * Compute the max allowed sectors per IO: The controller info has two
6319          * limits on max sectors. Driver should use the minimum of these two.
6320          *
6321          * 1 << stripe_sz_ops.min = max sectors per strip
6322          *
6323          * Note that older firmwares ( < FW ver 30) didn't report information
6324          * to calculate max_sectors_1. So the number ended up as zero always.
6325          */
6326         tmp_sectors = 0;
6327         ctrl_info = instance->ctrl_info_buf;
6328
6329         max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
6330                 le16_to_cpu(ctrl_info->max_strips_per_io);
6331         max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size);
6332
6333         tmp_sectors = min_t(u32, max_sectors_1, max_sectors_2);
6334
6335         instance->peerIsPresent = ctrl_info->cluster.peerIsPresent;
6336         instance->passive = ctrl_info->cluster.passive;
6337         memcpy(instance->clusterId, ctrl_info->clusterId, sizeof(instance->clusterId));
6338         instance->UnevenSpanSupport =
6339                 ctrl_info->adapterOperations2.supportUnevenSpans;
6340         if (instance->UnevenSpanSupport) {
6341                 struct fusion_context *fusion = instance->ctrl_context;
6342                 if (MR_ValidateMapInfo(instance, instance->map_id))
6343                         fusion->fast_path_io = 1;
6344                 else
6345                         fusion->fast_path_io = 0;
6346
6347         }
6348         if (ctrl_info->host_interface.SRIOV) {
6349                 instance->requestorId = ctrl_info->iov.requestorId;
6350                 if (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) {
6351                         if (!ctrl_info->adapterOperations2.activePassive)
6352                             instance->PlasmaFW111 = 1;
6353
6354                         dev_info(&instance->pdev->dev, "SR-IOV: firmware type: %s\n",
6355                             instance->PlasmaFW111 ? "1.11" : "new");
6356
6357                         if (instance->PlasmaFW111) {
6358                             iovPtr = (struct IOV_111 *)
6359                                 ((unsigned char *)ctrl_info + IOV_111_OFFSET);
6360                             instance->requestorId = iovPtr->requestorId;
6361                         }
6362                 }
6363                 dev_info(&instance->pdev->dev, "SRIOV: VF requestorId %d\n",
6364                         instance->requestorId);
6365         }
6366
6367         instance->crash_dump_fw_support =
6368                 ctrl_info->adapterOperations3.supportCrashDump;
6369         instance->crash_dump_drv_support =
6370                 (instance->crash_dump_fw_support &&
6371                 instance->crash_dump_buf);
6372         if (instance->crash_dump_drv_support)
6373                 megasas_set_crash_dump_params(instance,
6374                         MR_CRASH_BUF_TURN_OFF);
6375
6376         else {
6377                 if (instance->crash_dump_buf)
6378                         dma_free_coherent(&instance->pdev->dev,
6379                                 CRASH_DMA_BUF_SIZE,
6380                                 instance->crash_dump_buf,
6381                                 instance->crash_dump_h);
6382                 instance->crash_dump_buf = NULL;
6383         }
6384
6385         if (instance->snapdump_wait_time) {
6386                 megasas_get_snapdump_properties(instance);
6387                 dev_info(&instance->pdev->dev, "Snap dump wait time\t: %d\n",
6388                          instance->snapdump_wait_time);
6389         }
6390
6391         dev_info(&instance->pdev->dev,
6392                 "pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n",
6393                 le16_to_cpu(ctrl_info->pci.vendor_id),
6394                 le16_to_cpu(ctrl_info->pci.device_id),
6395                 le16_to_cpu(ctrl_info->pci.sub_vendor_id),
6396                 le16_to_cpu(ctrl_info->pci.sub_device_id));
6397         dev_info(&instance->pdev->dev, "unevenspan support      : %s\n",
6398                 instance->UnevenSpanSupport ? "yes" : "no");
6399         dev_info(&instance->pdev->dev, "firmware crash dump     : %s\n",
6400                 instance->crash_dump_drv_support ? "yes" : "no");
6401         dev_info(&instance->pdev->dev, "JBOD sequence map       : %s\n",
6402                 instance->use_seqnum_jbod_fp ? "enabled" : "disabled");
6403
6404         instance->max_sectors_per_req = instance->max_num_sge *
6405                                                 SGE_BUFFER_SIZE / 512;
6406         if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
6407                 instance->max_sectors_per_req = tmp_sectors;
6408
6409         /* Check for valid throttlequeuedepth module parameter */
6410         if (throttlequeuedepth &&
6411                         throttlequeuedepth <= instance->max_scsi_cmds)
6412                 instance->throttlequeuedepth = throttlequeuedepth;
6413         else
6414                 instance->throttlequeuedepth =
6415                                 MEGASAS_THROTTLE_QUEUE_DEPTH;
6416
6417         if ((resetwaittime < 1) ||
6418             (resetwaittime > MEGASAS_RESET_WAIT_TIME))
6419                 resetwaittime = MEGASAS_RESET_WAIT_TIME;
6420
6421         if ((scmd_timeout < 10) || (scmd_timeout > MEGASAS_DEFAULT_CMD_TIMEOUT))
6422                 scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT;
6423
6424         /* Launch SR-IOV heartbeat timer */
6425         if (instance->requestorId) {
6426                 if (!megasas_sriov_start_heartbeat(instance, 1)) {
6427                         megasas_start_timer(instance);
6428                 } else {
6429                         instance->skip_heartbeat_timer_del = 1;
6430                         goto fail_get_ld_pd_list;
6431                 }
6432         }
6433
6434         /*
6435          * Create and start watchdog thread which will monitor
6436          * controller state every 1 sec and trigger OCR when
6437          * it enters fault state
6438          */
6439         if (instance->adapter_type != MFI_SERIES)
6440                 if (megasas_fusion_start_watchdog(instance) != SUCCESS)
6441                         goto fail_start_watchdog;
6442
6443         return 0;
6444
6445 fail_start_watchdog:
6446         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
6447                 del_timer_sync(&instance->sriov_heartbeat_timer);
6448 fail_get_ld_pd_list:
6449         instance->instancet->disable_intr(instance);
6450         megasas_destroy_irqs(instance);
6451 fail_init_adapter:
6452         if (instance->msix_vectors)
6453                 pci_free_irq_vectors(instance->pdev);
6454         instance->msix_vectors = 0;
6455 fail_alloc_dma_buf:
6456         megasas_free_ctrl_dma_buffers(instance);
6457         megasas_free_ctrl_mem(instance);
6458 fail_ready_state:
6459         iounmap(instance->reg_set);
6460
6461 fail_ioremap:
6462         pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6463
6464         dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6465                 __func__, __LINE__);
6466         return -EINVAL;
6467 }
6468
6469 /**
6470  * megasas_release_mfi -        Reverses the FW initialization
6471  * @instance:                   Adapter soft state
6472  */
6473 static void megasas_release_mfi(struct megasas_instance *instance)
6474 {
6475         u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
6476
6477         if (instance->reply_queue)
6478                 dma_free_coherent(&instance->pdev->dev, reply_q_sz,
6479                             instance->reply_queue, instance->reply_queue_h);
6480
6481         megasas_free_cmds(instance);
6482
6483         iounmap(instance->reg_set);
6484
6485         pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6486 }
6487
6488 /**
6489  * megasas_get_seq_num -        Gets latest event sequence numbers
6490  * @instance:                   Adapter soft state
6491  * @eli:                        FW event log sequence numbers information
6492  *
6493  * FW maintains a log of all events in a non-volatile area. Upper layers would
6494  * usually find out the latest sequence number of the events, the seq number at
6495  * the boot etc. They would "read" all the events below the latest seq number
6496  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
6497  * number), they would subsribe to AEN (asynchronous event notification) and
6498  * wait for the events to happen.
6499  */
6500 static int
6501 megasas_get_seq_num(struct megasas_instance *instance,
6502                     struct megasas_evt_log_info *eli)
6503 {
6504         struct megasas_cmd *cmd;
6505         struct megasas_dcmd_frame *dcmd;
6506         struct megasas_evt_log_info *el_info;
6507         dma_addr_t el_info_h = 0;
6508         int ret;
6509
6510         cmd = megasas_get_cmd(instance);
6511
6512         if (!cmd) {
6513                 return -ENOMEM;
6514         }
6515
6516         dcmd = &cmd->frame->dcmd;
6517         el_info = dma_alloc_coherent(&instance->pdev->dev,
6518                                      sizeof(struct megasas_evt_log_info),
6519                                      &el_info_h, GFP_KERNEL);
6520         if (!el_info) {
6521                 megasas_return_cmd(instance, cmd);
6522                 return -ENOMEM;
6523         }
6524
6525         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6526
6527         dcmd->cmd = MFI_CMD_DCMD;
6528         dcmd->cmd_status = 0x0;
6529         dcmd->sge_count = 1;
6530         dcmd->flags = MFI_FRAME_DIR_READ;
6531         dcmd->timeout = 0;
6532         dcmd->pad_0 = 0;
6533         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_log_info));
6534         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_GET_INFO);
6535
6536         megasas_set_dma_settings(instance, dcmd, el_info_h,
6537                                  sizeof(struct megasas_evt_log_info));
6538
6539         ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
6540         if (ret != DCMD_SUCCESS) {
6541                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6542                         __func__, __LINE__);
6543                 goto dcmd_failed;
6544         }
6545
6546         /*
6547          * Copy the data back into callers buffer
6548          */
6549         eli->newest_seq_num = el_info->newest_seq_num;
6550         eli->oldest_seq_num = el_info->oldest_seq_num;
6551         eli->clear_seq_num = el_info->clear_seq_num;
6552         eli->shutdown_seq_num = el_info->shutdown_seq_num;
6553         eli->boot_seq_num = el_info->boot_seq_num;
6554
6555 dcmd_failed:
6556         dma_free_coherent(&instance->pdev->dev,
6557                         sizeof(struct megasas_evt_log_info),
6558                         el_info, el_info_h);
6559
6560         megasas_return_cmd(instance, cmd);
6561
6562         return ret;
6563 }
6564
6565 /**
6566  * megasas_register_aen -       Registers for asynchronous event notification
6567  * @instance:                   Adapter soft state
6568  * @seq_num:                    The starting sequence number
6569  * @class_locale_word:          Class of the event
6570  *
6571  * This function subscribes for AEN for events beyond the @seq_num. It requests
6572  * to be notified if and only if the event is of type @class_locale
6573  */
6574 static int
6575 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
6576                      u32 class_locale_word)
6577 {
6578         int ret_val;
6579         struct megasas_cmd *cmd;
6580         struct megasas_dcmd_frame *dcmd;
6581         union megasas_evt_class_locale curr_aen;
6582         union megasas_evt_class_locale prev_aen;
6583
6584         /*
6585          * If there an AEN pending already (aen_cmd), check if the
6586          * class_locale of that pending AEN is inclusive of the new
6587          * AEN request we currently have. If it is, then we don't have
6588          * to do anything. In other words, whichever events the current
6589          * AEN request is subscribing to, have already been subscribed
6590          * to.
6591          *
6592          * If the old_cmd is _not_ inclusive, then we have to abort
6593          * that command, form a class_locale that is superset of both
6594          * old and current and re-issue to the FW
6595          */
6596
6597         curr_aen.word = class_locale_word;
6598
6599         if (instance->aen_cmd) {
6600
6601                 prev_aen.word =
6602                         le32_to_cpu(instance->aen_cmd->frame->dcmd.mbox.w[1]);
6603
6604                 if ((curr_aen.members.class < MFI_EVT_CLASS_DEBUG) ||
6605                     (curr_aen.members.class > MFI_EVT_CLASS_DEAD)) {
6606                         dev_info(&instance->pdev->dev,
6607                                  "%s %d out of range class %d send by application\n",
6608                                  __func__, __LINE__, curr_aen.members.class);
6609                         return 0;
6610                 }
6611
6612                 /*
6613                  * A class whose enum value is smaller is inclusive of all
6614                  * higher values. If a PROGRESS (= -1) was previously
6615                  * registered, then a new registration requests for higher
6616                  * classes need not be sent to FW. They are automatically
6617                  * included.
6618                  *
6619                  * Locale numbers don't have such hierarchy. They are bitmap
6620                  * values
6621                  */
6622                 if ((prev_aen.members.class <= curr_aen.members.class) &&
6623                     !((prev_aen.members.locale & curr_aen.members.locale) ^
6624                       curr_aen.members.locale)) {
6625                         /*
6626                          * Previously issued event registration includes
6627                          * current request. Nothing to do.
6628                          */
6629                         return 0;
6630                 } else {
6631                         curr_aen.members.locale |= prev_aen.members.locale;
6632
6633                         if (prev_aen.members.class < curr_aen.members.class)
6634                                 curr_aen.members.class = prev_aen.members.class;
6635
6636                         instance->aen_cmd->abort_aen = 1;
6637                         ret_val = megasas_issue_blocked_abort_cmd(instance,
6638                                                                   instance->
6639                                                                   aen_cmd, 30);
6640
6641                         if (ret_val) {
6642                                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to abort "
6643                                        "previous AEN command\n");
6644                                 return ret_val;
6645                         }
6646                 }
6647         }
6648
6649         cmd = megasas_get_cmd(instance);
6650
6651         if (!cmd)
6652                 return -ENOMEM;
6653
6654         dcmd = &cmd->frame->dcmd;
6655
6656         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
6657
6658         /*
6659          * Prepare DCMD for aen registration
6660          */
6661         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6662
6663         dcmd->cmd = MFI_CMD_DCMD;
6664         dcmd->cmd_status = 0x0;
6665         dcmd->sge_count = 1;
6666         dcmd->flags = MFI_FRAME_DIR_READ;
6667         dcmd->timeout = 0;
6668         dcmd->pad_0 = 0;
6669         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_detail));
6670         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_WAIT);
6671         dcmd->mbox.w[0] = cpu_to_le32(seq_num);
6672         instance->last_seq_num = seq_num;
6673         dcmd->mbox.w[1] = cpu_to_le32(curr_aen.word);
6674
6675         megasas_set_dma_settings(instance, dcmd, instance->evt_detail_h,
6676                                  sizeof(struct megasas_evt_detail));
6677
6678         if (instance->aen_cmd != NULL) {
6679                 megasas_return_cmd(instance, cmd);
6680                 return 0;
6681         }
6682
6683         /*
6684          * Store reference to the cmd used to register for AEN. When an
6685          * application wants us to register for AEN, we have to abort this
6686          * cmd and re-register with a new EVENT LOCALE supplied by that app
6687          */
6688         instance->aen_cmd = cmd;
6689
6690         /*
6691          * Issue the aen registration frame
6692          */
6693         instance->instancet->issue_dcmd(instance, cmd);
6694
6695         return 0;
6696 }
6697
6698 /* megasas_get_target_prop - Send DCMD with below details to firmware.
6699  *
6700  * This DCMD will fetch few properties of LD/system PD defined
6701  * in MR_TARGET_DEV_PROPERTIES. eg. Queue Depth, MDTS value.
6702  *
6703  * DCMD send by drivers whenever new target is added to the OS.
6704  *
6705  * dcmd.opcode         - MR_DCMD_DEV_GET_TARGET_PROP
6706  * dcmd.mbox.b[0]      - DCMD is to be fired for LD or system PD.
6707  *                       0 = system PD, 1 = LD.
6708  * dcmd.mbox.s[1]      - TargetID for LD/system PD.
6709  * dcmd.sge IN         - Pointer to return MR_TARGET_DEV_PROPERTIES.
6710  *
6711  * @instance:           Adapter soft state
6712  * @sdev:               OS provided scsi device
6713  *
6714  * Returns 0 on success non-zero on failure.
6715  */
6716 int
6717 megasas_get_target_prop(struct megasas_instance *instance,
6718                         struct scsi_device *sdev)
6719 {
6720         int ret;
6721         struct megasas_cmd *cmd;
6722         struct megasas_dcmd_frame *dcmd;
6723         u16 targetId = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL) +
6724                         sdev->id;
6725
6726         cmd = megasas_get_cmd(instance);
6727
6728         if (!cmd) {
6729                 dev_err(&instance->pdev->dev,
6730                         "Failed to get cmd %s\n", __func__);
6731                 return -ENOMEM;
6732         }
6733
6734         dcmd = &cmd->frame->dcmd;
6735
6736         memset(instance->tgt_prop, 0, sizeof(*instance->tgt_prop));
6737         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6738         dcmd->mbox.b[0] = MEGASAS_IS_LOGICAL(sdev);
6739
6740         dcmd->mbox.s[1] = cpu_to_le16(targetId);
6741         dcmd->cmd = MFI_CMD_DCMD;
6742         dcmd->cmd_status = 0xFF;
6743         dcmd->sge_count = 1;
6744         dcmd->flags = MFI_FRAME_DIR_READ;
6745         dcmd->timeout = 0;
6746         dcmd->pad_0 = 0;
6747         dcmd->data_xfer_len =
6748                 cpu_to_le32(sizeof(struct MR_TARGET_PROPERTIES));
6749         dcmd->opcode = cpu_to_le32(MR_DCMD_DRV_GET_TARGET_PROP);
6750
6751         megasas_set_dma_settings(instance, dcmd, instance->tgt_prop_h,
6752                                  sizeof(struct MR_TARGET_PROPERTIES));
6753
6754         if ((instance->adapter_type != MFI_SERIES) &&
6755             !instance->mask_interrupts)
6756                 ret = megasas_issue_blocked_cmd(instance,
6757                                                 cmd, MFI_IO_TIMEOUT_SECS);
6758         else
6759                 ret = megasas_issue_polled(instance, cmd);
6760
6761         switch (ret) {
6762         case DCMD_TIMEOUT:
6763                 switch (dcmd_timeout_ocr_possible(instance)) {
6764                 case INITIATE_OCR:
6765                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
6766                         mutex_unlock(&instance->reset_mutex);
6767                         megasas_reset_fusion(instance->host,
6768                                              MFI_IO_TIMEOUT_OCR);
6769                         mutex_lock(&instance->reset_mutex);
6770                         break;
6771                 case KILL_ADAPTER:
6772                         megaraid_sas_kill_hba(instance);
6773                         break;
6774                 case IGNORE_TIMEOUT:
6775                         dev_info(&instance->pdev->dev,
6776                                  "Ignore DCMD timeout: %s %d\n",
6777                                  __func__, __LINE__);
6778                         break;
6779                 }
6780                 break;
6781
6782         default:
6783                 megasas_return_cmd(instance, cmd);
6784         }
6785         if (ret != DCMD_SUCCESS)
6786                 dev_err(&instance->pdev->dev,
6787                         "return from %s %d return value %d\n",
6788                         __func__, __LINE__, ret);
6789
6790         return ret;
6791 }
6792
6793 /**
6794  * megasas_start_aen -  Subscribes to AEN during driver load time
6795  * @instance:           Adapter soft state
6796  */
6797 static int megasas_start_aen(struct megasas_instance *instance)
6798 {
6799         struct megasas_evt_log_info eli;
6800         union megasas_evt_class_locale class_locale;
6801
6802         /*
6803          * Get the latest sequence number from FW
6804          */
6805         memset(&eli, 0, sizeof(eli));
6806
6807         if (megasas_get_seq_num(instance, &eli))
6808                 return -1;
6809
6810         /*
6811          * Register AEN with FW for latest sequence number plus 1
6812          */
6813         class_locale.members.reserved = 0;
6814         class_locale.members.locale = MR_EVT_LOCALE_ALL;
6815         class_locale.members.class = MR_EVT_CLASS_DEBUG;
6816
6817         return megasas_register_aen(instance,
6818                         le32_to_cpu(eli.newest_seq_num) + 1,
6819                         class_locale.word);
6820 }
6821
6822 /**
6823  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
6824  * @instance:           Adapter soft state
6825  */
6826 static int megasas_io_attach(struct megasas_instance *instance)
6827 {
6828         struct Scsi_Host *host = instance->host;
6829
6830         /*
6831          * Export parameters required by SCSI mid-layer
6832          */
6833         host->unique_id = instance->unique_id;
6834         host->can_queue = instance->max_scsi_cmds;
6835         host->this_id = instance->init_id;
6836         host->sg_tablesize = instance->max_num_sge;
6837
6838         if (instance->fw_support_ieee)
6839                 instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
6840
6841         /*
6842          * Check if the module parameter value for max_sectors can be used
6843          */
6844         if (max_sectors && max_sectors < instance->max_sectors_per_req)
6845                 instance->max_sectors_per_req = max_sectors;
6846         else {
6847                 if (max_sectors) {
6848                         if (((instance->pdev->device ==
6849                                 PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
6850                                 (instance->pdev->device ==
6851                                 PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
6852                                 (max_sectors <= MEGASAS_MAX_SECTORS)) {
6853                                 instance->max_sectors_per_req = max_sectors;
6854                         } else {
6855                         dev_info(&instance->pdev->dev, "max_sectors should be > 0"
6856                                 "and <= %d (or < 1MB for GEN2 controller)\n",
6857                                 instance->max_sectors_per_req);
6858                         }
6859                 }
6860         }
6861
6862         host->max_sectors = instance->max_sectors_per_req;
6863         host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
6864         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
6865         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
6866         host->max_lun = MEGASAS_MAX_LUN;
6867         host->max_cmd_len = 16;
6868
6869         /*
6870          * Notify the mid-layer about the new controller
6871          */
6872         if (scsi_add_host(host, &instance->pdev->dev)) {
6873                 dev_err(&instance->pdev->dev,
6874                         "Failed to add host from %s %d\n",
6875                         __func__, __LINE__);
6876                 return -ENODEV;
6877         }
6878
6879         return 0;
6880 }
6881
6882 /**
6883  * megasas_set_dma_mask -       Set DMA mask for supported controllers
6884  *
6885  * @instance:           Adapter soft state
6886  * Description:
6887  *
6888  * For Ventura, driver/FW will operate in 63bit DMA addresses.
6889  *
6890  * For invader-
6891  *      By default, driver/FW will operate in 32bit DMA addresses
6892  *      for consistent DMA mapping but if 32 bit consistent
6893  *      DMA mask fails, driver will try with 63 bit consistent
6894  *      mask provided FW is true 63bit DMA capable
6895  *
6896  * For older controllers(Thunderbolt and MFI based adapters)-
6897  *      driver/FW will operate in 32 bit consistent DMA addresses.
6898  */
6899 static int
6900 megasas_set_dma_mask(struct megasas_instance *instance)
6901 {
6902         u64 consistent_mask;
6903         struct pci_dev *pdev;
6904         u32 scratch_pad_1;
6905
6906         pdev = instance->pdev;
6907         consistent_mask = (instance->adapter_type >= VENTURA_SERIES) ?
6908                                 DMA_BIT_MASK(63) : DMA_BIT_MASK(32);
6909
6910         if (IS_DMA64) {
6911                 if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(63)) &&
6912                     dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
6913                         goto fail_set_dma_mask;
6914
6915                 if ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) &&
6916                     (dma_set_coherent_mask(&pdev->dev, consistent_mask) &&
6917                      dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))) {
6918                         /*
6919                          * If 32 bit DMA mask fails, then try for 64 bit mask
6920                          * for FW capable of handling 64 bit DMA.
6921                          */
6922                         scratch_pad_1 = megasas_readl
6923                                 (instance, &instance->reg_set->outbound_scratch_pad_1);
6924
6925                         if (!(scratch_pad_1 & MR_CAN_HANDLE_64_BIT_DMA_OFFSET))
6926                                 goto fail_set_dma_mask;
6927                         else if (dma_set_mask_and_coherent(&pdev->dev,
6928                                                            DMA_BIT_MASK(63)))
6929                                 goto fail_set_dma_mask;
6930                 }
6931         } else if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
6932                 goto fail_set_dma_mask;
6933
6934         if (pdev->dev.coherent_dma_mask == DMA_BIT_MASK(32))
6935                 instance->consistent_mask_64bit = false;
6936         else
6937                 instance->consistent_mask_64bit = true;
6938
6939         dev_info(&pdev->dev, "%s bit DMA mask and %s bit consistent mask\n",
6940                  ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) ? "63" : "32"),
6941                  (instance->consistent_mask_64bit ? "63" : "32"));
6942
6943         return 0;
6944
6945 fail_set_dma_mask:
6946         dev_err(&pdev->dev, "Failed to set DMA mask\n");
6947         return -1;
6948
6949 }
6950
6951 /*
6952  * megasas_set_adapter_type -   Set adapter type.
6953  *                              Supported controllers can be divided in
6954  *                              different categories-
6955  *                                      enum MR_ADAPTER_TYPE {
6956  *                                              MFI_SERIES = 1,
6957  *                                              THUNDERBOLT_SERIES = 2,
6958  *                                              INVADER_SERIES = 3,
6959  *                                              VENTURA_SERIES = 4,
6960  *                                              AERO_SERIES = 5,
6961  *                                      };
6962  * @instance:                   Adapter soft state
6963  * return:                      void
6964  */
6965 static inline void megasas_set_adapter_type(struct megasas_instance *instance)
6966 {
6967         if ((instance->pdev->vendor == PCI_VENDOR_ID_DELL) &&
6968             (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5)) {
6969                 instance->adapter_type = MFI_SERIES;
6970         } else {
6971                 switch (instance->pdev->device) {
6972                 case PCI_DEVICE_ID_LSI_AERO_10E1:
6973                 case PCI_DEVICE_ID_LSI_AERO_10E2:
6974                 case PCI_DEVICE_ID_LSI_AERO_10E5:
6975                 case PCI_DEVICE_ID_LSI_AERO_10E6:
6976                         instance->adapter_type = AERO_SERIES;
6977                         break;
6978                 case PCI_DEVICE_ID_LSI_VENTURA:
6979                 case PCI_DEVICE_ID_LSI_CRUSADER:
6980                 case PCI_DEVICE_ID_LSI_HARPOON:
6981                 case PCI_DEVICE_ID_LSI_TOMCAT:
6982                 case PCI_DEVICE_ID_LSI_VENTURA_4PORT:
6983                 case PCI_DEVICE_ID_LSI_CRUSADER_4PORT:
6984                         instance->adapter_type = VENTURA_SERIES;
6985                         break;
6986                 case PCI_DEVICE_ID_LSI_FUSION:
6987                 case PCI_DEVICE_ID_LSI_PLASMA:
6988                         instance->adapter_type = THUNDERBOLT_SERIES;
6989                         break;
6990                 case PCI_DEVICE_ID_LSI_INVADER:
6991                 case PCI_DEVICE_ID_LSI_INTRUDER:
6992                 case PCI_DEVICE_ID_LSI_INTRUDER_24:
6993                 case PCI_DEVICE_ID_LSI_CUTLASS_52:
6994                 case PCI_DEVICE_ID_LSI_CUTLASS_53:
6995                 case PCI_DEVICE_ID_LSI_FURY:
6996                         instance->adapter_type = INVADER_SERIES;
6997                         break;
6998                 default: /* For all other supported controllers */
6999                         instance->adapter_type = MFI_SERIES;
7000                         break;
7001                 }
7002         }
7003 }
7004
7005 static inline int megasas_alloc_mfi_ctrl_mem(struct megasas_instance *instance)
7006 {
7007         instance->producer = dma_alloc_coherent(&instance->pdev->dev,
7008                         sizeof(u32), &instance->producer_h, GFP_KERNEL);
7009         instance->consumer = dma_alloc_coherent(&instance->pdev->dev,
7010                         sizeof(u32), &instance->consumer_h, GFP_KERNEL);
7011
7012         if (!instance->producer || !instance->consumer) {
7013                 dev_err(&instance->pdev->dev,
7014                         "Failed to allocate memory for producer, consumer\n");
7015                 return -1;
7016         }
7017
7018         *instance->producer = 0;
7019         *instance->consumer = 0;
7020         return 0;
7021 }
7022
7023 /**
7024  * megasas_alloc_ctrl_mem -     Allocate per controller memory for core data
7025  *                              structures which are not common across MFI
7026  *                              adapters and fusion adapters.
7027  *                              For MFI based adapters, allocate producer and
7028  *                              consumer buffers. For fusion adapters, allocate
7029  *                              memory for fusion context.
7030  * @instance:                   Adapter soft state
7031  * return:                      0 for SUCCESS
7032  */
7033 static int megasas_alloc_ctrl_mem(struct megasas_instance *instance)
7034 {
7035         instance->reply_map = kcalloc(nr_cpu_ids, sizeof(unsigned int),
7036                                       GFP_KERNEL);
7037         if (!instance->reply_map)
7038                 return -ENOMEM;
7039
7040         switch (instance->adapter_type) {
7041         case MFI_SERIES:
7042                 if (megasas_alloc_mfi_ctrl_mem(instance))
7043                         goto fail;
7044                 break;
7045         case AERO_SERIES:
7046         case VENTURA_SERIES:
7047         case THUNDERBOLT_SERIES:
7048         case INVADER_SERIES:
7049                 if (megasas_alloc_fusion_context(instance))
7050                         goto fail;
7051                 break;
7052         }
7053
7054         return 0;
7055  fail:
7056         kfree(instance->reply_map);
7057         instance->reply_map = NULL;
7058         return -ENOMEM;
7059 }
7060
7061 /*
7062  * megasas_free_ctrl_mem -      Free fusion context for fusion adapters and
7063  *                              producer, consumer buffers for MFI adapters
7064  *
7065  * @instance -                  Adapter soft instance
7066  *
7067  */
7068 static inline void megasas_free_ctrl_mem(struct megasas_instance *instance)
7069 {
7070         kfree(instance->reply_map);
7071         if (instance->adapter_type == MFI_SERIES) {
7072                 if (instance->producer)
7073                         dma_free_coherent(&instance->pdev->dev, sizeof(u32),
7074                                             instance->producer,
7075                                             instance->producer_h);
7076                 if (instance->consumer)
7077                         dma_free_coherent(&instance->pdev->dev, sizeof(u32),
7078                                             instance->consumer,
7079                                             instance->consumer_h);
7080         } else {
7081                 megasas_free_fusion_context(instance);
7082         }
7083 }
7084
7085 /**
7086  * megasas_alloc_ctrl_dma_buffers -     Allocate consistent DMA buffers during
7087  *                                      driver load time
7088  *
7089  * @instance:                           Adapter soft instance
7090  *
7091  * @return:                             O for SUCCESS
7092  */
7093 static inline
7094 int megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance)
7095 {
7096         struct pci_dev *pdev = instance->pdev;
7097         struct fusion_context *fusion = instance->ctrl_context;
7098
7099         instance->evt_detail = dma_alloc_coherent(&pdev->dev,
7100                         sizeof(struct megasas_evt_detail),
7101                         &instance->evt_detail_h, GFP_KERNEL);
7102
7103         if (!instance->evt_detail) {
7104                 dev_err(&instance->pdev->dev,
7105                         "Failed to allocate event detail buffer\n");
7106                 return -ENOMEM;
7107         }
7108
7109         if (fusion) {
7110                 fusion->ioc_init_request =
7111                         dma_alloc_coherent(&pdev->dev,
7112                                            sizeof(struct MPI2_IOC_INIT_REQUEST),
7113                                            &fusion->ioc_init_request_phys,
7114                                            GFP_KERNEL);
7115
7116                 if (!fusion->ioc_init_request) {
7117                         dev_err(&pdev->dev,
7118                                 "Failed to allocate PD list buffer\n");
7119                         return -ENOMEM;
7120                 }
7121
7122                 instance->snapdump_prop = dma_alloc_coherent(&pdev->dev,
7123                                 sizeof(struct MR_SNAPDUMP_PROPERTIES),
7124                                 &instance->snapdump_prop_h, GFP_KERNEL);
7125
7126                 if (!instance->snapdump_prop)
7127                         dev_err(&pdev->dev,
7128                                 "Failed to allocate snapdump properties buffer\n");
7129
7130                 instance->host_device_list_buf = dma_alloc_coherent(&pdev->dev,
7131                                                         HOST_DEVICE_LIST_SZ,
7132                                                         &instance->host_device_list_buf_h,
7133                                                         GFP_KERNEL);
7134
7135                 if (!instance->host_device_list_buf) {
7136                         dev_err(&pdev->dev,
7137                                 "Failed to allocate targetid list buffer\n");
7138                         return -ENOMEM;
7139                 }
7140
7141         }
7142
7143         instance->pd_list_buf =
7144                 dma_alloc_coherent(&pdev->dev,
7145                                      MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
7146                                      &instance->pd_list_buf_h, GFP_KERNEL);
7147
7148         if (!instance->pd_list_buf) {
7149                 dev_err(&pdev->dev, "Failed to allocate PD list buffer\n");
7150                 return -ENOMEM;
7151         }
7152
7153         instance->ctrl_info_buf =
7154                 dma_alloc_coherent(&pdev->dev,
7155                                      sizeof(struct megasas_ctrl_info),
7156                                      &instance->ctrl_info_buf_h, GFP_KERNEL);
7157
7158         if (!instance->ctrl_info_buf) {
7159                 dev_err(&pdev->dev,
7160                         "Failed to allocate controller info buffer\n");
7161                 return -ENOMEM;
7162         }
7163
7164         instance->ld_list_buf =
7165                 dma_alloc_coherent(&pdev->dev,
7166                                      sizeof(struct MR_LD_LIST),
7167                                      &instance->ld_list_buf_h, GFP_KERNEL);
7168
7169         if (!instance->ld_list_buf) {
7170                 dev_err(&pdev->dev, "Failed to allocate LD list buffer\n");
7171                 return -ENOMEM;
7172         }
7173
7174         instance->ld_targetid_list_buf =
7175                 dma_alloc_coherent(&pdev->dev,
7176                                 sizeof(struct MR_LD_TARGETID_LIST),
7177                                 &instance->ld_targetid_list_buf_h, GFP_KERNEL);
7178
7179         if (!instance->ld_targetid_list_buf) {
7180                 dev_err(&pdev->dev,
7181                         "Failed to allocate LD targetid list buffer\n");
7182                 return -ENOMEM;
7183         }
7184
7185         if (!reset_devices) {
7186                 instance->system_info_buf =
7187                         dma_alloc_coherent(&pdev->dev,
7188                                         sizeof(struct MR_DRV_SYSTEM_INFO),
7189                                         &instance->system_info_h, GFP_KERNEL);
7190                 instance->pd_info =
7191                         dma_alloc_coherent(&pdev->dev,
7192                                         sizeof(struct MR_PD_INFO),
7193                                         &instance->pd_info_h, GFP_KERNEL);
7194                 instance->tgt_prop =
7195                         dma_alloc_coherent(&pdev->dev,
7196                                         sizeof(struct MR_TARGET_PROPERTIES),
7197                                         &instance->tgt_prop_h, GFP_KERNEL);
7198                 instance->crash_dump_buf =
7199                         dma_alloc_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
7200                                         &instance->crash_dump_h, GFP_KERNEL);
7201
7202                 if (!instance->system_info_buf)
7203                         dev_err(&instance->pdev->dev,
7204                                 "Failed to allocate system info buffer\n");
7205
7206                 if (!instance->pd_info)
7207                         dev_err(&instance->pdev->dev,
7208                                 "Failed to allocate pd_info buffer\n");
7209
7210                 if (!instance->tgt_prop)
7211                         dev_err(&instance->pdev->dev,
7212                                 "Failed to allocate tgt_prop buffer\n");
7213
7214                 if (!instance->crash_dump_buf)
7215                         dev_err(&instance->pdev->dev,
7216                                 "Failed to allocate crash dump buffer\n");
7217         }
7218
7219         return 0;
7220 }
7221
7222 /*
7223  * megasas_free_ctrl_dma_buffers -      Free consistent DMA buffers allocated
7224  *                                      during driver load time
7225  *
7226  * @instance-                           Adapter soft instance
7227  *
7228  */
7229 static inline
7230 void megasas_free_ctrl_dma_buffers(struct megasas_instance *instance)
7231 {
7232         struct pci_dev *pdev = instance->pdev;
7233         struct fusion_context *fusion = instance->ctrl_context;
7234
7235         if (instance->evt_detail)
7236                 dma_free_coherent(&pdev->dev, sizeof(struct megasas_evt_detail),
7237                                     instance->evt_detail,
7238                                     instance->evt_detail_h);
7239
7240         if (fusion && fusion->ioc_init_request)
7241                 dma_free_coherent(&pdev->dev,
7242                                   sizeof(struct MPI2_IOC_INIT_REQUEST),
7243                                   fusion->ioc_init_request,
7244                                   fusion->ioc_init_request_phys);
7245
7246         if (instance->pd_list_buf)
7247                 dma_free_coherent(&pdev->dev,
7248                                     MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
7249                                     instance->pd_list_buf,
7250                                     instance->pd_list_buf_h);
7251
7252         if (instance->ld_list_buf)
7253                 dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_LIST),
7254                                     instance->ld_list_buf,
7255                                     instance->ld_list_buf_h);
7256
7257         if (instance->ld_targetid_list_buf)
7258                 dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_TARGETID_LIST),
7259                                     instance->ld_targetid_list_buf,
7260                                     instance->ld_targetid_list_buf_h);
7261
7262         if (instance->ctrl_info_buf)
7263                 dma_free_coherent(&pdev->dev, sizeof(struct megasas_ctrl_info),
7264                                     instance->ctrl_info_buf,
7265                                     instance->ctrl_info_buf_h);
7266
7267         if (instance->system_info_buf)
7268                 dma_free_coherent(&pdev->dev, sizeof(struct MR_DRV_SYSTEM_INFO),
7269                                     instance->system_info_buf,
7270                                     instance->system_info_h);
7271
7272         if (instance->pd_info)
7273                 dma_free_coherent(&pdev->dev, sizeof(struct MR_PD_INFO),
7274                                     instance->pd_info, instance->pd_info_h);
7275
7276         if (instance->tgt_prop)
7277                 dma_free_coherent(&pdev->dev, sizeof(struct MR_TARGET_PROPERTIES),
7278                                     instance->tgt_prop, instance->tgt_prop_h);
7279
7280         if (instance->crash_dump_buf)
7281                 dma_free_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
7282                                     instance->crash_dump_buf,
7283                                     instance->crash_dump_h);
7284
7285         if (instance->snapdump_prop)
7286                 dma_free_coherent(&pdev->dev,
7287                                   sizeof(struct MR_SNAPDUMP_PROPERTIES),
7288                                   instance->snapdump_prop,
7289                                   instance->snapdump_prop_h);
7290
7291         if (instance->host_device_list_buf)
7292                 dma_free_coherent(&pdev->dev,
7293                                   HOST_DEVICE_LIST_SZ,
7294                                   instance->host_device_list_buf,
7295                                   instance->host_device_list_buf_h);
7296
7297 }
7298
7299 /*
7300  * megasas_init_ctrl_params -           Initialize controller's instance
7301  *                                      parameters before FW init
7302  * @instance -                          Adapter soft instance
7303  * @return -                            void
7304  */
7305 static inline void megasas_init_ctrl_params(struct megasas_instance *instance)
7306 {
7307         instance->fw_crash_state = UNAVAILABLE;
7308
7309         megasas_poll_wait_aen = 0;
7310         instance->issuepend_done = 1;
7311         atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
7312
7313         /*
7314          * Initialize locks and queues
7315          */
7316         INIT_LIST_HEAD(&instance->cmd_pool);
7317         INIT_LIST_HEAD(&instance->internal_reset_pending_q);
7318
7319         atomic_set(&instance->fw_outstanding, 0);
7320         atomic64_set(&instance->total_io_count, 0);
7321
7322         init_waitqueue_head(&instance->int_cmd_wait_q);
7323         init_waitqueue_head(&instance->abort_cmd_wait_q);
7324
7325         mutex_init(&instance->crashdump_lock);
7326         spin_lock_init(&instance->mfi_pool_lock);
7327         spin_lock_init(&instance->hba_lock);
7328         spin_lock_init(&instance->stream_lock);
7329         spin_lock_init(&instance->completion_lock);
7330
7331         mutex_init(&instance->reset_mutex);
7332
7333         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
7334             (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY))
7335                 instance->flag_ieee = 1;
7336
7337         megasas_dbg_lvl = 0;
7338         instance->flag = 0;
7339         instance->unload = 1;
7340         instance->last_time = 0;
7341         instance->disableOnlineCtrlReset = 1;
7342         instance->UnevenSpanSupport = 0;
7343         instance->smp_affinity_enable = smp_affinity_enable ? true : false;
7344         instance->msix_load_balance = false;
7345
7346         if (instance->adapter_type != MFI_SERIES)
7347                 INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
7348         else
7349                 INIT_WORK(&instance->work_init, process_fw_state_change_wq);
7350 }
7351
7352 /**
7353  * megasas_probe_one -  PCI hotplug entry point
7354  * @pdev:               PCI device structure
7355  * @id:                 PCI ids of supported hotplugged adapter
7356  */
7357 static int megasas_probe_one(struct pci_dev *pdev,
7358                              const struct pci_device_id *id)
7359 {
7360         int rval, pos;
7361         struct Scsi_Host *host;
7362         struct megasas_instance *instance;
7363         u16 control = 0;
7364
7365         switch (pdev->device) {
7366         case PCI_DEVICE_ID_LSI_AERO_10E0:
7367         case PCI_DEVICE_ID_LSI_AERO_10E3:
7368         case PCI_DEVICE_ID_LSI_AERO_10E4:
7369         case PCI_DEVICE_ID_LSI_AERO_10E7:
7370                 dev_err(&pdev->dev, "Adapter is in non secure mode\n");
7371                 return 1;
7372         case PCI_DEVICE_ID_LSI_AERO_10E1:
7373         case PCI_DEVICE_ID_LSI_AERO_10E5:
7374                 dev_info(&pdev->dev, "Adapter is in configurable secure mode\n");
7375                 break;
7376         }
7377
7378         /* Reset MSI-X in the kdump kernel */
7379         if (reset_devices) {
7380                 pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
7381                 if (pos) {
7382                         pci_read_config_word(pdev, pos + PCI_MSIX_FLAGS,
7383                                              &control);
7384                         if (control & PCI_MSIX_FLAGS_ENABLE) {
7385                                 dev_info(&pdev->dev, "resetting MSI-X\n");
7386                                 pci_write_config_word(pdev,
7387                                                       pos + PCI_MSIX_FLAGS,
7388                                                       control &
7389                                                       ~PCI_MSIX_FLAGS_ENABLE);
7390                         }
7391                 }
7392         }
7393
7394         /*
7395          * PCI prepping: enable device set bus mastering and dma mask
7396          */
7397         rval = pci_enable_device_mem(pdev);
7398
7399         if (rval) {
7400                 return rval;
7401         }
7402
7403         pci_set_master(pdev);
7404
7405         host = scsi_host_alloc(&megasas_template,
7406                                sizeof(struct megasas_instance));
7407
7408         if (!host) {
7409                 dev_printk(KERN_DEBUG, &pdev->dev, "scsi_host_alloc failed\n");
7410                 goto fail_alloc_instance;
7411         }
7412
7413         instance = (struct megasas_instance *)host->hostdata;
7414         memset(instance, 0, sizeof(*instance));
7415         atomic_set(&instance->fw_reset_no_pci_access, 0);
7416
7417         /*
7418          * Initialize PCI related and misc parameters
7419          */
7420         instance->pdev = pdev;
7421         instance->host = host;
7422         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
7423         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
7424
7425         megasas_set_adapter_type(instance);
7426
7427         /*
7428          * Initialize MFI Firmware
7429          */
7430         if (megasas_init_fw(instance))
7431                 goto fail_init_mfi;
7432
7433         if (instance->requestorId) {
7434                 if (instance->PlasmaFW111) {
7435                         instance->vf_affiliation_111 =
7436                                 dma_alloc_coherent(&pdev->dev,
7437                                         sizeof(struct MR_LD_VF_AFFILIATION_111),
7438                                         &instance->vf_affiliation_111_h,
7439                                         GFP_KERNEL);
7440                         if (!instance->vf_affiliation_111)
7441                                 dev_warn(&pdev->dev, "Can't allocate "
7442                                        "memory for VF affiliation buffer\n");
7443                 } else {
7444                         instance->vf_affiliation =
7445                                 dma_alloc_coherent(&pdev->dev,
7446                                         (MAX_LOGICAL_DRIVES + 1) *
7447                                         sizeof(struct MR_LD_VF_AFFILIATION),
7448                                         &instance->vf_affiliation_h,
7449                                         GFP_KERNEL);
7450                         if (!instance->vf_affiliation)
7451                                 dev_warn(&pdev->dev, "Can't allocate "
7452                                        "memory for VF affiliation buffer\n");
7453                 }
7454         }
7455
7456         /*
7457          * Store instance in PCI softstate
7458          */
7459         pci_set_drvdata(pdev, instance);
7460
7461         /*
7462          * Add this controller to megasas_mgmt_info structure so that it
7463          * can be exported to management applications
7464          */
7465         megasas_mgmt_info.count++;
7466         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
7467         megasas_mgmt_info.max_index++;
7468
7469         /*
7470          * Register with SCSI mid-layer
7471          */
7472         if (megasas_io_attach(instance))
7473                 goto fail_io_attach;
7474
7475         instance->unload = 0;
7476         /*
7477          * Trigger SCSI to scan our drives
7478          */
7479         if (!instance->enable_fw_dev_list ||
7480             (instance->host_device_list_buf->count > 0))
7481                 scsi_scan_host(host);
7482
7483         /*
7484          * Initiate AEN (Asynchronous Event Notification)
7485          */
7486         if (megasas_start_aen(instance)) {
7487                 dev_printk(KERN_DEBUG, &pdev->dev, "start aen failed\n");
7488                 goto fail_start_aen;
7489         }
7490
7491         megasas_setup_debugfs(instance);
7492
7493         /* Get current SR-IOV LD/VF affiliation */
7494         if (instance->requestorId)
7495                 megasas_get_ld_vf_affiliation(instance, 1);
7496
7497         return 0;
7498
7499 fail_start_aen:
7500         instance->unload = 1;
7501         scsi_remove_host(instance->host);
7502 fail_io_attach:
7503         megasas_mgmt_info.count--;
7504         megasas_mgmt_info.max_index--;
7505         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
7506
7507         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7508                 del_timer_sync(&instance->sriov_heartbeat_timer);
7509
7510         instance->instancet->disable_intr(instance);
7511         megasas_destroy_irqs(instance);
7512
7513         if (instance->adapter_type != MFI_SERIES)
7514                 megasas_release_fusion(instance);
7515         else
7516                 megasas_release_mfi(instance);
7517
7518         if (instance->msix_vectors)
7519                 pci_free_irq_vectors(instance->pdev);
7520         instance->msix_vectors = 0;
7521
7522         if (instance->fw_crash_state != UNAVAILABLE)
7523                 megasas_free_host_crash_buffer(instance);
7524
7525         if (instance->adapter_type != MFI_SERIES)
7526                 megasas_fusion_stop_watchdog(instance);
7527 fail_init_mfi:
7528         scsi_host_put(host);
7529 fail_alloc_instance:
7530         pci_disable_device(pdev);
7531
7532         return -ENODEV;
7533 }
7534
7535 /**
7536  * megasas_flush_cache -        Requests FW to flush all its caches
7537  * @instance:                   Adapter soft state
7538  */
7539 static void megasas_flush_cache(struct megasas_instance *instance)
7540 {
7541         struct megasas_cmd *cmd;
7542         struct megasas_dcmd_frame *dcmd;
7543
7544         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7545                 return;
7546
7547         cmd = megasas_get_cmd(instance);
7548
7549         if (!cmd)
7550                 return;
7551
7552         dcmd = &cmd->frame->dcmd;
7553
7554         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7555
7556         dcmd->cmd = MFI_CMD_DCMD;
7557         dcmd->cmd_status = 0x0;
7558         dcmd->sge_count = 0;
7559         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7560         dcmd->timeout = 0;
7561         dcmd->pad_0 = 0;
7562         dcmd->data_xfer_len = 0;
7563         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_CACHE_FLUSH);
7564         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
7565
7566         if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7567                         != DCMD_SUCCESS) {
7568                 dev_err(&instance->pdev->dev,
7569                         "return from %s %d\n", __func__, __LINE__);
7570                 return;
7571         }
7572
7573         megasas_return_cmd(instance, cmd);
7574 }
7575
7576 /**
7577  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
7578  * @instance:                           Adapter soft state
7579  * @opcode:                             Shutdown/Hibernate
7580  */
7581 static void megasas_shutdown_controller(struct megasas_instance *instance,
7582                                         u32 opcode)
7583 {
7584         struct megasas_cmd *cmd;
7585         struct megasas_dcmd_frame *dcmd;
7586
7587         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7588                 return;
7589
7590         cmd = megasas_get_cmd(instance);
7591
7592         if (!cmd)
7593                 return;
7594
7595         if (instance->aen_cmd)
7596                 megasas_issue_blocked_abort_cmd(instance,
7597                         instance->aen_cmd, MFI_IO_TIMEOUT_SECS);
7598         if (instance->map_update_cmd)
7599                 megasas_issue_blocked_abort_cmd(instance,
7600                         instance->map_update_cmd, MFI_IO_TIMEOUT_SECS);
7601         if (instance->jbod_seq_cmd)
7602                 megasas_issue_blocked_abort_cmd(instance,
7603                         instance->jbod_seq_cmd, MFI_IO_TIMEOUT_SECS);
7604
7605         dcmd = &cmd->frame->dcmd;
7606
7607         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7608
7609         dcmd->cmd = MFI_CMD_DCMD;
7610         dcmd->cmd_status = 0x0;
7611         dcmd->sge_count = 0;
7612         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7613         dcmd->timeout = 0;
7614         dcmd->pad_0 = 0;
7615         dcmd->data_xfer_len = 0;
7616         dcmd->opcode = cpu_to_le32(opcode);
7617
7618         if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7619                         != DCMD_SUCCESS) {
7620                 dev_err(&instance->pdev->dev,
7621                         "return from %s %d\n", __func__, __LINE__);
7622                 return;
7623         }
7624
7625         megasas_return_cmd(instance, cmd);
7626 }
7627
7628 #ifdef CONFIG_PM
7629 /**
7630  * megasas_suspend -    driver suspend entry point
7631  * @pdev:               PCI device structure
7632  * @state:              PCI power state to suspend routine
7633  */
7634 static int
7635 megasas_suspend(struct pci_dev *pdev, pm_message_t state)
7636 {
7637         struct megasas_instance *instance;
7638
7639         instance = pci_get_drvdata(pdev);
7640
7641         if (!instance)
7642                 return 0;
7643
7644         instance->unload = 1;
7645
7646         dev_info(&pdev->dev, "%s is called\n", __func__);
7647
7648         /* Shutdown SR-IOV heartbeat timer */
7649         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7650                 del_timer_sync(&instance->sriov_heartbeat_timer);
7651
7652         /* Stop the FW fault detection watchdog */
7653         if (instance->adapter_type != MFI_SERIES)
7654                 megasas_fusion_stop_watchdog(instance);
7655
7656         megasas_flush_cache(instance);
7657         megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
7658
7659         /* cancel the delayed work if this work still in queue */
7660         if (instance->ev != NULL) {
7661                 struct megasas_aen_event *ev = instance->ev;
7662                 cancel_delayed_work_sync(&ev->hotplug_work);
7663                 instance->ev = NULL;
7664         }
7665
7666         tasklet_kill(&instance->isr_tasklet);
7667
7668         pci_set_drvdata(instance->pdev, instance);
7669         instance->instancet->disable_intr(instance);
7670
7671         megasas_destroy_irqs(instance);
7672
7673         if (instance->msix_vectors)
7674                 pci_free_irq_vectors(instance->pdev);
7675
7676         pci_save_state(pdev);
7677         pci_disable_device(pdev);
7678
7679         pci_set_power_state(pdev, pci_choose_state(pdev, state));
7680
7681         return 0;
7682 }
7683
7684 /**
7685  * megasas_resume-      driver resume entry point
7686  * @pdev:               PCI device structure
7687  */
7688 static int
7689 megasas_resume(struct pci_dev *pdev)
7690 {
7691         int rval;
7692         struct Scsi_Host *host;
7693         struct megasas_instance *instance;
7694         u32 status_reg;
7695
7696         instance = pci_get_drvdata(pdev);
7697
7698         if (!instance)
7699                 return 0;
7700
7701         host = instance->host;
7702         pci_set_power_state(pdev, PCI_D0);
7703         pci_enable_wake(pdev, PCI_D0, 0);
7704         pci_restore_state(pdev);
7705
7706         dev_info(&pdev->dev, "%s is called\n", __func__);
7707         /*
7708          * PCI prepping: enable device set bus mastering and dma mask
7709          */
7710         rval = pci_enable_device_mem(pdev);
7711
7712         if (rval) {
7713                 dev_err(&pdev->dev, "Enable device failed\n");
7714                 return rval;
7715         }
7716
7717         pci_set_master(pdev);
7718
7719         /*
7720          * We expect the FW state to be READY
7721          */
7722
7723         if (megasas_transition_to_ready(instance, 0)) {
7724                 dev_info(&instance->pdev->dev,
7725                          "Failed to transition controller to ready from %s!\n",
7726                          __func__);
7727                 if (instance->adapter_type != MFI_SERIES) {
7728                         status_reg =
7729                                 instance->instancet->read_fw_status_reg(instance);
7730                         if (!(status_reg & MFI_RESET_ADAPTER) ||
7731                                 ((megasas_adp_reset_wait_for_ready
7732                                 (instance, true, 0)) == FAILED))
7733                                 goto fail_ready_state;
7734                 } else {
7735                         atomic_set(&instance->fw_reset_no_pci_access, 1);
7736                         instance->instancet->adp_reset
7737                                 (instance, instance->reg_set);
7738                         atomic_set(&instance->fw_reset_no_pci_access, 0);
7739
7740                         /* waiting for about 30 seconds before retry */
7741                         ssleep(30);
7742
7743                         if (megasas_transition_to_ready(instance, 0))
7744                                 goto fail_ready_state;
7745                 }
7746
7747                 dev_info(&instance->pdev->dev,
7748                          "FW restarted successfully from %s!\n",
7749                          __func__);
7750         }
7751         if (megasas_set_dma_mask(instance))
7752                 goto fail_set_dma_mask;
7753
7754         /*
7755          * Initialize MFI Firmware
7756          */
7757
7758         atomic_set(&instance->fw_outstanding, 0);
7759         atomic_set(&instance->ldio_outstanding, 0);
7760
7761         /* Now re-enable MSI-X */
7762         if (instance->msix_vectors)
7763                 megasas_alloc_irq_vectors(instance);
7764
7765         if (!instance->msix_vectors) {
7766                 rval = pci_alloc_irq_vectors(instance->pdev, 1, 1,
7767                                              PCI_IRQ_LEGACY);
7768                 if (rval < 0)
7769                         goto fail_reenable_msix;
7770         }
7771
7772         megasas_setup_reply_map(instance);
7773
7774         if (instance->adapter_type != MFI_SERIES) {
7775                 megasas_reset_reply_desc(instance);
7776                 if (megasas_ioc_init_fusion(instance)) {
7777                         megasas_free_cmds(instance);
7778                         megasas_free_cmds_fusion(instance);
7779                         goto fail_init_mfi;
7780                 }
7781                 if (!megasas_get_map_info(instance))
7782                         megasas_sync_map_info(instance);
7783         } else {
7784                 *instance->producer = 0;
7785                 *instance->consumer = 0;
7786                 if (megasas_issue_init_mfi(instance))
7787                         goto fail_init_mfi;
7788         }
7789
7790         if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS)
7791                 goto fail_init_mfi;
7792
7793         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
7794                      (unsigned long)instance);
7795
7796         if (instance->msix_vectors ?
7797                         megasas_setup_irqs_msix(instance, 0) :
7798                         megasas_setup_irqs_ioapic(instance))
7799                 goto fail_init_mfi;
7800
7801         if (instance->adapter_type != MFI_SERIES)
7802                 megasas_setup_irq_poll(instance);
7803
7804         /* Re-launch SR-IOV heartbeat timer */
7805         if (instance->requestorId) {
7806                 if (!megasas_sriov_start_heartbeat(instance, 0))
7807                         megasas_start_timer(instance);
7808                 else {
7809                         instance->skip_heartbeat_timer_del = 1;
7810                         goto fail_init_mfi;
7811                 }
7812         }
7813
7814         instance->instancet->enable_intr(instance);
7815         megasas_setup_jbod_map(instance);
7816         instance->unload = 0;
7817
7818         /*
7819          * Initiate AEN (Asynchronous Event Notification)
7820          */
7821         if (megasas_start_aen(instance))
7822                 dev_err(&instance->pdev->dev, "Start AEN failed\n");
7823
7824         /* Re-launch FW fault watchdog */
7825         if (instance->adapter_type != MFI_SERIES)
7826                 if (megasas_fusion_start_watchdog(instance) != SUCCESS)
7827                         goto fail_start_watchdog;
7828
7829         return 0;
7830
7831 fail_start_watchdog:
7832         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7833                 del_timer_sync(&instance->sriov_heartbeat_timer);
7834 fail_init_mfi:
7835         megasas_free_ctrl_dma_buffers(instance);
7836         megasas_free_ctrl_mem(instance);
7837         scsi_host_put(host);
7838
7839 fail_reenable_msix:
7840 fail_set_dma_mask:
7841 fail_ready_state:
7842
7843         pci_disable_device(pdev);
7844
7845         return -ENODEV;
7846 }
7847 #else
7848 #define megasas_suspend NULL
7849 #define megasas_resume  NULL
7850 #endif
7851
7852 static inline int
7853 megasas_wait_for_adapter_operational(struct megasas_instance *instance)
7854 {
7855         int wait_time = MEGASAS_RESET_WAIT_TIME * 2;
7856         int i;
7857         u8 adp_state;
7858
7859         for (i = 0; i < wait_time; i++) {
7860                 adp_state = atomic_read(&instance->adprecovery);
7861                 if ((adp_state == MEGASAS_HBA_OPERATIONAL) ||
7862                     (adp_state == MEGASAS_HW_CRITICAL_ERROR))
7863                         break;
7864
7865                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL))
7866                         dev_notice(&instance->pdev->dev, "waiting for controller reset to finish\n");
7867
7868                 msleep(1000);
7869         }
7870
7871         if (adp_state != MEGASAS_HBA_OPERATIONAL) {
7872                 dev_info(&instance->pdev->dev,
7873                          "%s HBA failed to become operational, adp_state %d\n",
7874                          __func__, adp_state);
7875                 return 1;
7876         }
7877
7878         return 0;
7879 }
7880
7881 /**
7882  * megasas_detach_one - PCI hot"un"plug entry point
7883  * @pdev:               PCI device structure
7884  */
7885 static void megasas_detach_one(struct pci_dev *pdev)
7886 {
7887         int i;
7888         struct Scsi_Host *host;
7889         struct megasas_instance *instance;
7890         struct fusion_context *fusion;
7891         u32 pd_seq_map_sz;
7892
7893         instance = pci_get_drvdata(pdev);
7894
7895         if (!instance)
7896                 return;
7897
7898         host = instance->host;
7899         fusion = instance->ctrl_context;
7900
7901         /* Shutdown SR-IOV heartbeat timer */
7902         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7903                 del_timer_sync(&instance->sriov_heartbeat_timer);
7904
7905         /* Stop the FW fault detection watchdog */
7906         if (instance->adapter_type != MFI_SERIES)
7907                 megasas_fusion_stop_watchdog(instance);
7908
7909         if (instance->fw_crash_state != UNAVAILABLE)
7910                 megasas_free_host_crash_buffer(instance);
7911         scsi_remove_host(instance->host);
7912         instance->unload = 1;
7913
7914         if (megasas_wait_for_adapter_operational(instance))
7915                 goto skip_firing_dcmds;
7916
7917         megasas_flush_cache(instance);
7918         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
7919
7920 skip_firing_dcmds:
7921         /* cancel the delayed work if this work still in queue*/
7922         if (instance->ev != NULL) {
7923                 struct megasas_aen_event *ev = instance->ev;
7924                 cancel_delayed_work_sync(&ev->hotplug_work);
7925                 instance->ev = NULL;
7926         }
7927
7928         /* cancel all wait events */
7929         wake_up_all(&instance->int_cmd_wait_q);
7930
7931         tasklet_kill(&instance->isr_tasklet);
7932
7933         /*
7934          * Take the instance off the instance array. Note that we will not
7935          * decrement the max_index. We let this array be sparse array
7936          */
7937         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
7938                 if (megasas_mgmt_info.instance[i] == instance) {
7939                         megasas_mgmt_info.count--;
7940                         megasas_mgmt_info.instance[i] = NULL;
7941
7942                         break;
7943                 }
7944         }
7945
7946         instance->instancet->disable_intr(instance);
7947
7948         megasas_destroy_irqs(instance);
7949
7950         if (instance->msix_vectors)
7951                 pci_free_irq_vectors(instance->pdev);
7952
7953         if (instance->adapter_type >= VENTURA_SERIES) {
7954                 for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i)
7955                         kfree(fusion->stream_detect_by_ld[i]);
7956                 kfree(fusion->stream_detect_by_ld);
7957                 fusion->stream_detect_by_ld = NULL;
7958         }
7959
7960
7961         if (instance->adapter_type != MFI_SERIES) {
7962                 megasas_release_fusion(instance);
7963                         pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) +
7964                                 (sizeof(struct MR_PD_CFG_SEQ) *
7965                                         (MAX_PHYSICAL_DEVICES - 1));
7966                 for (i = 0; i < 2 ; i++) {
7967                         if (fusion->ld_map[i])
7968                                 dma_free_coherent(&instance->pdev->dev,
7969                                                   fusion->max_map_sz,
7970                                                   fusion->ld_map[i],
7971                                                   fusion->ld_map_phys[i]);
7972                         if (fusion->ld_drv_map[i]) {
7973                                 if (is_vmalloc_addr(fusion->ld_drv_map[i]))
7974                                         vfree(fusion->ld_drv_map[i]);
7975                                 else
7976                                         free_pages((ulong)fusion->ld_drv_map[i],
7977                                                    fusion->drv_map_pages);
7978                         }
7979
7980                         if (fusion->pd_seq_sync[i])
7981                                 dma_free_coherent(&instance->pdev->dev,
7982                                         pd_seq_map_sz,
7983                                         fusion->pd_seq_sync[i],
7984                                         fusion->pd_seq_phys[i]);
7985                 }
7986         } else {
7987                 megasas_release_mfi(instance);
7988         }
7989
7990         if (instance->vf_affiliation)
7991                 dma_free_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) *
7992                                     sizeof(struct MR_LD_VF_AFFILIATION),
7993                                     instance->vf_affiliation,
7994                                     instance->vf_affiliation_h);
7995
7996         if (instance->vf_affiliation_111)
7997                 dma_free_coherent(&pdev->dev,
7998                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
7999                                     instance->vf_affiliation_111,
8000                                     instance->vf_affiliation_111_h);
8001
8002         if (instance->hb_host_mem)
8003                 dma_free_coherent(&pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM),
8004                                     instance->hb_host_mem,
8005                                     instance->hb_host_mem_h);
8006
8007         megasas_free_ctrl_dma_buffers(instance);
8008
8009         megasas_free_ctrl_mem(instance);
8010
8011         megasas_destroy_debugfs(instance);
8012
8013         scsi_host_put(host);
8014
8015         pci_disable_device(pdev);
8016 }
8017
8018 /**
8019  * megasas_shutdown -   Shutdown entry point
8020  * @pdev:               Generic device structure
8021  */
8022 static void megasas_shutdown(struct pci_dev *pdev)
8023 {
8024         struct megasas_instance *instance = pci_get_drvdata(pdev);
8025
8026         if (!instance)
8027                 return;
8028
8029         instance->unload = 1;
8030
8031         if (megasas_wait_for_adapter_operational(instance))
8032                 goto skip_firing_dcmds;
8033
8034         megasas_flush_cache(instance);
8035         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
8036
8037 skip_firing_dcmds:
8038         instance->instancet->disable_intr(instance);
8039         megasas_destroy_irqs(instance);
8040
8041         if (instance->msix_vectors)
8042                 pci_free_irq_vectors(instance->pdev);
8043 }
8044
8045 /*
8046  * megasas_mgmt_open -  char node "open" entry point
8047  * @inode:      char node inode
8048  * @filep:      char node file
8049  */
8050 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
8051 {
8052         /*
8053          * Allow only those users with admin rights
8054          */
8055         if (!capable(CAP_SYS_ADMIN))
8056                 return -EACCES;
8057
8058         return 0;
8059 }
8060
8061 /*
8062  * megasas_mgmt_fasync -        Async notifier registration from applications
8063  * @fd:         char node file descriptor number
8064  * @filep:      char node file
8065  * @mode:       notifier on/off
8066  *
8067  * This function adds the calling process to a driver global queue. When an
8068  * event occurs, SIGIO will be sent to all processes in this queue.
8069  */
8070 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
8071 {
8072         int rc;
8073
8074         mutex_lock(&megasas_async_queue_mutex);
8075
8076         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
8077
8078         mutex_unlock(&megasas_async_queue_mutex);
8079
8080         if (rc >= 0) {
8081                 /* For sanity check when we get ioctl */
8082                 filep->private_data = filep;
8083                 return 0;
8084         }
8085
8086         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
8087
8088         return rc;
8089 }
8090
8091 /*
8092  * megasas_mgmt_poll -  char node "poll" entry point
8093  * @filep:      char node file
8094  * @wait:       Events to poll for
8095  */
8096 static __poll_t megasas_mgmt_poll(struct file *file, poll_table *wait)
8097 {
8098         __poll_t mask;
8099         unsigned long flags;
8100
8101         poll_wait(file, &megasas_poll_wait, wait);
8102         spin_lock_irqsave(&poll_aen_lock, flags);
8103         if (megasas_poll_wait_aen)
8104                 mask = (EPOLLIN | EPOLLRDNORM);
8105         else
8106                 mask = 0;
8107         megasas_poll_wait_aen = 0;
8108         spin_unlock_irqrestore(&poll_aen_lock, flags);
8109         return mask;
8110 }
8111
8112 /*
8113  * megasas_set_crash_dump_params_ioctl:
8114  *              Send CRASH_DUMP_MODE DCMD to all controllers
8115  * @cmd:        MFI command frame
8116  */
8117
8118 static int megasas_set_crash_dump_params_ioctl(struct megasas_cmd *cmd)
8119 {
8120         struct megasas_instance *local_instance;
8121         int i, error = 0;
8122         int crash_support;
8123
8124         crash_support = cmd->frame->dcmd.mbox.w[0];
8125
8126         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
8127                 local_instance = megasas_mgmt_info.instance[i];
8128                 if (local_instance && local_instance->crash_dump_drv_support) {
8129                         if ((atomic_read(&local_instance->adprecovery) ==
8130                                 MEGASAS_HBA_OPERATIONAL) &&
8131                                 !megasas_set_crash_dump_params(local_instance,
8132                                         crash_support)) {
8133                                 local_instance->crash_dump_app_support =
8134                                         crash_support;
8135                                 dev_info(&local_instance->pdev->dev,
8136                                         "Application firmware crash "
8137                                         "dump mode set success\n");
8138                                 error = 0;
8139                         } else {
8140                                 dev_info(&local_instance->pdev->dev,
8141                                         "Application firmware crash "
8142                                         "dump mode set failed\n");
8143                                 error = -1;
8144                         }
8145                 }
8146         }
8147         return error;
8148 }
8149
8150 /**
8151  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
8152  * @instance:                   Adapter soft state
8153  * @user_ioc:                   User's ioctl packet
8154  * @ioc:                        ioctl packet
8155  */
8156 static int
8157 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
8158                       struct megasas_iocpacket __user * user_ioc,
8159                       struct megasas_iocpacket *ioc)
8160 {
8161         struct megasas_sge64 *kern_sge64 = NULL;
8162         struct megasas_sge32 *kern_sge32 = NULL;
8163         struct megasas_cmd *cmd;
8164         void *kbuff_arr[MAX_IOCTL_SGE];
8165         dma_addr_t buf_handle = 0;
8166         int error = 0, i;
8167         void *sense = NULL;
8168         dma_addr_t sense_handle;
8169         void *sense_ptr;
8170         u32 opcode = 0;
8171         int ret = DCMD_SUCCESS;
8172
8173         memset(kbuff_arr, 0, sizeof(kbuff_arr));
8174
8175         if (ioc->sge_count > MAX_IOCTL_SGE) {
8176                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "SGE count [%d] >  max limit [%d]\n",
8177                        ioc->sge_count, MAX_IOCTL_SGE);
8178                 return -EINVAL;
8179         }
8180
8181         if ((ioc->frame.hdr.cmd >= MFI_CMD_OP_COUNT) ||
8182             ((ioc->frame.hdr.cmd == MFI_CMD_NVME) &&
8183             !instance->support_nvme_passthru) ||
8184             ((ioc->frame.hdr.cmd == MFI_CMD_TOOLBOX) &&
8185             !instance->support_pci_lane_margining)) {
8186                 dev_err(&instance->pdev->dev,
8187                         "Received invalid ioctl command 0x%x\n",
8188                         ioc->frame.hdr.cmd);
8189                 return -ENOTSUPP;
8190         }
8191
8192         cmd = megasas_get_cmd(instance);
8193         if (!cmd) {
8194                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a cmd packet\n");
8195                 return -ENOMEM;
8196         }
8197
8198         /*
8199          * User's IOCTL packet has 2 frames (maximum). Copy those two
8200          * frames into our cmd's frames. cmd->frame's context will get
8201          * overwritten when we copy from user's frames. So set that value
8202          * alone separately
8203          */
8204         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
8205         cmd->frame->hdr.context = cpu_to_le32(cmd->index);
8206         cmd->frame->hdr.pad_0 = 0;
8207
8208         cmd->frame->hdr.flags &= (~MFI_FRAME_IEEE);
8209
8210         if (instance->consistent_mask_64bit)
8211                 cmd->frame->hdr.flags |= cpu_to_le16((MFI_FRAME_SGL64 |
8212                                        MFI_FRAME_SENSE64));
8213         else
8214                 cmd->frame->hdr.flags &= cpu_to_le16(~(MFI_FRAME_SGL64 |
8215                                                MFI_FRAME_SENSE64));
8216
8217         if (cmd->frame->hdr.cmd == MFI_CMD_DCMD)
8218                 opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
8219
8220         if (opcode == MR_DCMD_CTRL_SHUTDOWN) {
8221                 mutex_lock(&instance->reset_mutex);
8222                 if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS) {
8223                         megasas_return_cmd(instance, cmd);
8224                         mutex_unlock(&instance->reset_mutex);
8225                         return -1;
8226                 }
8227                 mutex_unlock(&instance->reset_mutex);
8228         }
8229
8230         if (opcode == MR_DRIVER_SET_APP_CRASHDUMP_MODE) {
8231                 error = megasas_set_crash_dump_params_ioctl(cmd);
8232                 megasas_return_cmd(instance, cmd);
8233                 return error;
8234         }
8235
8236         /*
8237          * The management interface between applications and the fw uses
8238          * MFI frames. E.g, RAID configuration changes, LD property changes
8239          * etc are accomplishes through different kinds of MFI frames. The
8240          * driver needs to care only about substituting user buffers with
8241          * kernel buffers in SGLs. The location of SGL is embedded in the
8242          * struct iocpacket itself.
8243          */
8244         if (instance->consistent_mask_64bit)
8245                 kern_sge64 = (struct megasas_sge64 *)
8246                         ((unsigned long)cmd->frame + ioc->sgl_off);
8247         else
8248                 kern_sge32 = (struct megasas_sge32 *)
8249                         ((unsigned long)cmd->frame + ioc->sgl_off);
8250
8251         /*
8252          * For each user buffer, create a mirror buffer and copy in
8253          */
8254         for (i = 0; i < ioc->sge_count; i++) {
8255                 if (!ioc->sgl[i].iov_len)
8256                         continue;
8257
8258                 kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
8259                                                     ioc->sgl[i].iov_len,
8260                                                     &buf_handle, GFP_KERNEL);
8261                 if (!kbuff_arr[i]) {
8262                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to alloc "
8263                                "kernel SGL buffer for IOCTL\n");
8264                         error = -ENOMEM;
8265                         goto out;
8266                 }
8267
8268                 /*
8269                  * We don't change the dma_coherent_mask, so
8270                  * dma_alloc_coherent only returns 32bit addresses
8271                  */
8272                 if (instance->consistent_mask_64bit) {
8273                         kern_sge64[i].phys_addr = cpu_to_le64(buf_handle);
8274                         kern_sge64[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
8275                 } else {
8276                         kern_sge32[i].phys_addr = cpu_to_le32(buf_handle);
8277                         kern_sge32[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
8278                 }
8279
8280                 /*
8281                  * We created a kernel buffer corresponding to the
8282                  * user buffer. Now copy in from the user buffer
8283                  */
8284                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
8285                                    (u32) (ioc->sgl[i].iov_len))) {
8286                         error = -EFAULT;
8287                         goto out;
8288                 }
8289         }
8290
8291         if (ioc->sense_len) {
8292                 /* make sure the pointer is part of the frame */
8293                 if (ioc->sense_off >
8294                     (sizeof(union megasas_frame) - sizeof(__le64))) {
8295                         error = -EINVAL;
8296                         goto out;
8297                 }
8298
8299                 sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
8300                                              &sense_handle, GFP_KERNEL);
8301                 if (!sense) {
8302                         error = -ENOMEM;
8303                         goto out;
8304                 }
8305
8306                 /* always store 64 bits regardless of addressing */
8307                 sense_ptr = (void *)cmd->frame + ioc->sense_off;
8308                 put_unaligned_le64(sense_handle, sense_ptr);
8309         }
8310
8311         /*
8312          * Set the sync_cmd flag so that the ISR knows not to complete this
8313          * cmd to the SCSI mid-layer
8314          */
8315         cmd->sync_cmd = 1;
8316
8317         ret = megasas_issue_blocked_cmd(instance, cmd, 0);
8318         switch (ret) {
8319         case DCMD_INIT:
8320         case DCMD_BUSY:
8321                 cmd->sync_cmd = 0;
8322                 dev_err(&instance->pdev->dev,
8323                         "return -EBUSY from %s %d cmd 0x%x opcode 0x%x cmd->cmd_status_drv 0x%x\n",
8324                          __func__, __LINE__, cmd->frame->hdr.cmd, opcode,
8325                          cmd->cmd_status_drv);
8326                 error = -EBUSY;
8327                 goto out;
8328         }
8329
8330         cmd->sync_cmd = 0;
8331
8332         if (instance->unload == 1) {
8333                 dev_info(&instance->pdev->dev, "Driver unload is in progress "
8334                         "don't submit data to application\n");
8335                 goto out;
8336         }
8337         /*
8338          * copy out the kernel buffers to user buffers
8339          */
8340         for (i = 0; i < ioc->sge_count; i++) {
8341                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
8342                                  ioc->sgl[i].iov_len)) {
8343                         error = -EFAULT;
8344                         goto out;
8345                 }
8346         }
8347
8348         /*
8349          * copy out the sense
8350          */
8351         if (ioc->sense_len) {
8352                 /*
8353                  * sense_ptr points to the location that has the user
8354                  * sense buffer address
8355                  */
8356                 sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
8357                                 ioc->sense_off);
8358
8359                 if (copy_to_user((void __user *)((unsigned long)
8360                                  get_unaligned((unsigned long *)sense_ptr)),
8361                                  sense, ioc->sense_len)) {
8362                         dev_err(&instance->pdev->dev, "Failed to copy out to user "
8363                                         "sense data\n");
8364                         error = -EFAULT;
8365                         goto out;
8366                 }
8367         }
8368
8369         /*
8370          * copy the status codes returned by the fw
8371          */
8372         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
8373                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
8374                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error copying out cmd_status\n");
8375                 error = -EFAULT;
8376         }
8377
8378 out:
8379         if (sense) {
8380                 dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
8381                                     sense, sense_handle);
8382         }
8383
8384         for (i = 0; i < ioc->sge_count; i++) {
8385                 if (kbuff_arr[i]) {
8386                         if (instance->consistent_mask_64bit)
8387                                 dma_free_coherent(&instance->pdev->dev,
8388                                         le32_to_cpu(kern_sge64[i].length),
8389                                         kbuff_arr[i],
8390                                         le64_to_cpu(kern_sge64[i].phys_addr));
8391                         else
8392                                 dma_free_coherent(&instance->pdev->dev,
8393                                         le32_to_cpu(kern_sge32[i].length),
8394                                         kbuff_arr[i],
8395                                         le32_to_cpu(kern_sge32[i].phys_addr));
8396                         kbuff_arr[i] = NULL;
8397                 }
8398         }
8399
8400         megasas_return_cmd(instance, cmd);
8401         return error;
8402 }
8403
8404 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
8405 {
8406         struct megasas_iocpacket __user *user_ioc =
8407             (struct megasas_iocpacket __user *)arg;
8408         struct megasas_iocpacket *ioc;
8409         struct megasas_instance *instance;
8410         int error;
8411
8412         ioc = memdup_user(user_ioc, sizeof(*ioc));
8413         if (IS_ERR(ioc))
8414                 return PTR_ERR(ioc);
8415
8416         instance = megasas_lookup_instance(ioc->host_no);
8417         if (!instance) {
8418                 error = -ENODEV;
8419                 goto out_kfree_ioc;
8420         }
8421
8422         /* Block ioctls in VF mode */
8423         if (instance->requestorId && !allow_vf_ioctls) {
8424                 error = -ENODEV;
8425                 goto out_kfree_ioc;
8426         }
8427
8428         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8429                 dev_err(&instance->pdev->dev, "Controller in crit error\n");
8430                 error = -ENODEV;
8431                 goto out_kfree_ioc;
8432         }
8433
8434         if (instance->unload == 1) {
8435                 error = -ENODEV;
8436                 goto out_kfree_ioc;
8437         }
8438
8439         if (down_interruptible(&instance->ioctl_sem)) {
8440                 error = -ERESTARTSYS;
8441                 goto out_kfree_ioc;
8442         }
8443
8444         if  (megasas_wait_for_adapter_operational(instance)) {
8445                 error = -ENODEV;
8446                 goto out_up;
8447         }
8448
8449         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
8450 out_up:
8451         up(&instance->ioctl_sem);
8452
8453 out_kfree_ioc:
8454         kfree(ioc);
8455         return error;
8456 }
8457
8458 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
8459 {
8460         struct megasas_instance *instance;
8461         struct megasas_aen aen;
8462         int error;
8463
8464         if (file->private_data != file) {
8465                 printk(KERN_DEBUG "megasas: fasync_helper was not "
8466                        "called first\n");
8467                 return -EINVAL;
8468         }
8469
8470         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
8471                 return -EFAULT;
8472
8473         instance = megasas_lookup_instance(aen.host_no);
8474
8475         if (!instance)
8476                 return -ENODEV;
8477
8478         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8479                 return -ENODEV;
8480         }
8481
8482         if (instance->unload == 1) {
8483                 return -ENODEV;
8484         }
8485
8486         if  (megasas_wait_for_adapter_operational(instance))
8487                 return -ENODEV;
8488
8489         mutex_lock(&instance->reset_mutex);
8490         error = megasas_register_aen(instance, aen.seq_num,
8491                                      aen.class_locale_word);
8492         mutex_unlock(&instance->reset_mutex);
8493         return error;
8494 }
8495
8496 /**
8497  * megasas_mgmt_ioctl - char node ioctl entry point
8498  * @file:       char device file pointer
8499  * @cmd:        ioctl command
8500  * @arg:        ioctl command arguments address
8501  */
8502 static long
8503 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
8504 {
8505         switch (cmd) {
8506         case MEGASAS_IOC_FIRMWARE:
8507                 return megasas_mgmt_ioctl_fw(file, arg);
8508
8509         case MEGASAS_IOC_GET_AEN:
8510                 return megasas_mgmt_ioctl_aen(file, arg);
8511         }
8512
8513         return -ENOTTY;
8514 }
8515
8516 #ifdef CONFIG_COMPAT
8517 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
8518 {
8519         struct compat_megasas_iocpacket __user *cioc =
8520             (struct compat_megasas_iocpacket __user *)arg;
8521         struct megasas_iocpacket __user *ioc =
8522             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
8523         int i;
8524         int error = 0;
8525         compat_uptr_t ptr;
8526         u32 local_sense_off;
8527         u32 local_sense_len;
8528         u32 user_sense_off;
8529
8530         if (clear_user(ioc, sizeof(*ioc)))
8531                 return -EFAULT;
8532
8533         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
8534             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
8535             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
8536             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
8537             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
8538             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
8539                 return -EFAULT;
8540
8541         /*
8542          * The sense_ptr is used in megasas_mgmt_fw_ioctl only when
8543          * sense_len is not null, so prepare the 64bit value under
8544          * the same condition.
8545          */
8546         if (get_user(local_sense_off, &ioc->sense_off) ||
8547                 get_user(local_sense_len, &ioc->sense_len) ||
8548                 get_user(user_sense_off, &cioc->sense_off))
8549                 return -EFAULT;
8550
8551         if (local_sense_off != user_sense_off)
8552                 return -EINVAL;
8553
8554         if (local_sense_len) {
8555                 void __user **sense_ioc_ptr =
8556                         (void __user **)((u8 *)((unsigned long)&ioc->frame.raw) + local_sense_off);
8557                 compat_uptr_t *sense_cioc_ptr =
8558                         (compat_uptr_t *)(((unsigned long)&cioc->frame.raw) + user_sense_off);
8559                 if (get_user(ptr, sense_cioc_ptr) ||
8560                     put_user(compat_ptr(ptr), sense_ioc_ptr))
8561                         return -EFAULT;
8562         }
8563
8564         for (i = 0; i < MAX_IOCTL_SGE; i++) {
8565                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
8566                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
8567                     copy_in_user(&ioc->sgl[i].iov_len,
8568                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
8569                         return -EFAULT;
8570         }
8571
8572         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
8573
8574         if (copy_in_user(&cioc->frame.hdr.cmd_status,
8575                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
8576                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
8577                 return -EFAULT;
8578         }
8579         return error;
8580 }
8581
8582 static long
8583 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
8584                           unsigned long arg)
8585 {
8586         switch (cmd) {
8587         case MEGASAS_IOC_FIRMWARE32:
8588                 return megasas_mgmt_compat_ioctl_fw(file, arg);
8589         case MEGASAS_IOC_GET_AEN:
8590                 return megasas_mgmt_ioctl_aen(file, arg);
8591         }
8592
8593         return -ENOTTY;
8594 }
8595 #endif
8596
8597 /*
8598  * File operations structure for management interface
8599  */
8600 static const struct file_operations megasas_mgmt_fops = {
8601         .owner = THIS_MODULE,
8602         .open = megasas_mgmt_open,
8603         .fasync = megasas_mgmt_fasync,
8604         .unlocked_ioctl = megasas_mgmt_ioctl,
8605         .poll = megasas_mgmt_poll,
8606 #ifdef CONFIG_COMPAT
8607         .compat_ioctl = megasas_mgmt_compat_ioctl,
8608 #endif
8609         .llseek = noop_llseek,
8610 };
8611
8612 /*
8613  * PCI hotplug support registration structure
8614  */
8615 static struct pci_driver megasas_pci_driver = {
8616
8617         .name = "megaraid_sas",
8618         .id_table = megasas_pci_table,
8619         .probe = megasas_probe_one,
8620         .remove = megasas_detach_one,
8621         .suspend = megasas_suspend,
8622         .resume = megasas_resume,
8623         .shutdown = megasas_shutdown,
8624 };
8625
8626 /*
8627  * Sysfs driver attributes
8628  */
8629 static ssize_t version_show(struct device_driver *dd, char *buf)
8630 {
8631         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
8632                         MEGASAS_VERSION);
8633 }
8634 static DRIVER_ATTR_RO(version);
8635
8636 static ssize_t release_date_show(struct device_driver *dd, char *buf)
8637 {
8638         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
8639                 MEGASAS_RELDATE);
8640 }
8641 static DRIVER_ATTR_RO(release_date);
8642
8643 static ssize_t support_poll_for_event_show(struct device_driver *dd, char *buf)
8644 {
8645         return sprintf(buf, "%u\n", support_poll_for_event);
8646 }
8647 static DRIVER_ATTR_RO(support_poll_for_event);
8648
8649 static ssize_t support_device_change_show(struct device_driver *dd, char *buf)
8650 {
8651         return sprintf(buf, "%u\n", support_device_change);
8652 }
8653 static DRIVER_ATTR_RO(support_device_change);
8654
8655 static ssize_t dbg_lvl_show(struct device_driver *dd, char *buf)
8656 {
8657         return sprintf(buf, "%u\n", megasas_dbg_lvl);
8658 }
8659
8660 static ssize_t dbg_lvl_store(struct device_driver *dd, const char *buf,
8661                              size_t count)
8662 {
8663         int retval = count;
8664
8665         if (sscanf(buf, "%u", &megasas_dbg_lvl) < 1) {
8666                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
8667                 retval = -EINVAL;
8668         }
8669         return retval;
8670 }
8671 static DRIVER_ATTR_RW(dbg_lvl);
8672
8673 static ssize_t
8674 support_nvme_encapsulation_show(struct device_driver *dd, char *buf)
8675 {
8676         return sprintf(buf, "%u\n", support_nvme_encapsulation);
8677 }
8678
8679 static DRIVER_ATTR_RO(support_nvme_encapsulation);
8680
8681 static ssize_t
8682 support_pci_lane_margining_show(struct device_driver *dd, char *buf)
8683 {
8684         return sprintf(buf, "%u\n", support_pci_lane_margining);
8685 }
8686
8687 static DRIVER_ATTR_RO(support_pci_lane_margining);
8688
8689 static inline void megasas_remove_scsi_device(struct scsi_device *sdev)
8690 {
8691         sdev_printk(KERN_INFO, sdev, "SCSI device is removed\n");
8692         scsi_remove_device(sdev);
8693         scsi_device_put(sdev);
8694 }
8695
8696 /**
8697  * megasas_update_device_list - Update the PD and LD device list from FW
8698  *                              after an AEN event notification
8699  * @instance:                   Adapter soft state
8700  * @event_type:                 Indicates type of event (PD or LD event)
8701  *
8702  * @return:                     Success or failure
8703  *
8704  * Issue DCMDs to Firmware to update the internal device list in driver.
8705  * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
8706  * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
8707  */
8708 static
8709 int megasas_update_device_list(struct megasas_instance *instance,
8710                                int event_type)
8711 {
8712         int dcmd_ret = DCMD_SUCCESS;
8713
8714         if (instance->enable_fw_dev_list) {
8715                 dcmd_ret = megasas_host_device_list_query(instance, false);
8716                 if (dcmd_ret != DCMD_SUCCESS)
8717                         goto out;
8718         } else {
8719                 if (event_type & SCAN_PD_CHANNEL) {
8720                         dcmd_ret = megasas_get_pd_list(instance);
8721
8722                         if (dcmd_ret != DCMD_SUCCESS)
8723                                 goto out;
8724                 }
8725
8726                 if (event_type & SCAN_VD_CHANNEL) {
8727                         if (!instance->requestorId ||
8728                             (instance->requestorId &&
8729                              megasas_get_ld_vf_affiliation(instance, 0))) {
8730                                 dcmd_ret = megasas_ld_list_query(instance,
8731                                                 MR_LD_QUERY_TYPE_EXPOSED_TO_HOST);
8732                                 if (dcmd_ret != DCMD_SUCCESS)
8733                                         goto out;
8734                         }
8735                 }
8736         }
8737
8738 out:
8739         return dcmd_ret;
8740 }
8741
8742 /**
8743  * megasas_add_remove_devices - Add/remove devices to SCSI mid-layer
8744  *                              after an AEN event notification
8745  * @instance:                   Adapter soft state
8746  * @scan_type:                  Indicates type of devices (PD/LD) to add
8747  * @return                      void
8748  */
8749 static
8750 void megasas_add_remove_devices(struct megasas_instance *instance,
8751                                 int scan_type)
8752 {
8753         int i, j;
8754         u16 pd_index = 0;
8755         u16 ld_index = 0;
8756         u16 channel = 0, id = 0;
8757         struct Scsi_Host *host;
8758         struct scsi_device *sdev1;
8759         struct MR_HOST_DEVICE_LIST *targetid_list = NULL;
8760         struct MR_HOST_DEVICE_LIST_ENTRY *targetid_entry = NULL;
8761
8762         host = instance->host;
8763
8764         if (instance->enable_fw_dev_list) {
8765                 targetid_list = instance->host_device_list_buf;
8766                 for (i = 0; i < targetid_list->count; i++) {
8767                         targetid_entry = &targetid_list->host_device_list[i];
8768                         if (targetid_entry->flags.u.bits.is_sys_pd) {
8769                                 channel = le16_to_cpu(targetid_entry->target_id) /
8770                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8771                                 id = le16_to_cpu(targetid_entry->target_id) %
8772                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8773                         } else {
8774                                 channel = MEGASAS_MAX_PD_CHANNELS +
8775                                           (le16_to_cpu(targetid_entry->target_id) /
8776                                            MEGASAS_MAX_DEV_PER_CHANNEL);
8777                                 id = le16_to_cpu(targetid_entry->target_id) %
8778                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8779                         }
8780                         sdev1 = scsi_device_lookup(host, channel, id, 0);
8781                         if (!sdev1) {
8782                                 scsi_add_device(host, channel, id, 0);
8783                         } else {
8784                                 scsi_device_put(sdev1);
8785                         }
8786                 }
8787         }
8788
8789         if (scan_type & SCAN_PD_CHANNEL) {
8790                 for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
8791                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8792                                 pd_index = i * MEGASAS_MAX_DEV_PER_CHANNEL + j;
8793                                 sdev1 = scsi_device_lookup(host, i, j, 0);
8794                                 if (instance->pd_list[pd_index].driveState ==
8795                                                         MR_PD_STATE_SYSTEM) {
8796                                         if (!sdev1)
8797                                                 scsi_add_device(host, i, j, 0);
8798                                         else
8799                                                 scsi_device_put(sdev1);
8800                                 } else {
8801                                         if (sdev1)
8802                                                 megasas_remove_scsi_device(sdev1);
8803                                 }
8804                         }
8805                 }
8806         }
8807
8808         if (scan_type & SCAN_VD_CHANNEL) {
8809                 for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
8810                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8811                                 ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
8812                                 sdev1 = scsi_device_lookup(host,
8813                                                 MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8814                                 if (instance->ld_ids[ld_index] != 0xff) {
8815                                         if (!sdev1)
8816                                                 scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8817                                         else
8818                                                 scsi_device_put(sdev1);
8819                                 } else {
8820                                         if (sdev1)
8821                                                 megasas_remove_scsi_device(sdev1);
8822                                 }
8823                         }
8824                 }
8825         }
8826
8827 }
8828
8829 static void
8830 megasas_aen_polling(struct work_struct *work)
8831 {
8832         struct megasas_aen_event *ev =
8833                 container_of(work, struct megasas_aen_event, hotplug_work.work);
8834         struct megasas_instance *instance = ev->instance;
8835         union megasas_evt_class_locale class_locale;
8836         int event_type = 0;
8837         u32 seq_num;
8838         u16 ld_target_id;
8839         int error;
8840         u8  dcmd_ret = DCMD_SUCCESS;
8841         struct scsi_device *sdev1;
8842
8843         if (!instance) {
8844                 printk(KERN_ERR "invalid instance!\n");
8845                 kfree(ev);
8846                 return;
8847         }
8848
8849         /* Don't run the event workqueue thread if OCR is running */
8850         mutex_lock(&instance->reset_mutex);
8851
8852         instance->ev = NULL;
8853         if (instance->evt_detail) {
8854                 megasas_decode_evt(instance);
8855
8856                 switch (le32_to_cpu(instance->evt_detail->code)) {
8857
8858                 case MR_EVT_PD_INSERTED:
8859                 case MR_EVT_PD_REMOVED:
8860                         event_type = SCAN_PD_CHANNEL;
8861                         break;
8862
8863                 case MR_EVT_LD_OFFLINE:
8864                 case MR_EVT_LD_DELETED:
8865                         ld_target_id = instance->evt_detail->args.ld.target_id;
8866                         sdev1 = scsi_device_lookup(instance->host,
8867                                                    MEGASAS_MAX_PD_CHANNELS +
8868                                                    (ld_target_id / MEGASAS_MAX_DEV_PER_CHANNEL),
8869                                                    (ld_target_id - MEGASAS_MAX_DEV_PER_CHANNEL),
8870                                                    0);
8871                         if (sdev1)
8872                                 megasas_remove_scsi_device(sdev1);
8873
8874                         event_type = SCAN_VD_CHANNEL;
8875                         break;
8876                 case MR_EVT_LD_CREATED:
8877                         event_type = SCAN_VD_CHANNEL;
8878                         break;
8879
8880                 case MR_EVT_CFG_CLEARED:
8881                 case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
8882                 case MR_EVT_FOREIGN_CFG_IMPORTED:
8883                 case MR_EVT_LD_STATE_CHANGE:
8884                         event_type = SCAN_PD_CHANNEL | SCAN_VD_CHANNEL;
8885                         dev_info(&instance->pdev->dev, "scanning for scsi%d...\n",
8886                                 instance->host->host_no);
8887                         break;
8888
8889                 case MR_EVT_CTRL_PROP_CHANGED:
8890                         dcmd_ret = megasas_get_ctrl_info(instance);
8891                         if (dcmd_ret == DCMD_SUCCESS &&
8892                             instance->snapdump_wait_time) {
8893                                 megasas_get_snapdump_properties(instance);
8894                                 dev_info(&instance->pdev->dev,
8895                                          "Snap dump wait time\t: %d\n",
8896                                          instance->snapdump_wait_time);
8897                         }
8898                         break;
8899                 default:
8900                         event_type = 0;
8901                         break;
8902                 }
8903         } else {
8904                 dev_err(&instance->pdev->dev, "invalid evt_detail!\n");
8905                 mutex_unlock(&instance->reset_mutex);
8906                 kfree(ev);
8907                 return;
8908         }
8909
8910         if (event_type)
8911                 dcmd_ret = megasas_update_device_list(instance, event_type);
8912
8913         mutex_unlock(&instance->reset_mutex);
8914
8915         if (event_type && dcmd_ret == DCMD_SUCCESS)
8916                 megasas_add_remove_devices(instance, event_type);
8917
8918         if (dcmd_ret == DCMD_SUCCESS)
8919                 seq_num = le32_to_cpu(instance->evt_detail->seq_num) + 1;
8920         else
8921                 seq_num = instance->last_seq_num;
8922
8923         /* Register AEN with FW for latest sequence number plus 1 */
8924         class_locale.members.reserved = 0;
8925         class_locale.members.locale = MR_EVT_LOCALE_ALL;
8926         class_locale.members.class = MR_EVT_CLASS_DEBUG;
8927
8928         if (instance->aen_cmd != NULL) {
8929                 kfree(ev);
8930                 return;
8931         }
8932
8933         mutex_lock(&instance->reset_mutex);
8934         error = megasas_register_aen(instance, seq_num,
8935                                         class_locale.word);
8936         if (error)
8937                 dev_err(&instance->pdev->dev,
8938                         "register aen failed error %x\n", error);
8939
8940         mutex_unlock(&instance->reset_mutex);
8941         kfree(ev);
8942 }
8943
8944 /**
8945  * megasas_init - Driver load entry point
8946  */
8947 static int __init megasas_init(void)
8948 {
8949         int rval;
8950
8951         /*
8952          * Booted in kdump kernel, minimize memory footprints by
8953          * disabling few features
8954          */
8955         if (reset_devices) {
8956                 msix_vectors = 1;
8957                 rdpq_enable = 0;
8958                 dual_qdepth_disable = 1;
8959         }
8960
8961         /*
8962          * Announce driver version and other information
8963          */
8964         pr_info("megasas: %s\n", MEGASAS_VERSION);
8965
8966         spin_lock_init(&poll_aen_lock);
8967
8968         support_poll_for_event = 2;
8969         support_device_change = 1;
8970         support_nvme_encapsulation = true;
8971         support_pci_lane_margining = true;
8972
8973         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
8974
8975         /*
8976          * Register character device node
8977          */
8978         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
8979
8980         if (rval < 0) {
8981                 printk(KERN_DEBUG "megasas: failed to open device node\n");
8982                 return rval;
8983         }
8984
8985         megasas_mgmt_majorno = rval;
8986
8987         megasas_init_debugfs();
8988
8989         /*
8990          * Register ourselves as PCI hotplug module
8991          */
8992         rval = pci_register_driver(&megasas_pci_driver);
8993
8994         if (rval) {
8995                 printk(KERN_DEBUG "megasas: PCI hotplug registration failed \n");
8996                 goto err_pcidrv;
8997         }
8998
8999         if ((event_log_level < MFI_EVT_CLASS_DEBUG) ||
9000             (event_log_level > MFI_EVT_CLASS_DEAD)) {
9001                 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");
9002                 event_log_level = MFI_EVT_CLASS_CRITICAL;
9003         }
9004
9005         rval = driver_create_file(&megasas_pci_driver.driver,
9006                                   &driver_attr_version);
9007         if (rval)
9008                 goto err_dcf_attr_ver;
9009
9010         rval = driver_create_file(&megasas_pci_driver.driver,
9011                                   &driver_attr_release_date);
9012         if (rval)
9013                 goto err_dcf_rel_date;
9014
9015         rval = driver_create_file(&megasas_pci_driver.driver,
9016                                 &driver_attr_support_poll_for_event);
9017         if (rval)
9018                 goto err_dcf_support_poll_for_event;
9019
9020         rval = driver_create_file(&megasas_pci_driver.driver,
9021                                   &driver_attr_dbg_lvl);
9022         if (rval)
9023                 goto err_dcf_dbg_lvl;
9024         rval = driver_create_file(&megasas_pci_driver.driver,
9025                                 &driver_attr_support_device_change);
9026         if (rval)
9027                 goto err_dcf_support_device_change;
9028
9029         rval = driver_create_file(&megasas_pci_driver.driver,
9030                                   &driver_attr_support_nvme_encapsulation);
9031         if (rval)
9032                 goto err_dcf_support_nvme_encapsulation;
9033
9034         rval = driver_create_file(&megasas_pci_driver.driver,
9035                                   &driver_attr_support_pci_lane_margining);
9036         if (rval)
9037                 goto err_dcf_support_pci_lane_margining;
9038
9039         return rval;
9040
9041 err_dcf_support_pci_lane_margining:
9042         driver_remove_file(&megasas_pci_driver.driver,
9043                            &driver_attr_support_nvme_encapsulation);
9044
9045 err_dcf_support_nvme_encapsulation:
9046         driver_remove_file(&megasas_pci_driver.driver,
9047                            &driver_attr_support_device_change);
9048
9049 err_dcf_support_device_change:
9050         driver_remove_file(&megasas_pci_driver.driver,
9051                            &driver_attr_dbg_lvl);
9052 err_dcf_dbg_lvl:
9053         driver_remove_file(&megasas_pci_driver.driver,
9054                         &driver_attr_support_poll_for_event);
9055 err_dcf_support_poll_for_event:
9056         driver_remove_file(&megasas_pci_driver.driver,
9057                            &driver_attr_release_date);
9058 err_dcf_rel_date:
9059         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
9060 err_dcf_attr_ver:
9061         pci_unregister_driver(&megasas_pci_driver);
9062 err_pcidrv:
9063         megasas_exit_debugfs();
9064         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
9065         return rval;
9066 }
9067
9068 /**
9069  * megasas_exit - Driver unload entry point
9070  */
9071 static void __exit megasas_exit(void)
9072 {
9073         driver_remove_file(&megasas_pci_driver.driver,
9074                            &driver_attr_dbg_lvl);
9075         driver_remove_file(&megasas_pci_driver.driver,
9076                         &driver_attr_support_poll_for_event);
9077         driver_remove_file(&megasas_pci_driver.driver,
9078                         &driver_attr_support_device_change);
9079         driver_remove_file(&megasas_pci_driver.driver,
9080                            &driver_attr_release_date);
9081         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
9082         driver_remove_file(&megasas_pci_driver.driver,
9083                            &driver_attr_support_nvme_encapsulation);
9084         driver_remove_file(&megasas_pci_driver.driver,
9085                            &driver_attr_support_pci_lane_margining);
9086
9087         pci_unregister_driver(&megasas_pci_driver);
9088         megasas_exit_debugfs();
9089         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
9090 }
9091
9092 module_init(megasas_init);
9093 module_exit(megasas_exit);