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