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