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