1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Linux MegaRAID driver for SAS based RAID controllers
4  *
5  *  Copyright (c) 2009-2013  LSI Corporation
6  *  Copyright (c) 2013-2016  Avago Technologies
7  *  Copyright (c) 2016-2018  Broadcom Inc.
8  *
9  *  FILE: megaraid_sas_fusion.c
10  *
11  *  Authors: Broadcom Inc.
12  *           Sumant Patro
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/uaccess.h>
31 #include <linux/fs.h>
32 #include <linux/compat.h>
33 #include <linux/blkdev.h>
34 #include <linux/mutex.h>
35 #include <linux/poll.h>
36 #include <linux/vmalloc.h>
37 #include <linux/workqueue.h>
38 #include <linux/irq_poll.h>
39 
40 #include <scsi/scsi.h>
41 #include <scsi/scsi_cmnd.h>
42 #include <scsi/scsi_device.h>
43 #include <scsi/scsi_host.h>
44 #include <scsi/scsi_dbg.h>
45 #include <linux/dmi.h>
46 
47 #include "megaraid_sas_fusion.h"
48 #include "megaraid_sas.h"
49 
50 
51 extern void megasas_free_cmds(struct megasas_instance *instance);
52 extern struct megasas_cmd *megasas_get_cmd(struct megasas_instance
53 					   *instance);
54 extern void
55 megasas_complete_cmd(struct megasas_instance *instance,
56 		     struct megasas_cmd *cmd, u8 alt_status);
57 int
58 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
59 	      int seconds);
60 
61 void
62 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd);
63 int megasas_alloc_cmds(struct megasas_instance *instance);
64 int
65 megasas_clear_intr_fusion(struct megasas_instance *instance);
66 int
67 megasas_issue_polled(struct megasas_instance *instance,
68 		     struct megasas_cmd *cmd);
69 void
70 megasas_check_and_restore_queue_depth(struct megasas_instance *instance);
71 
72 int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
73 void megaraid_sas_kill_hba(struct megasas_instance *instance);
74 
75 extern u32 megasas_dbg_lvl;
76 int megasas_sriov_start_heartbeat(struct megasas_instance *instance,
77 				  int initial);
78 void megasas_start_timer(struct megasas_instance *instance);
79 extern struct megasas_mgmt_info megasas_mgmt_info;
80 extern unsigned int resetwaittime;
81 extern unsigned int dual_qdepth_disable;
82 static void megasas_free_rdpq_fusion(struct megasas_instance *instance);
83 static void megasas_free_reply_fusion(struct megasas_instance *instance);
84 static inline
85 void megasas_configure_queue_sizes(struct megasas_instance *instance);
86 static void megasas_fusion_crash_dump(struct megasas_instance *instance);
87 extern u32 megasas_readl(struct megasas_instance *instance,
88 			 const volatile void __iomem *addr);
89 
90 /**
91  * megasas_adp_reset_wait_for_ready -	initiate chip reset and wait for
92  *					controller to come to ready state
93  * @instance -				adapter's soft state
94  * @do_adp_reset -			If true, do a chip reset
95  * @ocr_context -			If called from OCR context this will
96  *					be set to 1, else 0
97  *
98  * This function initates a chip reset followed by a wait for controller to
99  * transition to ready state.
100  * During this, driver will block all access to PCI config space from userspace
101  */
102 int
103 megasas_adp_reset_wait_for_ready(struct megasas_instance *instance,
104 				 bool do_adp_reset,
105 				 int ocr_context)
106 {
107 	int ret = FAILED;
108 
109 	/*
110 	 * Block access to PCI config space from userspace
111 	 * when diag reset is initiated from driver
112 	 */
113 	if (megasas_dbg_lvl & OCR_DEBUG)
114 		dev_info(&instance->pdev->dev,
115 			 "Block access to PCI config space %s %d\n",
116 			 __func__, __LINE__);
117 
118 	pci_cfg_access_lock(instance->pdev);
119 
120 	if (do_adp_reset) {
121 		if (instance->instancet->adp_reset
122 			(instance, instance->reg_set))
123 			goto out;
124 	}
125 
126 	/* Wait for FW to become ready */
127 	if (megasas_transition_to_ready(instance, ocr_context)) {
128 		dev_warn(&instance->pdev->dev,
129 			 "Failed to transition controller to ready for scsi%d.\n",
130 			 instance->host->host_no);
131 		goto out;
132 	}
133 
134 	ret = SUCCESS;
135 out:
136 	if (megasas_dbg_lvl & OCR_DEBUG)
137 		dev_info(&instance->pdev->dev,
138 			 "Unlock access to PCI config space %s %d\n",
139 			 __func__, __LINE__);
140 
141 	pci_cfg_access_unlock(instance->pdev);
142 
143 	return ret;
144 }
145 
146 /**
147  * megasas_check_same_4gb_region -	check if allocation
148  *					crosses same 4GB boundary or not
149  * @instance -				adapter's soft instance
150  * start_addr -			start address of DMA allocation
151  * size -				size of allocation in bytes
152  * return -				true : allocation does not cross same
153  *					4GB boundary
154  *					false: allocation crosses same
155  *					4GB boundary
156  */
157 static inline bool megasas_check_same_4gb_region
158 	(struct megasas_instance *instance, dma_addr_t start_addr, size_t size)
159 {
160 	dma_addr_t end_addr;
161 
162 	end_addr = start_addr + size;
163 
164 	if (upper_32_bits(start_addr) != upper_32_bits(end_addr)) {
165 		dev_err(&instance->pdev->dev,
166 			"Failed to get same 4GB boundary: start_addr: 0x%llx end_addr: 0x%llx\n",
167 			(unsigned long long)start_addr,
168 			(unsigned long long)end_addr);
169 		return false;
170 	}
171 
172 	return true;
173 }
174 
175 /**
176  * megasas_enable_intr_fusion -	Enables interrupts
177  * @regs:			MFI register set
178  */
179 void
180 megasas_enable_intr_fusion(struct megasas_instance *instance)
181 {
182 	struct megasas_register_set __iomem *regs;
183 	regs = instance->reg_set;
184 
185 	instance->mask_interrupts = 0;
186 	/* For Thunderbolt/Invader also clear intr on enable */
187 	writel(~0, &regs->outbound_intr_status);
188 	readl(&regs->outbound_intr_status);
189 
190 	writel(~MFI_FUSION_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
191 
192 	/* Dummy readl to force pci flush */
193 	dev_info(&instance->pdev->dev, "%s is called outbound_intr_mask:0x%08x\n",
194 		 __func__, readl(&regs->outbound_intr_mask));
195 }
196 
197 /**
198  * megasas_disable_intr_fusion - Disables interrupt
199  * @regs:			 MFI register set
200  */
201 void
202 megasas_disable_intr_fusion(struct megasas_instance *instance)
203 {
204 	u32 mask = 0xFFFFFFFF;
205 	struct megasas_register_set __iomem *regs;
206 	regs = instance->reg_set;
207 	instance->mask_interrupts = 1;
208 
209 	writel(mask, &regs->outbound_intr_mask);
210 	/* Dummy readl to force pci flush */
211 	dev_info(&instance->pdev->dev, "%s is called outbound_intr_mask:0x%08x\n",
212 		 __func__, readl(&regs->outbound_intr_mask));
213 }
214 
215 int
216 megasas_clear_intr_fusion(struct megasas_instance *instance)
217 {
218 	u32 status;
219 	struct megasas_register_set __iomem *regs;
220 	regs = instance->reg_set;
221 	/*
222 	 * Check if it is our interrupt
223 	 */
224 	status = megasas_readl(instance,
225 			       &regs->outbound_intr_status);
226 
227 	if (status & 1) {
228 		writel(status, &regs->outbound_intr_status);
229 		readl(&regs->outbound_intr_status);
230 		return 1;
231 	}
232 	if (!(status & MFI_FUSION_ENABLE_INTERRUPT_MASK))
233 		return 0;
234 
235 	return 1;
236 }
237 
238 /**
239  * megasas_get_cmd_fusion -	Get a command from the free pool
240  * @instance:		Adapter soft state
241  *
242  * Returns a blk_tag indexed mpt frame
243  */
244 inline struct megasas_cmd_fusion *megasas_get_cmd_fusion(struct megasas_instance
245 						  *instance, u32 blk_tag)
246 {
247 	struct fusion_context *fusion;
248 
249 	fusion = instance->ctrl_context;
250 	return fusion->cmd_list[blk_tag];
251 }
252 
253 /**
254  * megasas_return_cmd_fusion -	Return a cmd to free command pool
255  * @instance:		Adapter soft state
256  * @cmd:		Command packet to be returned to free command pool
257  */
258 inline void megasas_return_cmd_fusion(struct megasas_instance *instance,
259 	struct megasas_cmd_fusion *cmd)
260 {
261 	cmd->scmd = NULL;
262 	memset(cmd->io_request, 0, MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE);
263 	cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
264 	cmd->cmd_completed = false;
265 }
266 
267 /**
268  * megasas_write_64bit_req_desc -	PCI writes 64bit request descriptor
269  * @instance:				Adapter soft state
270  * @req_desc:				64bit Request descriptor
271  */
272 static void
273 megasas_write_64bit_req_desc(struct megasas_instance *instance,
274 		union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc)
275 {
276 #if defined(writeq) && defined(CONFIG_64BIT)
277 	u64 req_data = (((u64)le32_to_cpu(req_desc->u.high) << 32) |
278 		le32_to_cpu(req_desc->u.low));
279 	writeq(req_data, &instance->reg_set->inbound_low_queue_port);
280 #else
281 	unsigned long flags;
282 	spin_lock_irqsave(&instance->hba_lock, flags);
283 	writel(le32_to_cpu(req_desc->u.low),
284 		&instance->reg_set->inbound_low_queue_port);
285 	writel(le32_to_cpu(req_desc->u.high),
286 		&instance->reg_set->inbound_high_queue_port);
287 	spin_unlock_irqrestore(&instance->hba_lock, flags);
288 #endif
289 }
290 
291 /**
292  * megasas_fire_cmd_fusion -	Sends command to the FW
293  * @instance:			Adapter soft state
294  * @req_desc:			32bit or 64bit Request descriptor
295  *
296  * Perform PCI Write. AERO SERIES supports 32 bit Descriptor.
297  * Prior to AERO_SERIES support 64 bit Descriptor.
298  */
299 static void
300 megasas_fire_cmd_fusion(struct megasas_instance *instance,
301 		union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc)
302 {
303 	if (instance->atomic_desc_support)
304 		writel(le32_to_cpu(req_desc->u.low),
305 			&instance->reg_set->inbound_single_queue_port);
306 	else
307 		megasas_write_64bit_req_desc(instance, req_desc);
308 }
309 
310 /**
311  * megasas_fusion_update_can_queue -	Do all Adapter Queue depth related calculations here
312  * @instance:							Adapter soft state
313  * fw_boot_context:						Whether this function called during probe or after OCR
314  *
315  * This function is only for fusion controllers.
316  * Update host can queue, if firmware downgrade max supported firmware commands.
317  * Firmware upgrade case will be skiped because underlying firmware has
318  * more resource than exposed to the OS.
319  *
320  */
321 static void
322 megasas_fusion_update_can_queue(struct megasas_instance *instance, int fw_boot_context)
323 {
324 	u16 cur_max_fw_cmds = 0;
325 	u16 ldio_threshold = 0;
326 
327 	/* ventura FW does not fill outbound_scratch_pad_2 with queue depth */
328 	if (instance->adapter_type < VENTURA_SERIES)
329 		cur_max_fw_cmds =
330 		megasas_readl(instance,
331 			      &instance->reg_set->outbound_scratch_pad_2) & 0x00FFFF;
332 
333 	if (dual_qdepth_disable || !cur_max_fw_cmds)
334 		cur_max_fw_cmds = instance->instancet->read_fw_status_reg(instance) & 0x00FFFF;
335 	else
336 		ldio_threshold =
337 			(instance->instancet->read_fw_status_reg(instance) & 0x00FFFF) - MEGASAS_FUSION_IOCTL_CMDS;
338 
339 	dev_info(&instance->pdev->dev,
340 		 "Current firmware supports maximum commands: %d\t LDIO threshold: %d\n",
341 		 cur_max_fw_cmds, ldio_threshold);
342 
343 	if (fw_boot_context == OCR_CONTEXT) {
344 		cur_max_fw_cmds = cur_max_fw_cmds - 1;
345 		if (cur_max_fw_cmds < instance->max_fw_cmds) {
346 			instance->cur_can_queue =
347 				cur_max_fw_cmds - (MEGASAS_FUSION_INTERNAL_CMDS +
348 						MEGASAS_FUSION_IOCTL_CMDS);
349 			instance->host->can_queue = instance->cur_can_queue;
350 			instance->ldio_threshold = ldio_threshold;
351 		}
352 	} else {
353 		instance->max_fw_cmds = cur_max_fw_cmds;
354 		instance->ldio_threshold = ldio_threshold;
355 
356 		if (reset_devices)
357 			instance->max_fw_cmds = min(instance->max_fw_cmds,
358 						(u16)MEGASAS_KDUMP_QUEUE_DEPTH);
359 		/*
360 		* Reduce the max supported cmds by 1. This is to ensure that the
361 		* reply_q_sz (1 more than the max cmd that driver may send)
362 		* does not exceed max cmds that the FW can support
363 		*/
364 		instance->max_fw_cmds = instance->max_fw_cmds-1;
365 	}
366 }
367 
368 static inline void
369 megasas_get_msix_index(struct megasas_instance *instance,
370 		       struct scsi_cmnd *scmd,
371 		       struct megasas_cmd_fusion *cmd,
372 		       u8 data_arms)
373 {
374 	int sdev_busy;
375 
376 	/* nr_hw_queue = 1 for MegaRAID */
377 	struct blk_mq_hw_ctx *hctx =
378 		scmd->device->request_queue->queue_hw_ctx[0];
379 
380 	sdev_busy = atomic_read(&hctx->nr_active);
381 
382 	if (instance->perf_mode == MR_BALANCED_PERF_MODE &&
383 	    sdev_busy > (data_arms * MR_DEVICE_HIGH_IOPS_DEPTH))
384 		cmd->request_desc->SCSIIO.MSIxIndex =
385 			mega_mod64((atomic64_add_return(1, &instance->high_iops_outstanding) /
386 					MR_HIGH_IOPS_BATCH_COUNT), instance->low_latency_index_start);
387 	else if (instance->msix_load_balance)
388 		cmd->request_desc->SCSIIO.MSIxIndex =
389 			(mega_mod64(atomic64_add_return(1, &instance->total_io_count),
390 				instance->msix_vectors));
391 	else
392 		cmd->request_desc->SCSIIO.MSIxIndex =
393 			instance->reply_map[raw_smp_processor_id()];
394 }
395 
396 /**
397  * megasas_free_cmds_fusion -	Free all the cmds in the free cmd pool
398  * @instance:		Adapter soft state
399  */
400 void
401 megasas_free_cmds_fusion(struct megasas_instance *instance)
402 {
403 	int i;
404 	struct fusion_context *fusion = instance->ctrl_context;
405 	struct megasas_cmd_fusion *cmd;
406 
407 	if (fusion->sense)
408 		dma_pool_free(fusion->sense_dma_pool, fusion->sense,
409 			      fusion->sense_phys_addr);
410 
411 	/* SG */
412 	if (fusion->cmd_list) {
413 		for (i = 0; i < instance->max_mpt_cmds; i++) {
414 			cmd = fusion->cmd_list[i];
415 			if (cmd) {
416 				if (cmd->sg_frame)
417 					dma_pool_free(fusion->sg_dma_pool,
418 						      cmd->sg_frame,
419 						      cmd->sg_frame_phys_addr);
420 			}
421 			kfree(cmd);
422 		}
423 		kfree(fusion->cmd_list);
424 	}
425 
426 	if (fusion->sg_dma_pool) {
427 		dma_pool_destroy(fusion->sg_dma_pool);
428 		fusion->sg_dma_pool = NULL;
429 	}
430 	if (fusion->sense_dma_pool) {
431 		dma_pool_destroy(fusion->sense_dma_pool);
432 		fusion->sense_dma_pool = NULL;
433 	}
434 
435 
436 	/* Reply Frame, Desc*/
437 	if (instance->is_rdpq)
438 		megasas_free_rdpq_fusion(instance);
439 	else
440 		megasas_free_reply_fusion(instance);
441 
442 	/* Request Frame, Desc*/
443 	if (fusion->req_frames_desc)
444 		dma_free_coherent(&instance->pdev->dev,
445 			fusion->request_alloc_sz, fusion->req_frames_desc,
446 			fusion->req_frames_desc_phys);
447 	if (fusion->io_request_frames)
448 		dma_pool_free(fusion->io_request_frames_pool,
449 			fusion->io_request_frames,
450 			fusion->io_request_frames_phys);
451 	if (fusion->io_request_frames_pool) {
452 		dma_pool_destroy(fusion->io_request_frames_pool);
453 		fusion->io_request_frames_pool = NULL;
454 	}
455 }
456 
457 /**
458  * megasas_create_sg_sense_fusion -	Creates DMA pool for cmd frames
459  * @instance:			Adapter soft state
460  *
461  */
462 static int megasas_create_sg_sense_fusion(struct megasas_instance *instance)
463 {
464 	int i;
465 	u16 max_cmd;
466 	struct fusion_context *fusion;
467 	struct megasas_cmd_fusion *cmd;
468 	int sense_sz;
469 	u32 offset;
470 
471 	fusion = instance->ctrl_context;
472 	max_cmd = instance->max_fw_cmds;
473 	sense_sz = instance->max_mpt_cmds * SCSI_SENSE_BUFFERSIZE;
474 
475 	fusion->sg_dma_pool =
476 			dma_pool_create("mr_sg", &instance->pdev->dev,
477 				instance->max_chain_frame_sz,
478 				MR_DEFAULT_NVME_PAGE_SIZE, 0);
479 	/* SCSI_SENSE_BUFFERSIZE  = 96 bytes */
480 	fusion->sense_dma_pool =
481 			dma_pool_create("mr_sense", &instance->pdev->dev,
482 				sense_sz, 64, 0);
483 
484 	if (!fusion->sense_dma_pool || !fusion->sg_dma_pool) {
485 		dev_err(&instance->pdev->dev,
486 			"Failed from %s %d\n",  __func__, __LINE__);
487 		return -ENOMEM;
488 	}
489 
490 	fusion->sense = dma_pool_alloc(fusion->sense_dma_pool,
491 				       GFP_KERNEL, &fusion->sense_phys_addr);
492 	if (!fusion->sense) {
493 		dev_err(&instance->pdev->dev,
494 			"failed from %s %d\n",  __func__, __LINE__);
495 		return -ENOMEM;
496 	}
497 
498 	/* sense buffer, request frame and reply desc pool requires to be in
499 	 * same 4 gb region. Below function will check this.
500 	 * In case of failure, new pci pool will be created with updated
501 	 * alignment.
502 	 * Older allocation and pool will be destroyed.
503 	 * Alignment will be used such a way that next allocation if success,
504 	 * will always meet same 4gb region requirement.
505 	 * Actual requirement is not alignment, but we need start and end of
506 	 * DMA address must have same upper 32 bit address.
507 	 */
508 
509 	if (!megasas_check_same_4gb_region(instance, fusion->sense_phys_addr,
510 					   sense_sz)) {
511 		dma_pool_free(fusion->sense_dma_pool, fusion->sense,
512 			      fusion->sense_phys_addr);
513 		fusion->sense = NULL;
514 		dma_pool_destroy(fusion->sense_dma_pool);
515 
516 		fusion->sense_dma_pool =
517 			dma_pool_create("mr_sense_align", &instance->pdev->dev,
518 					sense_sz, roundup_pow_of_two(sense_sz),
519 					0);
520 		if (!fusion->sense_dma_pool) {
521 			dev_err(&instance->pdev->dev,
522 				"Failed from %s %d\n",  __func__, __LINE__);
523 			return -ENOMEM;
524 		}
525 		fusion->sense = dma_pool_alloc(fusion->sense_dma_pool,
526 					       GFP_KERNEL,
527 					       &fusion->sense_phys_addr);
528 		if (!fusion->sense) {
529 			dev_err(&instance->pdev->dev,
530 				"failed from %s %d\n",  __func__, __LINE__);
531 			return -ENOMEM;
532 		}
533 	}
534 
535 	/*
536 	 * Allocate and attach a frame to each of the commands in cmd_list
537 	 */
538 	for (i = 0; i < max_cmd; i++) {
539 		cmd = fusion->cmd_list[i];
540 		cmd->sg_frame = dma_pool_alloc(fusion->sg_dma_pool,
541 					GFP_KERNEL, &cmd->sg_frame_phys_addr);
542 
543 		offset = SCSI_SENSE_BUFFERSIZE * i;
544 		cmd->sense = (u8 *)fusion->sense + offset;
545 		cmd->sense_phys_addr = fusion->sense_phys_addr + offset;
546 
547 		if (!cmd->sg_frame) {
548 			dev_err(&instance->pdev->dev,
549 				"Failed from %s %d\n",  __func__, __LINE__);
550 			return -ENOMEM;
551 		}
552 	}
553 
554 	/* create sense buffer for the raid 1/10 fp */
555 	for (i = max_cmd; i < instance->max_mpt_cmds; i++) {
556 		cmd = fusion->cmd_list[i];
557 		offset = SCSI_SENSE_BUFFERSIZE * i;
558 		cmd->sense = (u8 *)fusion->sense + offset;
559 		cmd->sense_phys_addr = fusion->sense_phys_addr + offset;
560 
561 	}
562 
563 	return 0;
564 }
565 
566 static int
567 megasas_alloc_cmdlist_fusion(struct megasas_instance *instance)
568 {
569 	u32 max_mpt_cmd, i, j;
570 	struct fusion_context *fusion;
571 
572 	fusion = instance->ctrl_context;
573 
574 	max_mpt_cmd = instance->max_mpt_cmds;
575 
576 	/*
577 	 * fusion->cmd_list is an array of struct megasas_cmd_fusion pointers.
578 	 * Allocate the dynamic array first and then allocate individual
579 	 * commands.
580 	 */
581 	fusion->cmd_list =
582 		kcalloc(max_mpt_cmd, sizeof(struct megasas_cmd_fusion *),
583 			GFP_KERNEL);
584 	if (!fusion->cmd_list) {
585 		dev_err(&instance->pdev->dev,
586 			"Failed from %s %d\n",  __func__, __LINE__);
587 		return -ENOMEM;
588 	}
589 
590 	for (i = 0; i < max_mpt_cmd; i++) {
591 		fusion->cmd_list[i] = kzalloc(sizeof(struct megasas_cmd_fusion),
592 					      GFP_KERNEL);
593 		if (!fusion->cmd_list[i]) {
594 			for (j = 0; j < i; j++)
595 				kfree(fusion->cmd_list[j]);
596 			kfree(fusion->cmd_list);
597 			dev_err(&instance->pdev->dev,
598 				"Failed from %s %d\n",  __func__, __LINE__);
599 			return -ENOMEM;
600 		}
601 	}
602 
603 	return 0;
604 }
605 
606 static int
607 megasas_alloc_request_fusion(struct megasas_instance *instance)
608 {
609 	struct fusion_context *fusion;
610 
611 	fusion = instance->ctrl_context;
612 
613 retry_alloc:
614 	fusion->io_request_frames_pool =
615 			dma_pool_create("mr_ioreq", &instance->pdev->dev,
616 				fusion->io_frames_alloc_sz, 16, 0);
617 
618 	if (!fusion->io_request_frames_pool) {
619 		dev_err(&instance->pdev->dev,
620 			"Failed from %s %d\n",  __func__, __LINE__);
621 		return -ENOMEM;
622 	}
623 
624 	fusion->io_request_frames =
625 			dma_pool_alloc(fusion->io_request_frames_pool,
626 				GFP_KERNEL, &fusion->io_request_frames_phys);
627 	if (!fusion->io_request_frames) {
628 		if (instance->max_fw_cmds >= (MEGASAS_REDUCE_QD_COUNT * 2)) {
629 			instance->max_fw_cmds -= MEGASAS_REDUCE_QD_COUNT;
630 			dma_pool_destroy(fusion->io_request_frames_pool);
631 			megasas_configure_queue_sizes(instance);
632 			goto retry_alloc;
633 		} else {
634 			dev_err(&instance->pdev->dev,
635 				"Failed from %s %d\n",  __func__, __LINE__);
636 			return -ENOMEM;
637 		}
638 	}
639 
640 	if (!megasas_check_same_4gb_region(instance,
641 					   fusion->io_request_frames_phys,
642 					   fusion->io_frames_alloc_sz)) {
643 		dma_pool_free(fusion->io_request_frames_pool,
644 			      fusion->io_request_frames,
645 			      fusion->io_request_frames_phys);
646 		fusion->io_request_frames = NULL;
647 		dma_pool_destroy(fusion->io_request_frames_pool);
648 
649 		fusion->io_request_frames_pool =
650 			dma_pool_create("mr_ioreq_align",
651 					&instance->pdev->dev,
652 					fusion->io_frames_alloc_sz,
653 					roundup_pow_of_two(fusion->io_frames_alloc_sz),
654 					0);
655 
656 		if (!fusion->io_request_frames_pool) {
657 			dev_err(&instance->pdev->dev,
658 				"Failed from %s %d\n",  __func__, __LINE__);
659 			return -ENOMEM;
660 		}
661 
662 		fusion->io_request_frames =
663 			dma_pool_alloc(fusion->io_request_frames_pool,
664 				       GFP_KERNEL,
665 				       &fusion->io_request_frames_phys);
666 
667 		if (!fusion->io_request_frames) {
668 			dev_err(&instance->pdev->dev,
669 				"Failed from %s %d\n",  __func__, __LINE__);
670 			return -ENOMEM;
671 		}
672 	}
673 
674 	fusion->req_frames_desc =
675 		dma_alloc_coherent(&instance->pdev->dev,
676 				   fusion->request_alloc_sz,
677 				   &fusion->req_frames_desc_phys, GFP_KERNEL);
678 	if (!fusion->req_frames_desc) {
679 		dev_err(&instance->pdev->dev,
680 			"Failed from %s %d\n",  __func__, __LINE__);
681 		return -ENOMEM;
682 	}
683 
684 	return 0;
685 }
686 
687 static int
688 megasas_alloc_reply_fusion(struct megasas_instance *instance)
689 {
690 	int i, count;
691 	struct fusion_context *fusion;
692 	union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
693 	fusion = instance->ctrl_context;
694 
695 	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
696 	fusion->reply_frames_desc_pool =
697 			dma_pool_create("mr_reply", &instance->pdev->dev,
698 				fusion->reply_alloc_sz * count, 16, 0);
699 
700 	if (!fusion->reply_frames_desc_pool) {
701 		dev_err(&instance->pdev->dev,
702 			"Failed from %s %d\n",  __func__, __LINE__);
703 		return -ENOMEM;
704 	}
705 
706 	fusion->reply_frames_desc[0] =
707 		dma_pool_alloc(fusion->reply_frames_desc_pool,
708 			GFP_KERNEL, &fusion->reply_frames_desc_phys[0]);
709 	if (!fusion->reply_frames_desc[0]) {
710 		dev_err(&instance->pdev->dev,
711 			"Failed from %s %d\n",  __func__, __LINE__);
712 		return -ENOMEM;
713 	}
714 
715 	if (!megasas_check_same_4gb_region(instance,
716 					   fusion->reply_frames_desc_phys[0],
717 					   (fusion->reply_alloc_sz * count))) {
718 		dma_pool_free(fusion->reply_frames_desc_pool,
719 			      fusion->reply_frames_desc[0],
720 			      fusion->reply_frames_desc_phys[0]);
721 		fusion->reply_frames_desc[0] = NULL;
722 		dma_pool_destroy(fusion->reply_frames_desc_pool);
723 
724 		fusion->reply_frames_desc_pool =
725 			dma_pool_create("mr_reply_align",
726 					&instance->pdev->dev,
727 					fusion->reply_alloc_sz * count,
728 					roundup_pow_of_two(fusion->reply_alloc_sz * count),
729 					0);
730 
731 		if (!fusion->reply_frames_desc_pool) {
732 			dev_err(&instance->pdev->dev,
733 				"Failed from %s %d\n",  __func__, __LINE__);
734 			return -ENOMEM;
735 		}
736 
737 		fusion->reply_frames_desc[0] =
738 			dma_pool_alloc(fusion->reply_frames_desc_pool,
739 				       GFP_KERNEL,
740 				       &fusion->reply_frames_desc_phys[0]);
741 
742 		if (!fusion->reply_frames_desc[0]) {
743 			dev_err(&instance->pdev->dev,
744 				"Failed from %s %d\n",  __func__, __LINE__);
745 			return -ENOMEM;
746 		}
747 	}
748 
749 	reply_desc = fusion->reply_frames_desc[0];
750 	for (i = 0; i < fusion->reply_q_depth * count; i++, reply_desc++)
751 		reply_desc->Words = cpu_to_le64(ULLONG_MAX);
752 
753 	/* This is not a rdpq mode, but driver still populate
754 	 * reply_frame_desc array to use same msix index in ISR path.
755 	 */
756 	for (i = 0; i < (count - 1); i++)
757 		fusion->reply_frames_desc[i + 1] =
758 			fusion->reply_frames_desc[i] +
759 			(fusion->reply_alloc_sz)/sizeof(union MPI2_REPLY_DESCRIPTORS_UNION);
760 
761 	return 0;
762 }
763 
764 static int
765 megasas_alloc_rdpq_fusion(struct megasas_instance *instance)
766 {
767 	int i, j, k, msix_count;
768 	struct fusion_context *fusion;
769 	union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
770 	union MPI2_REPLY_DESCRIPTORS_UNION *rdpq_chunk_virt[RDPQ_MAX_CHUNK_COUNT];
771 	dma_addr_t rdpq_chunk_phys[RDPQ_MAX_CHUNK_COUNT];
772 	u8 dma_alloc_count, abs_index;
773 	u32 chunk_size, array_size, offset;
774 
775 	fusion = instance->ctrl_context;
776 	chunk_size = fusion->reply_alloc_sz * RDPQ_MAX_INDEX_IN_ONE_CHUNK;
777 	array_size = sizeof(struct MPI2_IOC_INIT_RDPQ_ARRAY_ENTRY) *
778 		     MAX_MSIX_QUEUES_FUSION;
779 
780 	fusion->rdpq_virt = dma_alloc_coherent(&instance->pdev->dev,
781 					       array_size, &fusion->rdpq_phys,
782 					       GFP_KERNEL);
783 	if (!fusion->rdpq_virt) {
784 		dev_err(&instance->pdev->dev,
785 			"Failed from %s %d\n",  __func__, __LINE__);
786 		return -ENOMEM;
787 	}
788 
789 	msix_count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
790 
791 	fusion->reply_frames_desc_pool = dma_pool_create("mr_rdpq",
792 							 &instance->pdev->dev,
793 							 chunk_size, 16, 0);
794 	fusion->reply_frames_desc_pool_align =
795 				dma_pool_create("mr_rdpq_align",
796 						&instance->pdev->dev,
797 						chunk_size,
798 						roundup_pow_of_two(chunk_size),
799 						0);
800 
801 	if (!fusion->reply_frames_desc_pool ||
802 	    !fusion->reply_frames_desc_pool_align) {
803 		dev_err(&instance->pdev->dev,
804 			"Failed from %s %d\n",  __func__, __LINE__);
805 		return -ENOMEM;
806 	}
807 
808 /*
809  * For INVADER_SERIES each set of 8 reply queues(0-7, 8-15, ..) and
810  * VENTURA_SERIES each set of 16 reply queues(0-15, 16-31, ..) should be
811  * within 4GB boundary and also reply queues in a set must have same
812  * upper 32-bits in their memory address. so here driver is allocating the
813  * DMA'able memory for reply queues according. Driver uses limitation of
814  * VENTURA_SERIES to manage INVADER_SERIES as well.
815  */
816 	dma_alloc_count = DIV_ROUND_UP(msix_count, RDPQ_MAX_INDEX_IN_ONE_CHUNK);
817 
818 	for (i = 0; i < dma_alloc_count; i++) {
819 		rdpq_chunk_virt[i] =
820 			dma_pool_alloc(fusion->reply_frames_desc_pool,
821 				       GFP_KERNEL, &rdpq_chunk_phys[i]);
822 		if (!rdpq_chunk_virt[i]) {
823 			dev_err(&instance->pdev->dev,
824 				"Failed from %s %d\n",  __func__, __LINE__);
825 			return -ENOMEM;
826 		}
827 		/* reply desc pool requires to be in same 4 gb region.
828 		 * Below function will check this.
829 		 * In case of failure, new pci pool will be created with updated
830 		 * alignment.
831 		 * For RDPQ buffers, driver always allocate two separate pci pool.
832 		 * Alignment will be used such a way that next allocation if
833 		 * success, will always meet same 4gb region requirement.
834 		 * rdpq_tracker keep track of each buffer's physical,
835 		 * virtual address and pci pool descriptor. It will help driver
836 		 * while freeing the resources.
837 		 *
838 		 */
839 		if (!megasas_check_same_4gb_region(instance, rdpq_chunk_phys[i],
840 						   chunk_size)) {
841 			dma_pool_free(fusion->reply_frames_desc_pool,
842 				      rdpq_chunk_virt[i],
843 				      rdpq_chunk_phys[i]);
844 
845 			rdpq_chunk_virt[i] =
846 				dma_pool_alloc(fusion->reply_frames_desc_pool_align,
847 					       GFP_KERNEL, &rdpq_chunk_phys[i]);
848 			if (!rdpq_chunk_virt[i]) {
849 				dev_err(&instance->pdev->dev,
850 					"Failed from %s %d\n",
851 					__func__, __LINE__);
852 				return -ENOMEM;
853 			}
854 			fusion->rdpq_tracker[i].dma_pool_ptr =
855 					fusion->reply_frames_desc_pool_align;
856 		} else {
857 			fusion->rdpq_tracker[i].dma_pool_ptr =
858 					fusion->reply_frames_desc_pool;
859 		}
860 
861 		fusion->rdpq_tracker[i].pool_entry_phys = rdpq_chunk_phys[i];
862 		fusion->rdpq_tracker[i].pool_entry_virt = rdpq_chunk_virt[i];
863 	}
864 
865 	for (k = 0; k < dma_alloc_count; k++) {
866 		for (i = 0; i < RDPQ_MAX_INDEX_IN_ONE_CHUNK; i++) {
867 			abs_index = (k * RDPQ_MAX_INDEX_IN_ONE_CHUNK) + i;
868 
869 			if (abs_index == msix_count)
870 				break;
871 			offset = fusion->reply_alloc_sz * i;
872 			fusion->rdpq_virt[abs_index].RDPQBaseAddress =
873 					cpu_to_le64(rdpq_chunk_phys[k] + offset);
874 			fusion->reply_frames_desc_phys[abs_index] =
875 					rdpq_chunk_phys[k] + offset;
876 			fusion->reply_frames_desc[abs_index] =
877 					(union MPI2_REPLY_DESCRIPTORS_UNION *)((u8 *)rdpq_chunk_virt[k] + offset);
878 
879 			reply_desc = fusion->reply_frames_desc[abs_index];
880 			for (j = 0; j < fusion->reply_q_depth; j++, reply_desc++)
881 				reply_desc->Words = ULLONG_MAX;
882 		}
883 	}
884 
885 	return 0;
886 }
887 
888 static void
889 megasas_free_rdpq_fusion(struct megasas_instance *instance) {
890 
891 	int i;
892 	struct fusion_context *fusion;
893 
894 	fusion = instance->ctrl_context;
895 
896 	for (i = 0; i < RDPQ_MAX_CHUNK_COUNT; i++) {
897 		if (fusion->rdpq_tracker[i].pool_entry_virt)
898 			dma_pool_free(fusion->rdpq_tracker[i].dma_pool_ptr,
899 				      fusion->rdpq_tracker[i].pool_entry_virt,
900 				      fusion->rdpq_tracker[i].pool_entry_phys);
901 
902 	}
903 
904 	dma_pool_destroy(fusion->reply_frames_desc_pool);
905 	dma_pool_destroy(fusion->reply_frames_desc_pool_align);
906 
907 	if (fusion->rdpq_virt)
908 		dma_free_coherent(&instance->pdev->dev,
909 			sizeof(struct MPI2_IOC_INIT_RDPQ_ARRAY_ENTRY) * MAX_MSIX_QUEUES_FUSION,
910 			fusion->rdpq_virt, fusion->rdpq_phys);
911 }
912 
913 static void
914 megasas_free_reply_fusion(struct megasas_instance *instance) {
915 
916 	struct fusion_context *fusion;
917 
918 	fusion = instance->ctrl_context;
919 
920 	if (fusion->reply_frames_desc[0])
921 		dma_pool_free(fusion->reply_frames_desc_pool,
922 			fusion->reply_frames_desc[0],
923 			fusion->reply_frames_desc_phys[0]);
924 
925 	dma_pool_destroy(fusion->reply_frames_desc_pool);
926 
927 }
928 
929 
930 /**
931  * megasas_alloc_cmds_fusion -	Allocates the command packets
932  * @instance:		Adapter soft state
933  *
934  *
935  * Each frame has a 32-bit field called context. This context is used to get
936  * back the megasas_cmd_fusion from the frame when a frame gets completed
937  * In this driver, the 32 bit values are the indices into an array cmd_list.
938  * This array is used only to look up the megasas_cmd_fusion given the context.
939  * The free commands themselves are maintained in a linked list called cmd_pool.
940  *
941  * cmds are formed in the io_request and sg_frame members of the
942  * megasas_cmd_fusion. The context field is used to get a request descriptor
943  * and is used as SMID of the cmd.
944  * SMID value range is from 1 to max_fw_cmds.
945  */
946 static int
947 megasas_alloc_cmds_fusion(struct megasas_instance *instance)
948 {
949 	int i;
950 	struct fusion_context *fusion;
951 	struct megasas_cmd_fusion *cmd;
952 	u32 offset;
953 	dma_addr_t io_req_base_phys;
954 	u8 *io_req_base;
955 
956 
957 	fusion = instance->ctrl_context;
958 
959 	if (megasas_alloc_request_fusion(instance))
960 		goto fail_exit;
961 
962 	if (instance->is_rdpq) {
963 		if (megasas_alloc_rdpq_fusion(instance))
964 			goto fail_exit;
965 	} else
966 		if (megasas_alloc_reply_fusion(instance))
967 			goto fail_exit;
968 
969 	if (megasas_alloc_cmdlist_fusion(instance))
970 		goto fail_exit;
971 
972 	dev_info(&instance->pdev->dev, "Configured max firmware commands: %d\n",
973 		 instance->max_fw_cmds);
974 
975 	/* The first 256 bytes (SMID 0) is not used. Don't add to the cmd list */
976 	io_req_base = fusion->io_request_frames + MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;
977 	io_req_base_phys = fusion->io_request_frames_phys + MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;
978 
979 	/*
980 	 * Add all the commands to command pool (fusion->cmd_pool)
981 	 */
982 
983 	/* SMID 0 is reserved. Set SMID/index from 1 */
984 	for (i = 0; i < instance->max_mpt_cmds; i++) {
985 		cmd = fusion->cmd_list[i];
986 		offset = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE * i;
987 		memset(cmd, 0, sizeof(struct megasas_cmd_fusion));
988 		cmd->index = i + 1;
989 		cmd->scmd = NULL;
990 		cmd->sync_cmd_idx =
991 		(i >= instance->max_scsi_cmds && i < instance->max_fw_cmds) ?
992 				(i - instance->max_scsi_cmds) :
993 				(u32)ULONG_MAX; /* Set to Invalid */
994 		cmd->instance = instance;
995 		cmd->io_request =
996 			(struct MPI2_RAID_SCSI_IO_REQUEST *)
997 		  (io_req_base + offset);
998 		memset(cmd->io_request, 0,
999 		       sizeof(struct MPI2_RAID_SCSI_IO_REQUEST));
1000 		cmd->io_request_phys_addr = io_req_base_phys + offset;
1001 		cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
1002 	}
1003 
1004 	if (megasas_create_sg_sense_fusion(instance))
1005 		goto fail_exit;
1006 
1007 	return 0;
1008 
1009 fail_exit:
1010 	megasas_free_cmds_fusion(instance);
1011 	return -ENOMEM;
1012 }
1013 
1014 /**
1015  * wait_and_poll -	Issues a polling command
1016  * @instance:			Adapter soft state
1017  * @cmd:			Command packet to be issued
1018  *
1019  * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
1020  */
1021 int
1022 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
1023 	int seconds)
1024 {
1025 	int i;
1026 	struct megasas_header *frame_hdr = &cmd->frame->hdr;
1027 	u32 status_reg;
1028 
1029 	u32 msecs = seconds * 1000;
1030 
1031 	/*
1032 	 * Wait for cmd_status to change
1033 	 */
1034 	for (i = 0; (i < msecs) && (frame_hdr->cmd_status == 0xff); i += 20) {
1035 		rmb();
1036 		msleep(20);
1037 		if (!(i % 5000)) {
1038 			status_reg = instance->instancet->read_fw_status_reg(instance)
1039 					& MFI_STATE_MASK;
1040 			if (status_reg == MFI_STATE_FAULT)
1041 				break;
1042 		}
1043 	}
1044 
1045 	if (frame_hdr->cmd_status == MFI_STAT_INVALID_STATUS)
1046 		return DCMD_TIMEOUT;
1047 	else if (frame_hdr->cmd_status == MFI_STAT_OK)
1048 		return DCMD_SUCCESS;
1049 	else
1050 		return DCMD_FAILED;
1051 }
1052 
1053 /**
1054  * megasas_ioc_init_fusion -	Initializes the FW
1055  * @instance:		Adapter soft state
1056  *
1057  * Issues the IOC Init cmd
1058  */
1059 int
1060 megasas_ioc_init_fusion(struct megasas_instance *instance)
1061 {
1062 	struct megasas_init_frame *init_frame;
1063 	struct MPI2_IOC_INIT_REQUEST *IOCInitMessage = NULL;
1064 	dma_addr_t	ioc_init_handle;
1065 	struct megasas_cmd *cmd;
1066 	u8 ret, cur_rdpq_mode;
1067 	struct fusion_context *fusion;
1068 	union MEGASAS_REQUEST_DESCRIPTOR_UNION req_desc;
1069 	int i;
1070 	struct megasas_header *frame_hdr;
1071 	const char *sys_info;
1072 	MFI_CAPABILITIES *drv_ops;
1073 	u32 scratch_pad_1;
1074 	ktime_t time;
1075 	bool cur_fw_64bit_dma_capable;
1076 	bool cur_intr_coalescing;
1077 
1078 	fusion = instance->ctrl_context;
1079 
1080 	ioc_init_handle = fusion->ioc_init_request_phys;
1081 	IOCInitMessage = fusion->ioc_init_request;
1082 
1083 	cmd = fusion->ioc_init_cmd;
1084 
1085 	scratch_pad_1 = megasas_readl
1086 		(instance, &instance->reg_set->outbound_scratch_pad_1);
1087 
1088 	cur_rdpq_mode = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ? 1 : 0;
1089 
1090 	if (instance->adapter_type == INVADER_SERIES) {
1091 		cur_fw_64bit_dma_capable =
1092 			(scratch_pad_1 & MR_CAN_HANDLE_64_BIT_DMA_OFFSET) ? true : false;
1093 
1094 		if (instance->consistent_mask_64bit && !cur_fw_64bit_dma_capable) {
1095 			dev_err(&instance->pdev->dev, "Driver was operating on 64bit "
1096 				"DMA mask, but upcoming FW does not support 64bit DMA mask\n");
1097 			megaraid_sas_kill_hba(instance);
1098 			ret = 1;
1099 			goto fail_fw_init;
1100 		}
1101 	}
1102 
1103 	if (instance->is_rdpq && !cur_rdpq_mode) {
1104 		dev_err(&instance->pdev->dev, "Firmware downgrade *NOT SUPPORTED*"
1105 			" from RDPQ mode to non RDPQ mode\n");
1106 		ret = 1;
1107 		goto fail_fw_init;
1108 	}
1109 
1110 	cur_intr_coalescing = (scratch_pad_1 & MR_INTR_COALESCING_SUPPORT_OFFSET) ?
1111 							true : false;
1112 
1113 	if ((instance->low_latency_index_start ==
1114 		MR_HIGH_IOPS_QUEUE_COUNT) && cur_intr_coalescing)
1115 		instance->perf_mode = MR_BALANCED_PERF_MODE;
1116 
1117 	dev_info(&instance->pdev->dev, "Performance mode :%s\n",
1118 		MEGASAS_PERF_MODE_2STR(instance->perf_mode));
1119 
1120 	instance->fw_sync_cache_support = (scratch_pad_1 &
1121 		MR_CAN_HANDLE_SYNC_CACHE_OFFSET) ? 1 : 0;
1122 	dev_info(&instance->pdev->dev, "FW supports sync cache\t: %s\n",
1123 		 instance->fw_sync_cache_support ? "Yes" : "No");
1124 
1125 	memset(IOCInitMessage, 0, sizeof(struct MPI2_IOC_INIT_REQUEST));
1126 
1127 	IOCInitMessage->Function = MPI2_FUNCTION_IOC_INIT;
1128 	IOCInitMessage->WhoInit	= MPI2_WHOINIT_HOST_DRIVER;
1129 	IOCInitMessage->MsgVersion = cpu_to_le16(MPI2_VERSION);
1130 	IOCInitMessage->HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
1131 	IOCInitMessage->SystemRequestFrameSize = cpu_to_le16(MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE / 4);
1132 
1133 	IOCInitMessage->ReplyDescriptorPostQueueDepth = cpu_to_le16(fusion->reply_q_depth);
1134 	IOCInitMessage->ReplyDescriptorPostQueueAddress = instance->is_rdpq ?
1135 			cpu_to_le64(fusion->rdpq_phys) :
1136 			cpu_to_le64(fusion->reply_frames_desc_phys[0]);
1137 	IOCInitMessage->MsgFlags = instance->is_rdpq ?
1138 			MPI2_IOCINIT_MSGFLAG_RDPQ_ARRAY_MODE : 0;
1139 	IOCInitMessage->SystemRequestFrameBaseAddress = cpu_to_le64(fusion->io_request_frames_phys);
1140 	IOCInitMessage->SenseBufferAddressHigh = cpu_to_le32(upper_32_bits(fusion->sense_phys_addr));
1141 	IOCInitMessage->HostMSIxVectors = instance->msix_vectors;
1142 	IOCInitMessage->HostPageSize = MR_DEFAULT_NVME_PAGE_SHIFT;
1143 
1144 	time = ktime_get_real();
1145 	/* Convert to milliseconds as per FW requirement */
1146 	IOCInitMessage->TimeStamp = cpu_to_le64(ktime_to_ms(time));
1147 
1148 	init_frame = (struct megasas_init_frame *)cmd->frame;
1149 	memset(init_frame, 0, IOC_INIT_FRAME_SIZE);
1150 
1151 	frame_hdr = &cmd->frame->hdr;
1152 	frame_hdr->cmd_status = 0xFF;
1153 	frame_hdr->flags |= cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE);
1154 
1155 	init_frame->cmd	= MFI_CMD_INIT;
1156 	init_frame->cmd_status = 0xFF;
1157 
1158 	drv_ops = (MFI_CAPABILITIES *) &(init_frame->driver_operations);
1159 
1160 	/* driver support Extended MSIX */
1161 	if (instance->adapter_type >= INVADER_SERIES)
1162 		drv_ops->mfi_capabilities.support_additional_msix = 1;
1163 	/* driver supports HA / Remote LUN over Fast Path interface */
1164 	drv_ops->mfi_capabilities.support_fp_remote_lun = 1;
1165 
1166 	drv_ops->mfi_capabilities.support_max_255lds = 1;
1167 	drv_ops->mfi_capabilities.support_ndrive_r1_lb = 1;
1168 	drv_ops->mfi_capabilities.security_protocol_cmds_fw = 1;
1169 
1170 	if (instance->max_chain_frame_sz > MEGASAS_CHAIN_FRAME_SZ_MIN)
1171 		drv_ops->mfi_capabilities.support_ext_io_size = 1;
1172 
1173 	drv_ops->mfi_capabilities.support_fp_rlbypass = 1;
1174 	if (!dual_qdepth_disable)
1175 		drv_ops->mfi_capabilities.support_ext_queue_depth = 1;
1176 
1177 	drv_ops->mfi_capabilities.support_qd_throttling = 1;
1178 	drv_ops->mfi_capabilities.support_pd_map_target_id = 1;
1179 	drv_ops->mfi_capabilities.support_nvme_passthru = 1;
1180 	drv_ops->mfi_capabilities.support_fw_exposed_dev_list = 1;
1181 
1182 	if (instance->consistent_mask_64bit)
1183 		drv_ops->mfi_capabilities.support_64bit_mode = 1;
1184 
1185 	/* Convert capability to LE32 */
1186 	cpu_to_le32s((u32 *)&init_frame->driver_operations.mfi_capabilities);
1187 
1188 	sys_info = dmi_get_system_info(DMI_PRODUCT_UUID);
1189 	if (instance->system_info_buf && sys_info) {
1190 		memcpy(instance->system_info_buf->systemId, sys_info,
1191 			strlen(sys_info) > 64 ? 64 : strlen(sys_info));
1192 		instance->system_info_buf->systemIdLength =
1193 			strlen(sys_info) > 64 ? 64 : strlen(sys_info);
1194 		init_frame->system_info_lo = cpu_to_le32(lower_32_bits(instance->system_info_h));
1195 		init_frame->system_info_hi = cpu_to_le32(upper_32_bits(instance->system_info_h));
1196 	}
1197 
1198 	init_frame->queue_info_new_phys_addr_hi =
1199 		cpu_to_le32(upper_32_bits(ioc_init_handle));
1200 	init_frame->queue_info_new_phys_addr_lo =
1201 		cpu_to_le32(lower_32_bits(ioc_init_handle));
1202 	init_frame->data_xfer_len = cpu_to_le32(sizeof(struct MPI2_IOC_INIT_REQUEST));
1203 
1204 	/*
1205 	 * Each bit in replyqueue_mask represents one group of MSI-x vectors
1206 	 * (each group has 8 vectors)
1207 	 */
1208 	switch (instance->perf_mode) {
1209 	case MR_BALANCED_PERF_MODE:
1210 		init_frame->replyqueue_mask =
1211 		       cpu_to_le16(~(~0 << instance->low_latency_index_start/8));
1212 		break;
1213 	case MR_IOPS_PERF_MODE:
1214 		init_frame->replyqueue_mask =
1215 		       cpu_to_le16(~(~0 << instance->msix_vectors/8));
1216 		break;
1217 	}
1218 
1219 
1220 	req_desc.u.low = cpu_to_le32(lower_32_bits(cmd->frame_phys_addr));
1221 	req_desc.u.high = cpu_to_le32(upper_32_bits(cmd->frame_phys_addr));
1222 	req_desc.MFAIo.RequestFlags =
1223 		(MEGASAS_REQ_DESCRIPT_FLAGS_MFA <<
1224 		MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1225 
1226 	/*
1227 	 * disable the intr before firing the init frame
1228 	 */
1229 	instance->instancet->disable_intr(instance);
1230 
1231 	for (i = 0; i < (10 * 1000); i += 20) {
1232 		if (megasas_readl(instance, &instance->reg_set->doorbell) & 1)
1233 			msleep(20);
1234 		else
1235 			break;
1236 	}
1237 
1238 	/* For AERO also, IOC_INIT requires 64 bit descriptor write */
1239 	megasas_write_64bit_req_desc(instance, &req_desc);
1240 
1241 	wait_and_poll(instance, cmd, MFI_IO_TIMEOUT_SECS);
1242 
1243 	frame_hdr = &cmd->frame->hdr;
1244 	if (frame_hdr->cmd_status != 0) {
1245 		ret = 1;
1246 		goto fail_fw_init;
1247 	}
1248 
1249 	if (instance->adapter_type >= AERO_SERIES) {
1250 		scratch_pad_1 = megasas_readl
1251 			(instance, &instance->reg_set->outbound_scratch_pad_1);
1252 
1253 		instance->atomic_desc_support =
1254 			(scratch_pad_1 & MR_ATOMIC_DESCRIPTOR_SUPPORT_OFFSET) ? 1 : 0;
1255 
1256 		dev_info(&instance->pdev->dev, "FW supports atomic descriptor\t: %s\n",
1257 			instance->atomic_desc_support ? "Yes" : "No");
1258 	}
1259 
1260 	return 0;
1261 
1262 fail_fw_init:
1263 	dev_err(&instance->pdev->dev,
1264 		"Init cmd return status FAILED for SCSI host %d\n",
1265 		instance->host->host_no);
1266 
1267 	return ret;
1268 }
1269 
1270 /**
1271  * megasas_sync_pd_seq_num -	JBOD SEQ MAP
1272  * @instance:		Adapter soft state
1273  * @pend:		set to 1, if it is pended jbod map.
1274  *
1275  * Issue Jbod map to the firmware. If it is pended command,
1276  * issue command and return. If it is first instance of jbod map
1277  * issue and receive command.
1278  */
1279 int
1280 megasas_sync_pd_seq_num(struct megasas_instance *instance, bool pend) {
1281 	int ret = 0;
1282 	size_t pd_seq_map_sz;
1283 	struct megasas_cmd *cmd;
1284 	struct megasas_dcmd_frame *dcmd;
1285 	struct fusion_context *fusion = instance->ctrl_context;
1286 	struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
1287 	dma_addr_t pd_seq_h;
1288 
1289 	pd_sync = (void *)fusion->pd_seq_sync[(instance->pd_seq_map_id & 1)];
1290 	pd_seq_h = fusion->pd_seq_phys[(instance->pd_seq_map_id & 1)];
1291 	pd_seq_map_sz = struct_size(pd_sync, seq, MAX_PHYSICAL_DEVICES - 1);
1292 
1293 	cmd = megasas_get_cmd(instance);
1294 	if (!cmd) {
1295 		dev_err(&instance->pdev->dev,
1296 			"Could not get mfi cmd. Fail from %s %d\n",
1297 			__func__, __LINE__);
1298 		return -ENOMEM;
1299 	}
1300 
1301 	dcmd = &cmd->frame->dcmd;
1302 
1303 	memset(pd_sync, 0, pd_seq_map_sz);
1304 	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1305 
1306 	if (pend) {
1307 		dcmd->mbox.b[0] = MEGASAS_DCMD_MBOX_PEND_FLAG;
1308 		dcmd->flags = MFI_FRAME_DIR_WRITE;
1309 		instance->jbod_seq_cmd = cmd;
1310 	} else {
1311 		dcmd->flags = MFI_FRAME_DIR_READ;
1312 	}
1313 
1314 	dcmd->cmd = MFI_CMD_DCMD;
1315 	dcmd->cmd_status = 0xFF;
1316 	dcmd->sge_count = 1;
1317 	dcmd->timeout = 0;
1318 	dcmd->pad_0 = 0;
1319 	dcmd->data_xfer_len = cpu_to_le32(pd_seq_map_sz);
1320 	dcmd->opcode = cpu_to_le32(MR_DCMD_SYSTEM_PD_MAP_GET_INFO);
1321 
1322 	megasas_set_dma_settings(instance, dcmd, pd_seq_h, pd_seq_map_sz);
1323 
1324 	if (pend) {
1325 		instance->instancet->issue_dcmd(instance, cmd);
1326 		return 0;
1327 	}
1328 
1329 	/* Below code is only for non pended DCMD */
1330 	if (!instance->mask_interrupts)
1331 		ret = megasas_issue_blocked_cmd(instance, cmd,
1332 			MFI_IO_TIMEOUT_SECS);
1333 	else
1334 		ret = megasas_issue_polled(instance, cmd);
1335 
1336 	if (le32_to_cpu(pd_sync->count) > MAX_PHYSICAL_DEVICES) {
1337 		dev_warn(&instance->pdev->dev,
1338 			"driver supports max %d JBOD, but FW reports %d\n",
1339 			MAX_PHYSICAL_DEVICES, le32_to_cpu(pd_sync->count));
1340 		ret = -EINVAL;
1341 	}
1342 
1343 	if (ret == DCMD_TIMEOUT)
1344 		dev_warn(&instance->pdev->dev,
1345 			 "%s DCMD timed out, continue without JBOD sequence map\n",
1346 			 __func__);
1347 
1348 	if (ret == DCMD_SUCCESS)
1349 		instance->pd_seq_map_id++;
1350 
1351 	megasas_return_cmd(instance, cmd);
1352 	return ret;
1353 }
1354 
1355 /*
1356  * megasas_get_ld_map_info -	Returns FW's ld_map structure
1357  * @instance:				Adapter soft state
1358  * @pend:				Pend the command or not
1359  * Issues an internal command (DCMD) to get the FW's controller PD
1360  * list structure.  This information is mainly used to find out SYSTEM
1361  * supported by the FW.
1362  * dcmd.mbox value setting for MR_DCMD_LD_MAP_GET_INFO
1363  * dcmd.mbox.b[0]	- number of LDs being sync'd
1364  * dcmd.mbox.b[1]	- 0 - complete command immediately.
1365  *			- 1 - pend till config change
1366  * dcmd.mbox.b[2]	- 0 - supports max 64 lds and uses legacy MR_FW_RAID_MAP
1367  *			- 1 - supports max MAX_LOGICAL_DRIVES_EXT lds and
1368  *				uses extended struct MR_FW_RAID_MAP_EXT
1369  */
1370 static int
1371 megasas_get_ld_map_info(struct megasas_instance *instance)
1372 {
1373 	int ret = 0;
1374 	struct megasas_cmd *cmd;
1375 	struct megasas_dcmd_frame *dcmd;
1376 	void *ci;
1377 	dma_addr_t ci_h = 0;
1378 	u32 size_map_info;
1379 	struct fusion_context *fusion;
1380 
1381 	cmd = megasas_get_cmd(instance);
1382 
1383 	if (!cmd) {
1384 		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get cmd for map info\n");
1385 		return -ENOMEM;
1386 	}
1387 
1388 	fusion = instance->ctrl_context;
1389 
1390 	if (!fusion) {
1391 		megasas_return_cmd(instance, cmd);
1392 		return -ENXIO;
1393 	}
1394 
1395 	dcmd = &cmd->frame->dcmd;
1396 
1397 	size_map_info = fusion->current_map_sz;
1398 
1399 	ci = (void *) fusion->ld_map[(instance->map_id & 1)];
1400 	ci_h = fusion->ld_map_phys[(instance->map_id & 1)];
1401 
1402 	if (!ci) {
1403 		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to alloc mem for ld_map_info\n");
1404 		megasas_return_cmd(instance, cmd);
1405 		return -ENOMEM;
1406 	}
1407 
1408 	memset(ci, 0, fusion->max_map_sz);
1409 	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1410 	dcmd->cmd = MFI_CMD_DCMD;
1411 	dcmd->cmd_status = 0xFF;
1412 	dcmd->sge_count = 1;
1413 	dcmd->flags = MFI_FRAME_DIR_READ;
1414 	dcmd->timeout = 0;
1415 	dcmd->pad_0 = 0;
1416 	dcmd->data_xfer_len = cpu_to_le32(size_map_info);
1417 	dcmd->opcode = cpu_to_le32(MR_DCMD_LD_MAP_GET_INFO);
1418 
1419 	megasas_set_dma_settings(instance, dcmd, ci_h, size_map_info);
1420 
1421 	if (!instance->mask_interrupts)
1422 		ret = megasas_issue_blocked_cmd(instance, cmd,
1423 			MFI_IO_TIMEOUT_SECS);
1424 	else
1425 		ret = megasas_issue_polled(instance, cmd);
1426 
1427 	if (ret == DCMD_TIMEOUT)
1428 		dev_warn(&instance->pdev->dev,
1429 			 "%s DCMD timed out, RAID map is disabled\n",
1430 			 __func__);
1431 
1432 	megasas_return_cmd(instance, cmd);
1433 
1434 	return ret;
1435 }
1436 
1437 u8
1438 megasas_get_map_info(struct megasas_instance *instance)
1439 {
1440 	struct fusion_context *fusion = instance->ctrl_context;
1441 
1442 	fusion->fast_path_io = 0;
1443 	if (!megasas_get_ld_map_info(instance)) {
1444 		if (MR_ValidateMapInfo(instance, instance->map_id)) {
1445 			fusion->fast_path_io = 1;
1446 			return 0;
1447 		}
1448 	}
1449 	return 1;
1450 }
1451 
1452 /*
1453  * megasas_sync_map_info -	Returns FW's ld_map structure
1454  * @instance:				Adapter soft state
1455  *
1456  * Issues an internal command (DCMD) to get the FW's controller PD
1457  * list structure.  This information is mainly used to find out SYSTEM
1458  * supported by the FW.
1459  */
1460 int
1461 megasas_sync_map_info(struct megasas_instance *instance)
1462 {
1463 	int i;
1464 	struct megasas_cmd *cmd;
1465 	struct megasas_dcmd_frame *dcmd;
1466 	u16 num_lds;
1467 	struct fusion_context *fusion;
1468 	struct MR_LD_TARGET_SYNC *ci = NULL;
1469 	struct MR_DRV_RAID_MAP_ALL *map;
1470 	struct MR_LD_RAID  *raid;
1471 	struct MR_LD_TARGET_SYNC *ld_sync;
1472 	dma_addr_t ci_h = 0;
1473 	u32 size_map_info;
1474 
1475 	cmd = megasas_get_cmd(instance);
1476 
1477 	if (!cmd) {
1478 		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get cmd for sync info\n");
1479 		return -ENOMEM;
1480 	}
1481 
1482 	fusion = instance->ctrl_context;
1483 
1484 	if (!fusion) {
1485 		megasas_return_cmd(instance, cmd);
1486 		return 1;
1487 	}
1488 
1489 	map = fusion->ld_drv_map[instance->map_id & 1];
1490 
1491 	num_lds = le16_to_cpu(map->raidMap.ldCount);
1492 
1493 	dcmd = &cmd->frame->dcmd;
1494 
1495 	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1496 
1497 	ci = (struct MR_LD_TARGET_SYNC *)
1498 	  fusion->ld_map[(instance->map_id - 1) & 1];
1499 	memset(ci, 0, fusion->max_map_sz);
1500 
1501 	ci_h = fusion->ld_map_phys[(instance->map_id - 1) & 1];
1502 
1503 	ld_sync = (struct MR_LD_TARGET_SYNC *)ci;
1504 
1505 	for (i = 0; i < num_lds; i++, ld_sync++) {
1506 		raid = MR_LdRaidGet(i, map);
1507 		ld_sync->targetId = MR_GetLDTgtId(i, map);
1508 		ld_sync->seqNum = raid->seqNum;
1509 	}
1510 
1511 	size_map_info = fusion->current_map_sz;
1512 
1513 	dcmd->cmd = MFI_CMD_DCMD;
1514 	dcmd->cmd_status = 0xFF;
1515 	dcmd->sge_count = 1;
1516 	dcmd->flags = MFI_FRAME_DIR_WRITE;
1517 	dcmd->timeout = 0;
1518 	dcmd->pad_0 = 0;
1519 	dcmd->data_xfer_len = cpu_to_le32(size_map_info);
1520 	dcmd->mbox.b[0] = num_lds;
1521 	dcmd->mbox.b[1] = MEGASAS_DCMD_MBOX_PEND_FLAG;
1522 	dcmd->opcode = cpu_to_le32(MR_DCMD_LD_MAP_GET_INFO);
1523 
1524 	megasas_set_dma_settings(instance, dcmd, ci_h, size_map_info);
1525 
1526 	instance->map_update_cmd = cmd;
1527 
1528 	instance->instancet->issue_dcmd(instance, cmd);
1529 
1530 	return 0;
1531 }
1532 
1533 /*
1534  * meagasas_display_intel_branding - Display branding string
1535  * @instance: per adapter object
1536  *
1537  * Return nothing.
1538  */
1539 static void
1540 megasas_display_intel_branding(struct megasas_instance *instance)
1541 {
1542 	if (instance->pdev->subsystem_vendor != PCI_VENDOR_ID_INTEL)
1543 		return;
1544 
1545 	switch (instance->pdev->device) {
1546 	case PCI_DEVICE_ID_LSI_INVADER:
1547 		switch (instance->pdev->subsystem_device) {
1548 		case MEGARAID_INTEL_RS3DC080_SSDID:
1549 			dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1550 				instance->host->host_no,
1551 				MEGARAID_INTEL_RS3DC080_BRANDING);
1552 			break;
1553 		case MEGARAID_INTEL_RS3DC040_SSDID:
1554 			dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1555 				instance->host->host_no,
1556 				MEGARAID_INTEL_RS3DC040_BRANDING);
1557 			break;
1558 		case MEGARAID_INTEL_RS3SC008_SSDID:
1559 			dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1560 				instance->host->host_no,
1561 				MEGARAID_INTEL_RS3SC008_BRANDING);
1562 			break;
1563 		case MEGARAID_INTEL_RS3MC044_SSDID:
1564 			dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1565 				instance->host->host_no,
1566 				MEGARAID_INTEL_RS3MC044_BRANDING);
1567 			break;
1568 		default:
1569 			break;
1570 		}
1571 		break;
1572 	case PCI_DEVICE_ID_LSI_FURY:
1573 		switch (instance->pdev->subsystem_device) {
1574 		case MEGARAID_INTEL_RS3WC080_SSDID:
1575 			dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1576 				instance->host->host_no,
1577 				MEGARAID_INTEL_RS3WC080_BRANDING);
1578 			break;
1579 		case MEGARAID_INTEL_RS3WC040_SSDID:
1580 			dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1581 				instance->host->host_no,
1582 				MEGARAID_INTEL_RS3WC040_BRANDING);
1583 			break;
1584 		default:
1585 			break;
1586 		}
1587 		break;
1588 	case PCI_DEVICE_ID_LSI_CUTLASS_52:
1589 	case PCI_DEVICE_ID_LSI_CUTLASS_53:
1590 		switch (instance->pdev->subsystem_device) {
1591 		case MEGARAID_INTEL_RMS3BC160_SSDID:
1592 			dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1593 				instance->host->host_no,
1594 				MEGARAID_INTEL_RMS3BC160_BRANDING);
1595 			break;
1596 		default:
1597 			break;
1598 		}
1599 		break;
1600 	default:
1601 		break;
1602 	}
1603 }
1604 
1605 /**
1606  * megasas_allocate_raid_maps -	Allocate memory for RAID maps
1607  * @instance:				Adapter soft state
1608  *
1609  * return:				if success: return 0
1610  *					failed:  return -ENOMEM
1611  */
1612 static inline int megasas_allocate_raid_maps(struct megasas_instance *instance)
1613 {
1614 	struct fusion_context *fusion;
1615 	int i = 0;
1616 
1617 	fusion = instance->ctrl_context;
1618 
1619 	fusion->drv_map_pages = get_order(fusion->drv_map_sz);
1620 
1621 	for (i = 0; i < 2; i++) {
1622 		fusion->ld_map[i] = NULL;
1623 
1624 		fusion->ld_drv_map[i] = (void *)
1625 			__get_free_pages(__GFP_ZERO | GFP_KERNEL,
1626 					 fusion->drv_map_pages);
1627 
1628 		if (!fusion->ld_drv_map[i]) {
1629 			fusion->ld_drv_map[i] = vzalloc(fusion->drv_map_sz);
1630 
1631 			if (!fusion->ld_drv_map[i]) {
1632 				dev_err(&instance->pdev->dev,
1633 					"Could not allocate memory for local map"
1634 					" size requested: %d\n",
1635 					fusion->drv_map_sz);
1636 				goto ld_drv_map_alloc_fail;
1637 			}
1638 		}
1639 	}
1640 
1641 	for (i = 0; i < 2; i++) {
1642 		fusion->ld_map[i] = dma_alloc_coherent(&instance->pdev->dev,
1643 						       fusion->max_map_sz,
1644 						       &fusion->ld_map_phys[i],
1645 						       GFP_KERNEL);
1646 		if (!fusion->ld_map[i]) {
1647 			dev_err(&instance->pdev->dev,
1648 				"Could not allocate memory for map info %s:%d\n",
1649 				__func__, __LINE__);
1650 			goto ld_map_alloc_fail;
1651 		}
1652 	}
1653 
1654 	return 0;
1655 
1656 ld_map_alloc_fail:
1657 	for (i = 0; i < 2; i++) {
1658 		if (fusion->ld_map[i])
1659 			dma_free_coherent(&instance->pdev->dev,
1660 					  fusion->max_map_sz,
1661 					  fusion->ld_map[i],
1662 					  fusion->ld_map_phys[i]);
1663 	}
1664 
1665 ld_drv_map_alloc_fail:
1666 	for (i = 0; i < 2; i++) {
1667 		if (fusion->ld_drv_map[i]) {
1668 			if (is_vmalloc_addr(fusion->ld_drv_map[i]))
1669 				vfree(fusion->ld_drv_map[i]);
1670 			else
1671 				free_pages((ulong)fusion->ld_drv_map[i],
1672 					   fusion->drv_map_pages);
1673 		}
1674 	}
1675 
1676 	return -ENOMEM;
1677 }
1678 
1679 /**
1680  * megasas_configure_queue_sizes -	Calculate size of request desc queue,
1681  *					reply desc queue,
1682  *					IO request frame queue, set can_queue.
1683  * @instance:				Adapter soft state
1684  * @return:				void
1685  */
1686 static inline
1687 void megasas_configure_queue_sizes(struct megasas_instance *instance)
1688 {
1689 	struct fusion_context *fusion;
1690 	u16 max_cmd;
1691 
1692 	fusion = instance->ctrl_context;
1693 	max_cmd = instance->max_fw_cmds;
1694 
1695 	if (instance->adapter_type >= VENTURA_SERIES)
1696 		instance->max_mpt_cmds = instance->max_fw_cmds * RAID_1_PEER_CMDS;
1697 	else
1698 		instance->max_mpt_cmds = instance->max_fw_cmds;
1699 
1700 	instance->max_scsi_cmds = instance->max_fw_cmds - instance->max_mfi_cmds;
1701 	instance->cur_can_queue = instance->max_scsi_cmds;
1702 	instance->host->can_queue = instance->cur_can_queue;
1703 
1704 	fusion->reply_q_depth = 2 * ((max_cmd + 1 + 15) / 16) * 16;
1705 
1706 	fusion->request_alloc_sz = sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) *
1707 					  instance->max_mpt_cmds;
1708 	fusion->reply_alloc_sz = sizeof(union MPI2_REPLY_DESCRIPTORS_UNION) *
1709 					(fusion->reply_q_depth);
1710 	fusion->io_frames_alloc_sz = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE +
1711 		(MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE
1712 		 * (instance->max_mpt_cmds + 1)); /* Extra 1 for SMID 0 */
1713 }
1714 
1715 static int megasas_alloc_ioc_init_frame(struct megasas_instance *instance)
1716 {
1717 	struct fusion_context *fusion;
1718 	struct megasas_cmd *cmd;
1719 
1720 	fusion = instance->ctrl_context;
1721 
1722 	cmd = kzalloc(sizeof(struct megasas_cmd), GFP_KERNEL);
1723 
1724 	if (!cmd) {
1725 		dev_err(&instance->pdev->dev, "Failed from func: %s line: %d\n",
1726 			__func__, __LINE__);
1727 		return -ENOMEM;
1728 	}
1729 
1730 	cmd->frame = dma_alloc_coherent(&instance->pdev->dev,
1731 					IOC_INIT_FRAME_SIZE,
1732 					&cmd->frame_phys_addr, GFP_KERNEL);
1733 
1734 	if (!cmd->frame) {
1735 		dev_err(&instance->pdev->dev, "Failed from func: %s line: %d\n",
1736 			__func__, __LINE__);
1737 		kfree(cmd);
1738 		return -ENOMEM;
1739 	}
1740 
1741 	fusion->ioc_init_cmd = cmd;
1742 	return 0;
1743 }
1744 
1745 /**
1746  * megasas_free_ioc_init_cmd -	Free IOC INIT command frame
1747  * @instance:		Adapter soft state
1748  */
1749 static inline void megasas_free_ioc_init_cmd(struct megasas_instance *instance)
1750 {
1751 	struct fusion_context *fusion;
1752 
1753 	fusion = instance->ctrl_context;
1754 
1755 	if (fusion->ioc_init_cmd && fusion->ioc_init_cmd->frame)
1756 		dma_free_coherent(&instance->pdev->dev,
1757 				  IOC_INIT_FRAME_SIZE,
1758 				  fusion->ioc_init_cmd->frame,
1759 				  fusion->ioc_init_cmd->frame_phys_addr);
1760 
1761 	kfree(fusion->ioc_init_cmd);
1762 }
1763 
1764 /**
1765  * megasas_init_adapter_fusion -	Initializes the FW
1766  * @instance:		Adapter soft state
1767  *
1768  * This is the main function for initializing firmware.
1769  */
1770 static u32
1771 megasas_init_adapter_fusion(struct megasas_instance *instance)
1772 {
1773 	struct fusion_context *fusion;
1774 	u32 scratch_pad_1;
1775 	int i = 0, count;
1776 	u32 status_reg;
1777 
1778 	fusion = instance->ctrl_context;
1779 
1780 	megasas_fusion_update_can_queue(instance, PROBE_CONTEXT);
1781 
1782 	/*
1783 	 * Only Driver's internal DCMDs and IOCTL DCMDs needs to have MFI frames
1784 	 */
1785 	instance->max_mfi_cmds =
1786 		MEGASAS_FUSION_INTERNAL_CMDS + MEGASAS_FUSION_IOCTL_CMDS;
1787 
1788 	megasas_configure_queue_sizes(instance);
1789 
1790 	scratch_pad_1 = megasas_readl(instance,
1791 				      &instance->reg_set->outbound_scratch_pad_1);
1792 	/* If scratch_pad_1 & MEGASAS_MAX_CHAIN_SIZE_UNITS_MASK is set,
1793 	 * Firmware support extended IO chain frame which is 4 times more than
1794 	 * legacy Firmware.
1795 	 * Legacy Firmware - Frame size is (8 * 128) = 1K
1796 	 * 1M IO Firmware  - Frame size is (8 * 128 * 4)  = 4K
1797 	 */
1798 	if (scratch_pad_1 & MEGASAS_MAX_CHAIN_SIZE_UNITS_MASK)
1799 		instance->max_chain_frame_sz =
1800 			((scratch_pad_1 & MEGASAS_MAX_CHAIN_SIZE_MASK) >>
1801 			MEGASAS_MAX_CHAIN_SHIFT) * MEGASAS_1MB_IO;
1802 	else
1803 		instance->max_chain_frame_sz =
1804 			((scratch_pad_1 & MEGASAS_MAX_CHAIN_SIZE_MASK) >>
1805 			MEGASAS_MAX_CHAIN_SHIFT) * MEGASAS_256K_IO;
1806 
1807 	if (instance->max_chain_frame_sz < MEGASAS_CHAIN_FRAME_SZ_MIN) {
1808 		dev_warn(&instance->pdev->dev, "frame size %d invalid, fall back to legacy max frame size %d\n",
1809 			instance->max_chain_frame_sz,
1810 			MEGASAS_CHAIN_FRAME_SZ_MIN);
1811 		instance->max_chain_frame_sz = MEGASAS_CHAIN_FRAME_SZ_MIN;
1812 	}
1813 
1814 	fusion->max_sge_in_main_msg =
1815 		(MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE
1816 			- offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL))/16;
1817 
1818 	fusion->max_sge_in_chain =
1819 		instance->max_chain_frame_sz
1820 			/ sizeof(union MPI2_SGE_IO_UNION);
1821 
1822 	instance->max_num_sge =
1823 		rounddown_pow_of_two(fusion->max_sge_in_main_msg
1824 			+ fusion->max_sge_in_chain - 2);
1825 
1826 	/* Used for pass thru MFI frame (DCMD) */
1827 	fusion->chain_offset_mfi_pthru =
1828 		offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL)/16;
1829 
1830 	fusion->chain_offset_io_request =
1831 		(MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE -
1832 		 sizeof(union MPI2_SGE_IO_UNION))/16;
1833 
1834 	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
1835 	for (i = 0 ; i < count; i++)
1836 		fusion->last_reply_idx[i] = 0;
1837 
1838 	/*
1839 	 * For fusion adapters, 3 commands for IOCTL and 8 commands
1840 	 * for driver's internal DCMDs.
1841 	 */
1842 	instance->max_scsi_cmds = instance->max_fw_cmds -
1843 				(MEGASAS_FUSION_INTERNAL_CMDS +
1844 				MEGASAS_FUSION_IOCTL_CMDS);
1845 	sema_init(&instance->ioctl_sem, MEGASAS_FUSION_IOCTL_CMDS);
1846 
1847 	if (megasas_alloc_ioc_init_frame(instance))
1848 		return 1;
1849 
1850 	/*
1851 	 * Allocate memory for descriptors
1852 	 * Create a pool of commands
1853 	 */
1854 	if (megasas_alloc_cmds(instance))
1855 		goto fail_alloc_mfi_cmds;
1856 	if (megasas_alloc_cmds_fusion(instance))
1857 		goto fail_alloc_cmds;
1858 
1859 	if (megasas_ioc_init_fusion(instance)) {
1860 		status_reg = instance->instancet->read_fw_status_reg(instance);
1861 		if (((status_reg & MFI_STATE_MASK) == MFI_STATE_FAULT) &&
1862 		    (status_reg & MFI_RESET_ADAPTER)) {
1863 			/* Do a chip reset and then retry IOC INIT once */
1864 			if (megasas_adp_reset_wait_for_ready
1865 				(instance, true, 0) == FAILED)
1866 				goto fail_ioc_init;
1867 
1868 			if (megasas_ioc_init_fusion(instance))
1869 				goto fail_ioc_init;
1870 		} else {
1871 			goto fail_ioc_init;
1872 		}
1873 	}
1874 
1875 	megasas_display_intel_branding(instance);
1876 	if (megasas_get_ctrl_info(instance)) {
1877 		dev_err(&instance->pdev->dev,
1878 			"Could not get controller info. Fail from %s %d\n",
1879 			__func__, __LINE__);
1880 		goto fail_ioc_init;
1881 	}
1882 
1883 	instance->flag_ieee = 1;
1884 	instance->r1_ldio_hint_default =  MR_R1_LDIO_PIGGYBACK_DEFAULT;
1885 	instance->threshold_reply_count = instance->max_fw_cmds / 4;
1886 	fusion->fast_path_io = 0;
1887 
1888 	if (megasas_allocate_raid_maps(instance))
1889 		goto fail_ioc_init;
1890 
1891 	if (!megasas_get_map_info(instance))
1892 		megasas_sync_map_info(instance);
1893 
1894 	return 0;
1895 
1896 fail_ioc_init:
1897 	megasas_free_cmds_fusion(instance);
1898 fail_alloc_cmds:
1899 	megasas_free_cmds(instance);
1900 fail_alloc_mfi_cmds:
1901 	megasas_free_ioc_init_cmd(instance);
1902 	return 1;
1903 }
1904 
1905 /**
1906  * megasas_fault_detect_work	-	Worker function of
1907  *					FW fault handling workqueue.
1908  */
1909 static void
1910 megasas_fault_detect_work(struct work_struct *work)
1911 {
1912 	struct megasas_instance *instance =
1913 		container_of(work, struct megasas_instance,
1914 			     fw_fault_work.work);
1915 	u32 fw_state, dma_state, status;
1916 
1917 	/* Check the fw state */
1918 	fw_state = instance->instancet->read_fw_status_reg(instance) &
1919 			MFI_STATE_MASK;
1920 
1921 	if (fw_state == MFI_STATE_FAULT) {
1922 		dma_state = instance->instancet->read_fw_status_reg(instance) &
1923 				MFI_STATE_DMADONE;
1924 		/* Start collecting crash, if DMA bit is done */
1925 		if (instance->crash_dump_drv_support &&
1926 		    instance->crash_dump_app_support && dma_state) {
1927 			megasas_fusion_crash_dump(instance);
1928 		} else {
1929 			if (instance->unload == 0) {
1930 				status = megasas_reset_fusion(instance->host, 0);
1931 				if (status != SUCCESS) {
1932 					dev_err(&instance->pdev->dev,
1933 						"Failed from %s %d, do not re-arm timer\n",
1934 						__func__, __LINE__);
1935 					return;
1936 				}
1937 			}
1938 		}
1939 	}
1940 
1941 	if (instance->fw_fault_work_q)
1942 		queue_delayed_work(instance->fw_fault_work_q,
1943 			&instance->fw_fault_work,
1944 			msecs_to_jiffies(MEGASAS_WATCHDOG_THREAD_INTERVAL));
1945 }
1946 
1947 int
1948 megasas_fusion_start_watchdog(struct megasas_instance *instance)
1949 {
1950 	/* Check if the Fault WQ is already started */
1951 	if (instance->fw_fault_work_q)
1952 		return SUCCESS;
1953 
1954 	INIT_DELAYED_WORK(&instance->fw_fault_work, megasas_fault_detect_work);
1955 
1956 	snprintf(instance->fault_handler_work_q_name,
1957 		 sizeof(instance->fault_handler_work_q_name),
1958 		 "poll_megasas%d_status", instance->host->host_no);
1959 
1960 	instance->fw_fault_work_q =
1961 		create_singlethread_workqueue(instance->fault_handler_work_q_name);
1962 	if (!instance->fw_fault_work_q) {
1963 		dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1964 			__func__, __LINE__);
1965 		return FAILED;
1966 	}
1967 
1968 	queue_delayed_work(instance->fw_fault_work_q,
1969 			   &instance->fw_fault_work,
1970 			   msecs_to_jiffies(MEGASAS_WATCHDOG_THREAD_INTERVAL));
1971 
1972 	return SUCCESS;
1973 }
1974 
1975 void
1976 megasas_fusion_stop_watchdog(struct megasas_instance *instance)
1977 {
1978 	struct workqueue_struct *wq;
1979 
1980 	if (instance->fw_fault_work_q) {
1981 		wq = instance->fw_fault_work_q;
1982 		instance->fw_fault_work_q = NULL;
1983 		if (!cancel_delayed_work_sync(&instance->fw_fault_work))
1984 			flush_workqueue(wq);
1985 		destroy_workqueue(wq);
1986 	}
1987 }
1988 
1989 /**
1990  * map_cmd_status -	Maps FW cmd status to OS cmd status
1991  * @cmd :		Pointer to cmd
1992  * @status :		status of cmd returned by FW
1993  * @ext_status :	ext status of cmd returned by FW
1994  */
1995 
1996 static void
1997 map_cmd_status(struct fusion_context *fusion,
1998 		struct scsi_cmnd *scmd, u8 status, u8 ext_status,
1999 		u32 data_length, u8 *sense)
2000 {
2001 	u8 cmd_type;
2002 	int resid;
2003 
2004 	cmd_type = megasas_cmd_type(scmd);
2005 	switch (status) {
2006 
2007 	case MFI_STAT_OK:
2008 		scmd->result = DID_OK << 16;
2009 		break;
2010 
2011 	case MFI_STAT_SCSI_IO_FAILED:
2012 	case MFI_STAT_LD_INIT_IN_PROGRESS:
2013 		scmd->result = (DID_ERROR << 16) | ext_status;
2014 		break;
2015 
2016 	case MFI_STAT_SCSI_DONE_WITH_ERROR:
2017 
2018 		scmd->result = (DID_OK << 16) | ext_status;
2019 		if (ext_status == SAM_STAT_CHECK_CONDITION) {
2020 			memset(scmd->sense_buffer, 0,
2021 			       SCSI_SENSE_BUFFERSIZE);
2022 			memcpy(scmd->sense_buffer, sense,
2023 			       SCSI_SENSE_BUFFERSIZE);
2024 			scmd->result |= DRIVER_SENSE << 24;
2025 		}
2026 
2027 		/*
2028 		 * If the  IO request is partially completed, then MR FW will
2029 		 * update "io_request->DataLength" field with actual number of
2030 		 * bytes transferred.Driver will set residual bytes count in
2031 		 * SCSI command structure.
2032 		 */
2033 		resid = (scsi_bufflen(scmd) - data_length);
2034 		scsi_set_resid(scmd, resid);
2035 
2036 		if (resid &&
2037 			((cmd_type == READ_WRITE_LDIO) ||
2038 			(cmd_type == READ_WRITE_SYSPDIO)))
2039 			scmd_printk(KERN_INFO, scmd, "BRCM Debug mfi stat 0x%x, data len"
2040 				" requested/completed 0x%x/0x%x\n",
2041 				status, scsi_bufflen(scmd), data_length);
2042 		break;
2043 
2044 	case MFI_STAT_LD_OFFLINE:
2045 	case MFI_STAT_DEVICE_NOT_FOUND:
2046 		scmd->result = DID_BAD_TARGET << 16;
2047 		break;
2048 	case MFI_STAT_CONFIG_SEQ_MISMATCH:
2049 		scmd->result = DID_IMM_RETRY << 16;
2050 		break;
2051 	default:
2052 		scmd->result = DID_ERROR << 16;
2053 		break;
2054 	}
2055 }
2056 
2057 /**
2058  * megasas_is_prp_possible -
2059  * Checks if native NVMe PRPs can be built for the IO
2060  *
2061  * @instance:		Adapter soft state
2062  * @scmd:		SCSI command from the mid-layer
2063  * @sge_count:		scatter gather element count.
2064  *
2065  * Returns:		true: PRPs can be built
2066  *			false: IEEE SGLs needs to be built
2067  */
2068 static bool
2069 megasas_is_prp_possible(struct megasas_instance *instance,
2070 			struct scsi_cmnd *scmd, int sge_count)
2071 {
2072 	int i;
2073 	u32 data_length = 0;
2074 	struct scatterlist *sg_scmd;
2075 	bool build_prp = false;
2076 	u32 mr_nvme_pg_size;
2077 
2078 	mr_nvme_pg_size = max_t(u32, instance->nvme_page_size,
2079 				MR_DEFAULT_NVME_PAGE_SIZE);
2080 	data_length = scsi_bufflen(scmd);
2081 	sg_scmd = scsi_sglist(scmd);
2082 
2083 	/*
2084 	 * NVMe uses one PRP for each page (or part of a page)
2085 	 * look at the data length - if 4 pages or less then IEEE is OK
2086 	 * if  > 5 pages then we need to build a native SGL
2087 	 * if > 4 and <= 5 pages, then check physical address of 1st SG entry
2088 	 * if this first size in the page is >= the residual beyond 4 pages
2089 	 * then use IEEE, otherwise use native SGL
2090 	 */
2091 
2092 	if (data_length > (mr_nvme_pg_size * 5)) {
2093 		build_prp = true;
2094 	} else if ((data_length > (mr_nvme_pg_size * 4)) &&
2095 			(data_length <= (mr_nvme_pg_size * 5)))  {
2096 		/* check if 1st SG entry size is < residual beyond 4 pages */
2097 		if (sg_dma_len(sg_scmd) < (data_length - (mr_nvme_pg_size * 4)))
2098 			build_prp = true;
2099 	}
2100 
2101 /*
2102  * Below code detects gaps/holes in IO data buffers.
2103  * What does holes/gaps mean?
2104  * Any SGE except first one in a SGL starts at non NVME page size
2105  * aligned address OR Any SGE except last one in a SGL ends at
2106  * non NVME page size boundary.
2107  *
2108  * Driver has already informed block layer by setting boundary rules for
2109  * bio merging done at NVME page size boundary calling kernel API
2110  * blk_queue_virt_boundary inside slave_config.
2111  * Still there is possibility of IO coming with holes to driver because of
2112  * IO merging done by IO scheduler.
2113  *
2114  * With SCSI BLK MQ enabled, there will be no IO with holes as there is no
2115  * IO scheduling so no IO merging.
2116  *
2117  * With SCSI BLK MQ disabled, IO scheduler may attempt to merge IOs and
2118  * then sending IOs with holes.
2119  *
2120  * Though driver can request block layer to disable IO merging by calling-
2121  * blk_queue_flag_set(QUEUE_FLAG_NOMERGES, sdev->request_queue) but
2122  * user may tune sysfs parameter- nomerges again to 0 or 1.
2123  *
2124  * If in future IO scheduling is enabled with SCSI BLK MQ,
2125  * this algorithm to detect holes will be required in driver
2126  * for SCSI BLK MQ enabled case as well.
2127  *
2128  *
2129  */
2130 	scsi_for_each_sg(scmd, sg_scmd, sge_count, i) {
2131 		if ((i != 0) && (i != (sge_count - 1))) {
2132 			if (mega_mod64(sg_dma_len(sg_scmd), mr_nvme_pg_size) ||
2133 			    mega_mod64(sg_dma_address(sg_scmd),
2134 				       mr_nvme_pg_size)) {
2135 				build_prp = false;
2136 				break;
2137 			}
2138 		}
2139 
2140 		if ((sge_count > 1) && (i == 0)) {
2141 			if ((mega_mod64((sg_dma_address(sg_scmd) +
2142 					sg_dma_len(sg_scmd)),
2143 					mr_nvme_pg_size))) {
2144 				build_prp = false;
2145 				break;
2146 			}
2147 		}
2148 
2149 		if ((sge_count > 1) && (i == (sge_count - 1))) {
2150 			if (mega_mod64(sg_dma_address(sg_scmd),
2151 				       mr_nvme_pg_size)) {
2152 				build_prp = false;
2153 				break;
2154 			}
2155 		}
2156 	}
2157 
2158 	return build_prp;
2159 }
2160 
2161 /**
2162  * megasas_make_prp_nvme -
2163  * Prepare PRPs(Physical Region Page)- SGLs specific to NVMe drives only
2164  *
2165  * @instance:		Adapter soft state
2166  * @scmd:		SCSI command from the mid-layer
2167  * @sgl_ptr:		SGL to be filled in
2168  * @cmd:		Fusion command frame
2169  * @sge_count:		scatter gather element count.
2170  *
2171  * Returns:		true: PRPs are built
2172  *			false: IEEE SGLs needs to be built
2173  */
2174 static bool
2175 megasas_make_prp_nvme(struct megasas_instance *instance, struct scsi_cmnd *scmd,
2176 		      struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr,
2177 		      struct megasas_cmd_fusion *cmd, int sge_count)
2178 {
2179 	int sge_len, offset, num_prp_in_chain = 0;
2180 	struct MPI25_IEEE_SGE_CHAIN64 *main_chain_element, *ptr_first_sgl;
2181 	u64 *ptr_sgl;
2182 	dma_addr_t ptr_sgl_phys;
2183 	u64 sge_addr;
2184 	u32 page_mask, page_mask_result;
2185 	struct scatterlist *sg_scmd;
2186 	u32 first_prp_len;
2187 	bool build_prp = false;
2188 	int data_len = scsi_bufflen(scmd);
2189 	u32 mr_nvme_pg_size = max_t(u32, instance->nvme_page_size,
2190 					MR_DEFAULT_NVME_PAGE_SIZE);
2191 
2192 	build_prp = megasas_is_prp_possible(instance, scmd, sge_count);
2193 
2194 	if (!build_prp)
2195 		return false;
2196 
2197 	/*
2198 	 * Nvme has a very convoluted prp format.  One prp is required
2199 	 * for each page or partial page. Driver need to split up OS sg_list
2200 	 * entries if it is longer than one page or cross a page
2201 	 * boundary.  Driver also have to insert a PRP list pointer entry as
2202 	 * the last entry in each physical page of the PRP list.
2203 	 *
2204 	 * NOTE: The first PRP "entry" is actually placed in the first
2205 	 * SGL entry in the main message as IEEE 64 format.  The 2nd
2206 	 * entry in the main message is the chain element, and the rest
2207 	 * of the PRP entries are built in the contiguous pcie buffer.
2208 	 */
2209 	page_mask = mr_nvme_pg_size - 1;
2210 	ptr_sgl = (u64 *)cmd->sg_frame;
2211 	ptr_sgl_phys = cmd->sg_frame_phys_addr;
2212 	memset(ptr_sgl, 0, instance->max_chain_frame_sz);
2213 
2214 	/* Build chain frame element which holds all prps except first*/
2215 	main_chain_element = (struct MPI25_IEEE_SGE_CHAIN64 *)
2216 	    ((u8 *)sgl_ptr + sizeof(struct MPI25_IEEE_SGE_CHAIN64));
2217 
2218 	main_chain_element->Address = cpu_to_le64(ptr_sgl_phys);
2219 	main_chain_element->NextChainOffset = 0;
2220 	main_chain_element->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2221 					IEEE_SGE_FLAGS_SYSTEM_ADDR |
2222 					MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
2223 
2224 	/* Build first prp, sge need not to be page aligned*/
2225 	ptr_first_sgl = sgl_ptr;
2226 	sg_scmd = scsi_sglist(scmd);
2227 	sge_addr = sg_dma_address(sg_scmd);
2228 	sge_len = sg_dma_len(sg_scmd);
2229 
2230 	offset = (u32)(sge_addr & page_mask);
2231 	first_prp_len = mr_nvme_pg_size - offset;
2232 
2233 	ptr_first_sgl->Address = cpu_to_le64(sge_addr);
2234 	ptr_first_sgl->Length = cpu_to_le32(first_prp_len);
2235 
2236 	data_len -= first_prp_len;
2237 
2238 	if (sge_len > first_prp_len) {
2239 		sge_addr += first_prp_len;
2240 		sge_len -= first_prp_len;
2241 	} else if (sge_len == first_prp_len) {
2242 		sg_scmd = sg_next(sg_scmd);
2243 		sge_addr = sg_dma_address(sg_scmd);
2244 		sge_len = sg_dma_len(sg_scmd);
2245 	}
2246 
2247 	for (;;) {
2248 		offset = (u32)(sge_addr & page_mask);
2249 
2250 		/* Put PRP pointer due to page boundary*/
2251 		page_mask_result = (uintptr_t)(ptr_sgl + 1) & page_mask;
2252 		if (unlikely(!page_mask_result)) {
2253 			scmd_printk(KERN_NOTICE,
2254 				    scmd, "page boundary ptr_sgl: 0x%p\n",
2255 				    ptr_sgl);
2256 			ptr_sgl_phys += 8;
2257 			*ptr_sgl = cpu_to_le64(ptr_sgl_phys);
2258 			ptr_sgl++;
2259 			num_prp_in_chain++;
2260 		}
2261 
2262 		*ptr_sgl = cpu_to_le64(sge_addr);
2263 		ptr_sgl++;
2264 		ptr_sgl_phys += 8;
2265 		num_prp_in_chain++;
2266 
2267 		sge_addr += mr_nvme_pg_size;
2268 		sge_len -= mr_nvme_pg_size;
2269 		data_len -= mr_nvme_pg_size;
2270 
2271 		if (data_len <= 0)
2272 			break;
2273 
2274 		if (sge_len > 0)
2275 			continue;
2276 
2277 		sg_scmd = sg_next(sg_scmd);
2278 		sge_addr = sg_dma_address(sg_scmd);
2279 		sge_len = sg_dma_len(sg_scmd);
2280 	}
2281 
2282 	main_chain_element->Length =
2283 			cpu_to_le32(num_prp_in_chain * sizeof(u64));
2284 
2285 	return build_prp;
2286 }
2287 
2288 /**
2289  * megasas_make_sgl_fusion -	Prepares 32-bit SGL
2290  * @instance:		Adapter soft state
2291  * @scp:		SCSI command from the mid-layer
2292  * @sgl_ptr:		SGL to be filled in
2293  * @cmd:		cmd we are working on
2294  * @sge_count		sge count
2295  *
2296  */
2297 static void
2298 megasas_make_sgl_fusion(struct megasas_instance *instance,
2299 			struct scsi_cmnd *scp,
2300 			struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr,
2301 			struct megasas_cmd_fusion *cmd, int sge_count)
2302 {
2303 	int i, sg_processed;
2304 	struct scatterlist *os_sgl;
2305 	struct fusion_context *fusion;
2306 
2307 	fusion = instance->ctrl_context;
2308 
2309 	if (instance->adapter_type >= INVADER_SERIES) {
2310 		struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr_end = sgl_ptr;
2311 		sgl_ptr_end += fusion->max_sge_in_main_msg - 1;
2312 		sgl_ptr_end->Flags = 0;
2313 	}
2314 
2315 	scsi_for_each_sg(scp, os_sgl, sge_count, i) {
2316 		sgl_ptr->Length = cpu_to_le32(sg_dma_len(os_sgl));
2317 		sgl_ptr->Address = cpu_to_le64(sg_dma_address(os_sgl));
2318 		sgl_ptr->Flags = 0;
2319 		if (instance->adapter_type >= INVADER_SERIES)
2320 			if (i == sge_count - 1)
2321 				sgl_ptr->Flags = IEEE_SGE_FLAGS_END_OF_LIST;
2322 		sgl_ptr++;
2323 		sg_processed = i + 1;
2324 
2325 		if ((sg_processed ==  (fusion->max_sge_in_main_msg - 1)) &&
2326 		    (sge_count > fusion->max_sge_in_main_msg)) {
2327 
2328 			struct MPI25_IEEE_SGE_CHAIN64 *sg_chain;
2329 			if (instance->adapter_type >= INVADER_SERIES) {
2330 				if ((le16_to_cpu(cmd->io_request->IoFlags) &
2331 					MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH) !=
2332 					MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
2333 					cmd->io_request->ChainOffset =
2334 						fusion->
2335 						chain_offset_io_request;
2336 				else
2337 					cmd->io_request->ChainOffset = 0;
2338 			} else
2339 				cmd->io_request->ChainOffset =
2340 					fusion->chain_offset_io_request;
2341 
2342 			sg_chain = sgl_ptr;
2343 			/* Prepare chain element */
2344 			sg_chain->NextChainOffset = 0;
2345 			if (instance->adapter_type >= INVADER_SERIES)
2346 				sg_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT;
2347 			else
2348 				sg_chain->Flags =
2349 					(IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2350 					 MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR);
2351 			sg_chain->Length =  cpu_to_le32((sizeof(union MPI2_SGE_IO_UNION) * (sge_count - sg_processed)));
2352 			sg_chain->Address = cpu_to_le64(cmd->sg_frame_phys_addr);
2353 
2354 			sgl_ptr =
2355 			  (struct MPI25_IEEE_SGE_CHAIN64 *)cmd->sg_frame;
2356 			memset(sgl_ptr, 0, instance->max_chain_frame_sz);
2357 		}
2358 	}
2359 }
2360 
2361 /**
2362  * megasas_make_sgl -	Build Scatter Gather List(SGLs)
2363  * @scp:		SCSI command pointer
2364  * @instance:		Soft instance of controller
2365  * @cmd:		Fusion command pointer
2366  *
2367  * This function will build sgls based on device type.
2368  * For nvme drives, there is different way of building sgls in nvme native
2369  * format- PRPs(Physical Region Page).
2370  *
2371  * Returns the number of sg lists actually used, zero if the sg lists
2372  * is NULL, or -ENOMEM if the mapping failed
2373  */
2374 static
2375 int megasas_make_sgl(struct megasas_instance *instance, struct scsi_cmnd *scp,
2376 		     struct megasas_cmd_fusion *cmd)
2377 {
2378 	int sge_count;
2379 	bool build_prp = false;
2380 	struct MPI25_IEEE_SGE_CHAIN64 *sgl_chain64;
2381 
2382 	sge_count = scsi_dma_map(scp);
2383 
2384 	if ((sge_count > instance->max_num_sge) || (sge_count <= 0))
2385 		return sge_count;
2386 
2387 	sgl_chain64 = (struct MPI25_IEEE_SGE_CHAIN64 *)&cmd->io_request->SGL;
2388 	if ((le16_to_cpu(cmd->io_request->IoFlags) &
2389 	    MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH) &&
2390 	    (cmd->pd_interface == NVME_PD))
2391 		build_prp = megasas_make_prp_nvme(instance, scp, sgl_chain64,
2392 						  cmd, sge_count);
2393 
2394 	if (!build_prp)
2395 		megasas_make_sgl_fusion(instance, scp, sgl_chain64,
2396 					cmd, sge_count);
2397 
2398 	return sge_count;
2399 }
2400 
2401 /**
2402  * megasas_set_pd_lba -	Sets PD LBA
2403  * @cdb:		CDB
2404  * @cdb_len:		cdb length
2405  * @start_blk:		Start block of IO
2406  *
2407  * Used to set the PD LBA in CDB for FP IOs
2408  */
2409 static void
2410 megasas_set_pd_lba(struct MPI2_RAID_SCSI_IO_REQUEST *io_request, u8 cdb_len,
2411 		   struct IO_REQUEST_INFO *io_info, struct scsi_cmnd *scp,
2412 		   struct MR_DRV_RAID_MAP_ALL *local_map_ptr, u32 ref_tag)
2413 {
2414 	struct MR_LD_RAID *raid;
2415 	u16 ld;
2416 	u64 start_blk = io_info->pdBlock;
2417 	u8 *cdb = io_request->CDB.CDB32;
2418 	u32 num_blocks = io_info->numBlocks;
2419 	u8 opcode = 0, flagvals = 0, groupnum = 0, control = 0;
2420 
2421 	/* Check if T10 PI (DIF) is enabled for this LD */
2422 	ld = MR_TargetIdToLdGet(io_info->ldTgtId, local_map_ptr);
2423 	raid = MR_LdRaidGet(ld, local_map_ptr);
2424 	if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER) {
2425 		memset(cdb, 0, sizeof(io_request->CDB.CDB32));
2426 		cdb[0] =  MEGASAS_SCSI_VARIABLE_LENGTH_CMD;
2427 		cdb[7] =  MEGASAS_SCSI_ADDL_CDB_LEN;
2428 
2429 		if (scp->sc_data_direction == DMA_FROM_DEVICE)
2430 			cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_READ32;
2431 		else
2432 			cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_WRITE32;
2433 		cdb[10] = MEGASAS_RD_WR_PROTECT_CHECK_ALL;
2434 
2435 		/* LBA */
2436 		cdb[12] = (u8)((start_blk >> 56) & 0xff);
2437 		cdb[13] = (u8)((start_blk >> 48) & 0xff);
2438 		cdb[14] = (u8)((start_blk >> 40) & 0xff);
2439 		cdb[15] = (u8)((start_blk >> 32) & 0xff);
2440 		cdb[16] = (u8)((start_blk >> 24) & 0xff);
2441 		cdb[17] = (u8)((start_blk >> 16) & 0xff);
2442 		cdb[18] = (u8)((start_blk >> 8) & 0xff);
2443 		cdb[19] = (u8)(start_blk & 0xff);
2444 
2445 		/* Logical block reference tag */
2446 		io_request->CDB.EEDP32.PrimaryReferenceTag =
2447 			cpu_to_be32(ref_tag);
2448 		io_request->CDB.EEDP32.PrimaryApplicationTagMask = cpu_to_be16(0xffff);
2449 		io_request->IoFlags = cpu_to_le16(32); /* Specify 32-byte cdb */
2450 
2451 		/* Transfer length */
2452 		cdb[28] = (u8)((num_blocks >> 24) & 0xff);
2453 		cdb[29] = (u8)((num_blocks >> 16) & 0xff);
2454 		cdb[30] = (u8)((num_blocks >> 8) & 0xff);
2455 		cdb[31] = (u8)(num_blocks & 0xff);
2456 
2457 		/* set SCSI IO EEDPFlags */
2458 		if (scp->sc_data_direction == DMA_FROM_DEVICE) {
2459 			io_request->EEDPFlags = cpu_to_le16(
2460 				MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG  |
2461 				MPI2_SCSIIO_EEDPFLAGS_CHECK_REFTAG |
2462 				MPI2_SCSIIO_EEDPFLAGS_CHECK_REMOVE_OP |
2463 				MPI2_SCSIIO_EEDPFLAGS_CHECK_APPTAG |
2464 				MPI25_SCSIIO_EEDPFLAGS_DO_NOT_DISABLE_MODE |
2465 				MPI2_SCSIIO_EEDPFLAGS_CHECK_GUARD);
2466 		} else {
2467 			io_request->EEDPFlags = cpu_to_le16(
2468 				MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG |
2469 				MPI2_SCSIIO_EEDPFLAGS_INSERT_OP);
2470 		}
2471 		io_request->Control |= cpu_to_le32((0x4 << 26));
2472 		io_request->EEDPBlockSize = cpu_to_le32(scp->device->sector_size);
2473 	} else {
2474 		/* Some drives don't support 16/12 byte CDB's, convert to 10 */
2475 		if (((cdb_len == 12) || (cdb_len == 16)) &&
2476 		    (start_blk <= 0xffffffff)) {
2477 			if (cdb_len == 16) {
2478 				opcode = cdb[0] == READ_16 ? READ_10 : WRITE_10;
2479 				flagvals = cdb[1];
2480 				groupnum = cdb[14];
2481 				control = cdb[15];
2482 			} else {
2483 				opcode = cdb[0] == READ_12 ? READ_10 : WRITE_10;
2484 				flagvals = cdb[1];
2485 				groupnum = cdb[10];
2486 				control = cdb[11];
2487 			}
2488 
2489 			memset(cdb, 0, sizeof(io_request->CDB.CDB32));
2490 
2491 			cdb[0] = opcode;
2492 			cdb[1] = flagvals;
2493 			cdb[6] = groupnum;
2494 			cdb[9] = control;
2495 
2496 			/* Transfer length */
2497 			cdb[8] = (u8)(num_blocks & 0xff);
2498 			cdb[7] = (u8)((num_blocks >> 8) & 0xff);
2499 
2500 			io_request->IoFlags = cpu_to_le16(10); /* Specify 10-byte cdb */
2501 			cdb_len = 10;
2502 		} else if ((cdb_len < 16) && (start_blk > 0xffffffff)) {
2503 			/* Convert to 16 byte CDB for large LBA's */
2504 			switch (cdb_len) {
2505 			case 6:
2506 				opcode = cdb[0] == READ_6 ? READ_16 : WRITE_16;
2507 				control = cdb[5];
2508 				break;
2509 			case 10:
2510 				opcode =
2511 					cdb[0] == READ_10 ? READ_16 : WRITE_16;
2512 				flagvals = cdb[1];
2513 				groupnum = cdb[6];
2514 				control = cdb[9];
2515 				break;
2516 			case 12:
2517 				opcode =
2518 					cdb[0] == READ_12 ? READ_16 : WRITE_16;
2519 				flagvals = cdb[1];
2520 				groupnum = cdb[10];
2521 				control = cdb[11];
2522 				break;
2523 			}
2524 
2525 			memset(cdb, 0, sizeof(io_request->CDB.CDB32));
2526 
2527 			cdb[0] = opcode;
2528 			cdb[1] = flagvals;
2529 			cdb[14] = groupnum;
2530 			cdb[15] = control;
2531 
2532 			/* Transfer length */
2533 			cdb[13] = (u8)(num_blocks & 0xff);
2534 			cdb[12] = (u8)((num_blocks >> 8) & 0xff);
2535 			cdb[11] = (u8)((num_blocks >> 16) & 0xff);
2536 			cdb[10] = (u8)((num_blocks >> 24) & 0xff);
2537 
2538 			io_request->IoFlags = cpu_to_le16(16); /* Specify 16-byte cdb */
2539 			cdb_len = 16;
2540 		}
2541 
2542 		/* Normal case, just load LBA here */
2543 		switch (cdb_len) {
2544 		case 6:
2545 		{
2546 			u8 val = cdb[1] & 0xE0;
2547 			cdb[3] = (u8)(start_blk & 0xff);
2548 			cdb[2] = (u8)((start_blk >> 8) & 0xff);
2549 			cdb[1] = val | ((u8)(start_blk >> 16) & 0x1f);
2550 			break;
2551 		}
2552 		case 10:
2553 			cdb[5] = (u8)(start_blk & 0xff);
2554 			cdb[4] = (u8)((start_blk >> 8) & 0xff);
2555 			cdb[3] = (u8)((start_blk >> 16) & 0xff);
2556 			cdb[2] = (u8)((start_blk >> 24) & 0xff);
2557 			break;
2558 		case 12:
2559 			cdb[5]    = (u8)(start_blk & 0xff);
2560 			cdb[4]    = (u8)((start_blk >> 8) & 0xff);
2561 			cdb[3]    = (u8)((start_blk >> 16) & 0xff);
2562 			cdb[2]    = (u8)((start_blk >> 24) & 0xff);
2563 			break;
2564 		case 16:
2565 			cdb[9]    = (u8)(start_blk & 0xff);
2566 			cdb[8]    = (u8)((start_blk >> 8) & 0xff);
2567 			cdb[7]    = (u8)((start_blk >> 16) & 0xff);
2568 			cdb[6]    = (u8)((start_blk >> 24) & 0xff);
2569 			cdb[5]    = (u8)((start_blk >> 32) & 0xff);
2570 			cdb[4]    = (u8)((start_blk >> 40) & 0xff);
2571 			cdb[3]    = (u8)((start_blk >> 48) & 0xff);
2572 			cdb[2]    = (u8)((start_blk >> 56) & 0xff);
2573 			break;
2574 		}
2575 	}
2576 }
2577 
2578 /**
2579  * megasas_stream_detect -	stream detection on read and and write IOs
2580  * @instance:		Adapter soft state
2581  * @cmd:		    Command to be prepared
2582  * @io_info:		IO Request info
2583  *
2584  */
2585 
2586 /** stream detection on read and and write IOs */
2587 static void megasas_stream_detect(struct megasas_instance *instance,
2588 				  struct megasas_cmd_fusion *cmd,
2589 				  struct IO_REQUEST_INFO *io_info)
2590 {
2591 	struct fusion_context *fusion = instance->ctrl_context;
2592 	u32 device_id = io_info->ldTgtId;
2593 	struct LD_STREAM_DETECT *current_ld_sd
2594 		= fusion->stream_detect_by_ld[device_id];
2595 	u32 *track_stream = &current_ld_sd->mru_bit_map, stream_num;
2596 	u32 shifted_values, unshifted_values;
2597 	u32 index_value_mask, shifted_values_mask;
2598 	int i;
2599 	bool is_read_ahead = false;
2600 	struct STREAM_DETECT *current_sd;
2601 	/* find possible stream */
2602 	for (i = 0; i < MAX_STREAMS_TRACKED; ++i) {
2603 		stream_num = (*track_stream >>
2604 			(i * BITS_PER_INDEX_STREAM)) &
2605 			STREAM_MASK;
2606 		current_sd = &current_ld_sd->stream_track[stream_num];
2607 		/* if we found a stream, update the raid
2608 		 *  context and also update the mruBitMap
2609 		 */
2610 		/*	boundary condition */
2611 		if ((current_sd->next_seq_lba) &&
2612 		    (io_info->ldStartBlock >= current_sd->next_seq_lba) &&
2613 		    (io_info->ldStartBlock <= (current_sd->next_seq_lba + 32)) &&
2614 		    (current_sd->is_read == io_info->isRead)) {
2615 
2616 			if ((io_info->ldStartBlock != current_sd->next_seq_lba)	&&
2617 			    ((!io_info->isRead) || (!is_read_ahead)))
2618 				/*
2619 				 * Once the API availible we need to change this.
2620 				 * At this point we are not allowing any gap
2621 				 */
2622 				continue;
2623 
2624 			SET_STREAM_DETECTED(cmd->io_request->RaidContext.raid_context_g35);
2625 			current_sd->next_seq_lba =
2626 			io_info->ldStartBlock + io_info->numBlocks;
2627 			/*
2628 			 *	update the mruBitMap LRU
2629 			 */
2630 			shifted_values_mask =
2631 				(1 <<  i * BITS_PER_INDEX_STREAM) - 1;
2632 			shifted_values = ((*track_stream & shifted_values_mask)
2633 						<< BITS_PER_INDEX_STREAM);
2634 			index_value_mask =
2635 				STREAM_MASK << i * BITS_PER_INDEX_STREAM;
2636 			unshifted_values =
2637 				*track_stream & ~(shifted_values_mask |
2638 				index_value_mask);
2639 			*track_stream =
2640 				unshifted_values | shifted_values | stream_num;
2641 			return;
2642 		}
2643 	}
2644 	/*
2645 	 * if we did not find any stream, create a new one
2646 	 * from the least recently used
2647 	 */
2648 	stream_num = (*track_stream >>
2649 		((MAX_STREAMS_TRACKED - 1) * BITS_PER_INDEX_STREAM)) &
2650 		STREAM_MASK;
2651 	current_sd = &current_ld_sd->stream_track[stream_num];
2652 	current_sd->is_read = io_info->isRead;
2653 	current_sd->next_seq_lba = io_info->ldStartBlock + io_info->numBlocks;
2654 	*track_stream = (((*track_stream & ZERO_LAST_STREAM) << 4) | stream_num);
2655 	return;
2656 }
2657 
2658 /**
2659  * megasas_set_raidflag_cpu_affinity - This function sets the cpu
2660  * affinity (cpu of the controller) and raid_flags in the raid context
2661  * based on IO type.
2662  *
2663  * @praid_context:	IO RAID context
2664  * @raid:		LD raid map
2665  * @fp_possible:	Is fast path possible?
2666  * @is_read:		Is read IO?
2667  *
2668  */
2669 static void
2670 megasas_set_raidflag_cpu_affinity(struct fusion_context *fusion,
2671 				union RAID_CONTEXT_UNION *praid_context,
2672 				struct MR_LD_RAID *raid, bool fp_possible,
2673 				u8 is_read, u32 scsi_buff_len)
2674 {
2675 	u8 cpu_sel = MR_RAID_CTX_CPUSEL_0;
2676 	struct RAID_CONTEXT_G35 *rctx_g35;
2677 
2678 	rctx_g35 = &praid_context->raid_context_g35;
2679 	if (fp_possible) {
2680 		if (is_read) {
2681 			if ((raid->cpuAffinity.pdRead.cpu0) &&
2682 			    (raid->cpuAffinity.pdRead.cpu1))
2683 				cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2684 			else if (raid->cpuAffinity.pdRead.cpu1)
2685 				cpu_sel = MR_RAID_CTX_CPUSEL_1;
2686 		} else {
2687 			if ((raid->cpuAffinity.pdWrite.cpu0) &&
2688 			    (raid->cpuAffinity.pdWrite.cpu1))
2689 				cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2690 			else if (raid->cpuAffinity.pdWrite.cpu1)
2691 				cpu_sel = MR_RAID_CTX_CPUSEL_1;
2692 			/* Fast path cache by pass capable R0/R1 VD */
2693 			if ((raid->level <= 1) &&
2694 			    (raid->capability.fp_cache_bypass_capable)) {
2695 				rctx_g35->routing_flags |=
2696 					(1 << MR_RAID_CTX_ROUTINGFLAGS_SLD_SHIFT);
2697 				rctx_g35->raid_flags =
2698 					(MR_RAID_FLAGS_IO_SUB_TYPE_CACHE_BYPASS
2699 					<< MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT);
2700 			}
2701 		}
2702 	} else {
2703 		if (is_read) {
2704 			if ((raid->cpuAffinity.ldRead.cpu0) &&
2705 			    (raid->cpuAffinity.ldRead.cpu1))
2706 				cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2707 			else if (raid->cpuAffinity.ldRead.cpu1)
2708 				cpu_sel = MR_RAID_CTX_CPUSEL_1;
2709 		} else {
2710 			if ((raid->cpuAffinity.ldWrite.cpu0) &&
2711 			    (raid->cpuAffinity.ldWrite.cpu1))
2712 				cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2713 			else if (raid->cpuAffinity.ldWrite.cpu1)
2714 				cpu_sel = MR_RAID_CTX_CPUSEL_1;
2715 
2716 			if (is_stream_detected(rctx_g35) &&
2717 			    ((raid->level == 5) || (raid->level == 6)) &&
2718 			    (raid->writeMode == MR_RL_WRITE_THROUGH_MODE) &&
2719 			    (cpu_sel == MR_RAID_CTX_CPUSEL_FCFS))
2720 				cpu_sel = MR_RAID_CTX_CPUSEL_0;
2721 		}
2722 	}
2723 
2724 	rctx_g35->routing_flags |=
2725 		(cpu_sel << MR_RAID_CTX_ROUTINGFLAGS_CPUSEL_SHIFT);
2726 
2727 	/* Always give priority to MR_RAID_FLAGS_IO_SUB_TYPE_LDIO_BW_LIMIT
2728 	 * vs MR_RAID_FLAGS_IO_SUB_TYPE_CACHE_BYPASS.
2729 	 * IO Subtype is not bitmap.
2730 	 */
2731 	if ((fusion->pcie_bw_limitation) && (raid->level == 1) && (!is_read) &&
2732 			(scsi_buff_len > MR_LARGE_IO_MIN_SIZE)) {
2733 		praid_context->raid_context_g35.raid_flags =
2734 			(MR_RAID_FLAGS_IO_SUB_TYPE_LDIO_BW_LIMIT
2735 			<< MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT);
2736 	}
2737 }
2738 
2739 /**
2740  * megasas_build_ldio_fusion -	Prepares IOs to devices
2741  * @instance:		Adapter soft state
2742  * @scp:		SCSI command
2743  * @cmd:		Command to be prepared
2744  *
2745  * Prepares the io_request and chain elements (sg_frame) for IO
2746  * The IO can be for PD (Fast Path) or LD
2747  */
2748 static void
2749 megasas_build_ldio_fusion(struct megasas_instance *instance,
2750 			  struct scsi_cmnd *scp,
2751 			  struct megasas_cmd_fusion *cmd)
2752 {
2753 	bool fp_possible;
2754 	u16 ld;
2755 	u32 start_lba_lo, start_lba_hi, device_id, datalength = 0;
2756 	u32 scsi_buff_len;
2757 	struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
2758 	struct IO_REQUEST_INFO io_info;
2759 	struct fusion_context *fusion;
2760 	struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
2761 	u8 *raidLUN;
2762 	unsigned long spinlock_flags;
2763 	struct MR_LD_RAID *raid = NULL;
2764 	struct MR_PRIV_DEVICE *mrdev_priv;
2765 	struct RAID_CONTEXT *rctx;
2766 	struct RAID_CONTEXT_G35 *rctx_g35;
2767 
2768 	device_id = MEGASAS_DEV_INDEX(scp);
2769 
2770 	fusion = instance->ctrl_context;
2771 
2772 	io_request = cmd->io_request;
2773 	rctx = &io_request->RaidContext.raid_context;
2774 	rctx_g35 = &io_request->RaidContext.raid_context_g35;
2775 
2776 	rctx->virtual_disk_tgt_id = cpu_to_le16(device_id);
2777 	rctx->status = 0;
2778 	rctx->ex_status = 0;
2779 
2780 	start_lba_lo = 0;
2781 	start_lba_hi = 0;
2782 	fp_possible = false;
2783 
2784 	/*
2785 	 * 6-byte READ(0x08) or WRITE(0x0A) cdb
2786 	 */
2787 	if (scp->cmd_len == 6) {
2788 		datalength = (u32) scp->cmnd[4];
2789 		start_lba_lo = ((u32) scp->cmnd[1] << 16) |
2790 			((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
2791 
2792 		start_lba_lo &= 0x1FFFFF;
2793 	}
2794 
2795 	/*
2796 	 * 10-byte READ(0x28) or WRITE(0x2A) cdb
2797 	 */
2798 	else if (scp->cmd_len == 10) {
2799 		datalength = (u32) scp->cmnd[8] |
2800 			((u32) scp->cmnd[7] << 8);
2801 		start_lba_lo = ((u32) scp->cmnd[2] << 24) |
2802 			((u32) scp->cmnd[3] << 16) |
2803 			((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
2804 	}
2805 
2806 	/*
2807 	 * 12-byte READ(0xA8) or WRITE(0xAA) cdb
2808 	 */
2809 	else if (scp->cmd_len == 12) {
2810 		datalength = ((u32) scp->cmnd[6] << 24) |
2811 			((u32) scp->cmnd[7] << 16) |
2812 			((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
2813 		start_lba_lo = ((u32) scp->cmnd[2] << 24) |
2814 			((u32) scp->cmnd[3] << 16) |
2815 			((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
2816 	}
2817 
2818 	/*
2819 	 * 16-byte READ(0x88) or WRITE(0x8A) cdb
2820 	 */
2821 	else if (scp->cmd_len == 16) {
2822 		datalength = ((u32) scp->cmnd[10] << 24) |
2823 			((u32) scp->cmnd[11] << 16) |
2824 			((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
2825 		start_lba_lo = ((u32) scp->cmnd[6] << 24) |
2826 			((u32) scp->cmnd[7] << 16) |
2827 			((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
2828 
2829 		start_lba_hi = ((u32) scp->cmnd[2] << 24) |
2830 			((u32) scp->cmnd[3] << 16) |
2831 			((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
2832 	}
2833 
2834 	memset(&io_info, 0, sizeof(struct IO_REQUEST_INFO));
2835 	io_info.ldStartBlock = ((u64)start_lba_hi << 32) | start_lba_lo;
2836 	io_info.numBlocks = datalength;
2837 	io_info.ldTgtId = device_id;
2838 	io_info.r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
2839 	scsi_buff_len = scsi_bufflen(scp);
2840 	io_request->DataLength = cpu_to_le32(scsi_buff_len);
2841 	io_info.data_arms = 1;
2842 
2843 	if (scp->sc_data_direction == DMA_FROM_DEVICE)
2844 		io_info.isRead = 1;
2845 
2846 	local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
2847 	ld = MR_TargetIdToLdGet(device_id, local_map_ptr);
2848 
2849 	if (ld < instance->fw_supported_vd_count)
2850 		raid = MR_LdRaidGet(ld, local_map_ptr);
2851 
2852 	if (!raid || (!fusion->fast_path_io)) {
2853 		rctx->reg_lock_flags  = 0;
2854 		fp_possible = false;
2855 	} else {
2856 		if (MR_BuildRaidContext(instance, &io_info, rctx,
2857 					local_map_ptr, &raidLUN))
2858 			fp_possible = (io_info.fpOkForIo > 0) ? true : false;
2859 	}
2860 
2861 	megasas_get_msix_index(instance, scp, cmd, io_info.data_arms);
2862 
2863 	if (instance->adapter_type >= VENTURA_SERIES) {
2864 		/* FP for Optimal raid level 1.
2865 		 * All large RAID-1 writes (> 32 KiB, both WT and WB modes)
2866 		 * are built by the driver as LD I/Os.
2867 		 * All small RAID-1 WT writes (<= 32 KiB) are built as FP I/Os
2868 		 * (there is never a reason to process these as buffered writes)
2869 		 * All small RAID-1 WB writes (<= 32 KiB) are built as FP I/Os
2870 		 * with the SLD bit asserted.
2871 		 */
2872 		if (io_info.r1_alt_dev_handle != MR_DEVHANDLE_INVALID) {
2873 			mrdev_priv = scp->device->hostdata;
2874 
2875 			if (atomic_inc_return(&instance->fw_outstanding) >
2876 				(instance->host->can_queue)) {
2877 				fp_possible = false;
2878 				atomic_dec(&instance->fw_outstanding);
2879 			} else if (fusion->pcie_bw_limitation &&
2880 				((scsi_buff_len > MR_LARGE_IO_MIN_SIZE) ||
2881 				   (atomic_dec_if_positive(&mrdev_priv->r1_ldio_hint) > 0))) {
2882 				fp_possible = false;
2883 				atomic_dec(&instance->fw_outstanding);
2884 				if (scsi_buff_len > MR_LARGE_IO_MIN_SIZE)
2885 					atomic_set(&mrdev_priv->r1_ldio_hint,
2886 						   instance->r1_ldio_hint_default);
2887 			}
2888 		}
2889 
2890 		if (!fp_possible ||
2891 		    (io_info.isRead && io_info.ra_capable)) {
2892 			spin_lock_irqsave(&instance->stream_lock,
2893 					  spinlock_flags);
2894 			megasas_stream_detect(instance, cmd, &io_info);
2895 			spin_unlock_irqrestore(&instance->stream_lock,
2896 					       spinlock_flags);
2897 			/* In ventura if stream detected for a read and it is
2898 			 * read ahead capable make this IO as LDIO
2899 			 */
2900 			if (is_stream_detected(rctx_g35))
2901 				fp_possible = false;
2902 		}
2903 
2904 		/* If raid is NULL, set CPU affinity to default CPU0 */
2905 		if (raid)
2906 			megasas_set_raidflag_cpu_affinity(fusion, &io_request->RaidContext,
2907 				raid, fp_possible, io_info.isRead,
2908 				scsi_buff_len);
2909 		else
2910 			rctx_g35->routing_flags |=
2911 				(MR_RAID_CTX_CPUSEL_0 << MR_RAID_CTX_ROUTINGFLAGS_CPUSEL_SHIFT);
2912 	}
2913 
2914 	if (fp_possible) {
2915 		megasas_set_pd_lba(io_request, scp->cmd_len, &io_info, scp,
2916 				   local_map_ptr, start_lba_lo);
2917 		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
2918 		cmd->request_desc->SCSIIO.RequestFlags =
2919 			(MPI2_REQ_DESCRIPT_FLAGS_FP_IO
2920 			 << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2921 		if (instance->adapter_type == INVADER_SERIES) {
2922 			rctx->type = MPI2_TYPE_CUDA;
2923 			rctx->nseg = 0x1;
2924 			io_request->IoFlags |= cpu_to_le16(MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH);
2925 			rctx->reg_lock_flags |=
2926 			  (MR_RL_FLAGS_GRANT_DESTINATION_CUDA |
2927 			   MR_RL_FLAGS_SEQ_NUM_ENABLE);
2928 		} else if (instance->adapter_type >= VENTURA_SERIES) {
2929 			rctx_g35->nseg_type |= (1 << RAID_CONTEXT_NSEG_SHIFT);
2930 			rctx_g35->nseg_type |= (MPI2_TYPE_CUDA << RAID_CONTEXT_TYPE_SHIFT);
2931 			rctx_g35->routing_flags |= (1 << MR_RAID_CTX_ROUTINGFLAGS_SQN_SHIFT);
2932 			io_request->IoFlags |=
2933 				cpu_to_le16(MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH);
2934 		}
2935 		if (fusion->load_balance_info &&
2936 			(fusion->load_balance_info[device_id].loadBalanceFlag) &&
2937 			(io_info.isRead)) {
2938 			io_info.devHandle =
2939 				get_updated_dev_handle(instance,
2940 					&fusion->load_balance_info[device_id],
2941 					&io_info, local_map_ptr);
2942 			scp->SCp.Status |= MEGASAS_LOAD_BALANCE_FLAG;
2943 			cmd->pd_r1_lb = io_info.pd_after_lb;
2944 			if (instance->adapter_type >= VENTURA_SERIES)
2945 				rctx_g35->span_arm = io_info.span_arm;
2946 			else
2947 				rctx->span_arm = io_info.span_arm;
2948 
2949 		} else
2950 			scp->SCp.Status &= ~MEGASAS_LOAD_BALANCE_FLAG;
2951 
2952 		if (instance->adapter_type >= VENTURA_SERIES)
2953 			cmd->r1_alt_dev_handle = io_info.r1_alt_dev_handle;
2954 		else
2955 			cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
2956 
2957 		if ((raidLUN[0] == 1) &&
2958 			(local_map_ptr->raidMap.devHndlInfo[io_info.pd_after_lb].validHandles > 1)) {
2959 			instance->dev_handle = !(instance->dev_handle);
2960 			io_info.devHandle =
2961 				local_map_ptr->raidMap.devHndlInfo[io_info.pd_after_lb].devHandle[instance->dev_handle];
2962 		}
2963 
2964 		cmd->request_desc->SCSIIO.DevHandle = io_info.devHandle;
2965 		io_request->DevHandle = io_info.devHandle;
2966 		cmd->pd_interface = io_info.pd_interface;
2967 		/* populate the LUN field */
2968 		memcpy(io_request->LUN, raidLUN, 8);
2969 	} else {
2970 		rctx->timeout_value =
2971 			cpu_to_le16(local_map_ptr->raidMap.fpPdIoTimeoutSec);
2972 		cmd->request_desc->SCSIIO.RequestFlags =
2973 			(MEGASAS_REQ_DESCRIPT_FLAGS_LD_IO
2974 			 << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2975 		if (instance->adapter_type == INVADER_SERIES) {
2976 			if (io_info.do_fp_rlbypass ||
2977 			(rctx->reg_lock_flags == REGION_TYPE_UNUSED))
2978 				cmd->request_desc->SCSIIO.RequestFlags =
2979 					(MEGASAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
2980 					MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2981 			rctx->type = MPI2_TYPE_CUDA;
2982 			rctx->reg_lock_flags |=
2983 				(MR_RL_FLAGS_GRANT_DESTINATION_CPU0 |
2984 					MR_RL_FLAGS_SEQ_NUM_ENABLE);
2985 			rctx->nseg = 0x1;
2986 		} else if (instance->adapter_type >= VENTURA_SERIES) {
2987 			rctx_g35->routing_flags |= (1 << MR_RAID_CTX_ROUTINGFLAGS_SQN_SHIFT);
2988 			rctx_g35->nseg_type |= (1 << RAID_CONTEXT_NSEG_SHIFT);
2989 			rctx_g35->nseg_type |= (MPI2_TYPE_CUDA << RAID_CONTEXT_TYPE_SHIFT);
2990 		}
2991 		io_request->Function = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
2992 		io_request->DevHandle = cpu_to_le16(device_id);
2993 
2994 	} /* Not FP */
2995 }
2996 
2997 /**
2998  * megasas_build_ld_nonrw_fusion - prepares non rw ios for virtual disk
2999  * @instance:		Adapter soft state
3000  * @scp:		SCSI command
3001  * @cmd:		Command to be prepared
3002  *
3003  * Prepares the io_request frame for non-rw io cmds for vd.
3004  */
3005 static void megasas_build_ld_nonrw_fusion(struct megasas_instance *instance,
3006 			  struct scsi_cmnd *scmd, struct megasas_cmd_fusion *cmd)
3007 {
3008 	u32 device_id;
3009 	struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
3010 	u16 ld;
3011 	struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
3012 	struct fusion_context *fusion = instance->ctrl_context;
3013 	u8                          span, physArm;
3014 	__le16                      devHandle;
3015 	u32                         arRef, pd;
3016 	struct MR_LD_RAID                  *raid;
3017 	struct RAID_CONTEXT                *pRAID_Context;
3018 	u8 fp_possible = 1;
3019 
3020 	io_request = cmd->io_request;
3021 	device_id = MEGASAS_DEV_INDEX(scmd);
3022 	local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
3023 	io_request->DataLength = cpu_to_le32(scsi_bufflen(scmd));
3024 	/* get RAID_Context pointer */
3025 	pRAID_Context = &io_request->RaidContext.raid_context;
3026 	/* Check with FW team */
3027 	pRAID_Context->virtual_disk_tgt_id = cpu_to_le16(device_id);
3028 	pRAID_Context->reg_lock_row_lba    = 0;
3029 	pRAID_Context->reg_lock_length    = 0;
3030 
3031 	if (fusion->fast_path_io && (
3032 		device_id < instance->fw_supported_vd_count)) {
3033 
3034 		ld = MR_TargetIdToLdGet(device_id, local_map_ptr);
3035 		if (ld >= instance->fw_supported_vd_count - 1)
3036 			fp_possible = 0;
3037 		else {
3038 			raid = MR_LdRaidGet(ld, local_map_ptr);
3039 			if (!(raid->capability.fpNonRWCapable))
3040 				fp_possible = 0;
3041 		}
3042 	} else
3043 		fp_possible = 0;
3044 
3045 	if (!fp_possible) {
3046 		io_request->Function  = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
3047 		io_request->DevHandle = cpu_to_le16(device_id);
3048 		io_request->LUN[1] = scmd->device->lun;
3049 		pRAID_Context->timeout_value =
3050 			cpu_to_le16 (scmd->request->timeout / HZ);
3051 		cmd->request_desc->SCSIIO.RequestFlags =
3052 			(MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
3053 			MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
3054 	} else {
3055 
3056 		/* set RAID context values */
3057 		pRAID_Context->config_seq_num = raid->seqNum;
3058 		if (instance->adapter_type < VENTURA_SERIES)
3059 			pRAID_Context->reg_lock_flags = REGION_TYPE_SHARED_READ;
3060 		pRAID_Context->timeout_value =
3061 			cpu_to_le16(raid->fpIoTimeoutForLd);
3062 
3063 		/* get the DevHandle for the PD (since this is
3064 		   fpNonRWCapable, this is a single disk RAID0) */
3065 		span = physArm = 0;
3066 		arRef = MR_LdSpanArrayGet(ld, span, local_map_ptr);
3067 		pd = MR_ArPdGet(arRef, physArm, local_map_ptr);
3068 		devHandle = MR_PdDevHandleGet(pd, local_map_ptr);
3069 
3070 		/* build request descriptor */
3071 		cmd->request_desc->SCSIIO.RequestFlags =
3072 			(MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
3073 			MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
3074 		cmd->request_desc->SCSIIO.DevHandle = devHandle;
3075 
3076 		/* populate the LUN field */
3077 		memcpy(io_request->LUN, raid->LUN, 8);
3078 
3079 		/* build the raidScsiIO structure */
3080 		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
3081 		io_request->DevHandle = devHandle;
3082 	}
3083 }
3084 
3085 /**
3086  * megasas_build_syspd_fusion - prepares rw/non-rw ios for syspd
3087  * @instance:		Adapter soft state
3088  * @scp:		SCSI command
3089  * @cmd:		Command to be prepared
3090  * @fp_possible:	parameter to detect fast path or firmware path io.
3091  *
3092  * Prepares the io_request frame for rw/non-rw io cmds for syspds
3093  */
3094 static void
3095 megasas_build_syspd_fusion(struct megasas_instance *instance,
3096 	struct scsi_cmnd *scmd, struct megasas_cmd_fusion *cmd,
3097 	bool fp_possible)
3098 {
3099 	u32 device_id;
3100 	struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
3101 	u16 pd_index = 0;
3102 	u16 os_timeout_value;
3103 	u16 timeout_limit;
3104 	struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
3105 	struct RAID_CONTEXT	*pRAID_Context;
3106 	struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
3107 	struct MR_PRIV_DEVICE *mr_device_priv_data;
3108 	struct fusion_context *fusion = instance->ctrl_context;
3109 	pd_sync = (void *)fusion->pd_seq_sync[(instance->pd_seq_map_id - 1) & 1];
3110 
3111 	device_id = MEGASAS_DEV_INDEX(scmd);
3112 	pd_index = MEGASAS_PD_INDEX(scmd);
3113 	os_timeout_value = scmd->request->timeout / HZ;
3114 	mr_device_priv_data = scmd->device->hostdata;
3115 	cmd->pd_interface = mr_device_priv_data->interface_type;
3116 
3117 	io_request = cmd->io_request;
3118 	/* get RAID_Context pointer */
3119 	pRAID_Context = &io_request->RaidContext.raid_context;
3120 	pRAID_Context->reg_lock_flags = 0;
3121 	pRAID_Context->reg_lock_row_lba = 0;
3122 	pRAID_Context->reg_lock_length = 0;
3123 	io_request->DataLength = cpu_to_le32(scsi_bufflen(scmd));
3124 	io_request->LUN[1] = scmd->device->lun;
3125 	pRAID_Context->raid_flags = MR_RAID_FLAGS_IO_SUB_TYPE_SYSTEM_PD
3126 		<< MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT;
3127 
3128 	/* If FW supports PD sequence number */
3129 	if (instance->support_seqnum_jbod_fp) {
3130 		if (instance->use_seqnum_jbod_fp &&
3131 			instance->pd_list[pd_index].driveType == TYPE_DISK) {
3132 
3133 			/* More than 256 PD/JBOD support for Ventura */
3134 			if (instance->support_morethan256jbod)
3135 				pRAID_Context->virtual_disk_tgt_id =
3136 					pd_sync->seq[pd_index].pd_target_id;
3137 			else
3138 				pRAID_Context->virtual_disk_tgt_id =
3139 					cpu_to_le16(device_id +
3140 					(MAX_PHYSICAL_DEVICES - 1));
3141 			pRAID_Context->config_seq_num =
3142 				pd_sync->seq[pd_index].seqNum;
3143 			io_request->DevHandle =
3144 				pd_sync->seq[pd_index].devHandle;
3145 			if (instance->adapter_type >= VENTURA_SERIES) {
3146 				io_request->RaidContext.raid_context_g35.routing_flags |=
3147 					(1 << MR_RAID_CTX_ROUTINGFLAGS_SQN_SHIFT);
3148 				io_request->RaidContext.raid_context_g35.nseg_type |=
3149 					(1 << RAID_CONTEXT_NSEG_SHIFT);
3150 				io_request->RaidContext.raid_context_g35.nseg_type |=
3151 					(MPI2_TYPE_CUDA << RAID_CONTEXT_TYPE_SHIFT);
3152 			} else {
3153 				pRAID_Context->type = MPI2_TYPE_CUDA;
3154 				pRAID_Context->nseg = 0x1;
3155 				pRAID_Context->reg_lock_flags |=
3156 					(MR_RL_FLAGS_SEQ_NUM_ENABLE |
3157 					 MR_RL_FLAGS_GRANT_DESTINATION_CUDA);
3158 			}
3159 		} else {
3160 			pRAID_Context->virtual_disk_tgt_id =
3161 				cpu_to_le16(device_id +
3162 				(MAX_PHYSICAL_DEVICES - 1));
3163 			pRAID_Context->config_seq_num = 0;
3164 			io_request->DevHandle = cpu_to_le16(0xFFFF);
3165 		}
3166 	} else {
3167 		pRAID_Context->virtual_disk_tgt_id = cpu_to_le16(device_id);
3168 		pRAID_Context->config_seq_num = 0;
3169 
3170 		if (fusion->fast_path_io) {
3171 			local_map_ptr =
3172 				fusion->ld_drv_map[(instance->map_id & 1)];
3173 			io_request->DevHandle =
3174 				local_map_ptr->raidMap.devHndlInfo[device_id].curDevHdl;
3175 		} else {
3176 			io_request->DevHandle = cpu_to_le16(0xFFFF);
3177 		}
3178 	}
3179 
3180 	cmd->request_desc->SCSIIO.DevHandle = io_request->DevHandle;
3181 
3182 	megasas_get_msix_index(instance, scmd, cmd, 1);
3183 
3184 	if (!fp_possible) {
3185 		/* system pd firmware path */
3186 		io_request->Function  = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
3187 		cmd->request_desc->SCSIIO.RequestFlags =
3188 			(MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
3189 				MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
3190 		pRAID_Context->timeout_value = cpu_to_le16(os_timeout_value);
3191 		pRAID_Context->virtual_disk_tgt_id = cpu_to_le16(device_id);
3192 	} else {
3193 		if (os_timeout_value)
3194 			os_timeout_value++;
3195 
3196 		/* system pd Fast Path */
3197 		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
3198 		timeout_limit = (scmd->device->type == TYPE_DISK) ?
3199 				255 : 0xFFFF;
3200 		pRAID_Context->timeout_value =
3201 			cpu_to_le16((os_timeout_value > timeout_limit) ?
3202 			timeout_limit : os_timeout_value);
3203 		if (instance->adapter_type >= INVADER_SERIES)
3204 			io_request->IoFlags |=
3205 				cpu_to_le16(MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH);
3206 
3207 		cmd->request_desc->SCSIIO.RequestFlags =
3208 			(MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
3209 				MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
3210 	}
3211 }
3212 
3213 /**
3214  * megasas_build_io_fusion -	Prepares IOs to devices
3215  * @instance:		Adapter soft state
3216  * @scp:		SCSI command
3217  * @cmd:		Command to be prepared
3218  *
3219  * Invokes helper functions to prepare request frames
3220  * and sets flags appropriate for IO/Non-IO cmd
3221  */
3222 static int
3223 megasas_build_io_fusion(struct megasas_instance *instance,
3224 			struct scsi_cmnd *scp,
3225 			struct megasas_cmd_fusion *cmd)
3226 {
3227 	int sge_count;
3228 	u8  cmd_type;
3229 	struct MPI2_RAID_SCSI_IO_REQUEST *io_request = cmd->io_request;
3230 	struct MR_PRIV_DEVICE *mr_device_priv_data;
3231 	mr_device_priv_data = scp->device->hostdata;
3232 
3233 	/* Zero out some fields so they don't get reused */
3234 	memset(io_request->LUN, 0x0, 8);
3235 	io_request->CDB.EEDP32.PrimaryReferenceTag = 0;
3236 	io_request->CDB.EEDP32.PrimaryApplicationTagMask = 0;
3237 	io_request->EEDPFlags = 0;
3238 	io_request->Control = 0;
3239 	io_request->EEDPBlockSize = 0;
3240 	io_request->ChainOffset = 0;
3241 	io_request->RaidContext.raid_context.raid_flags = 0;
3242 	io_request->RaidContext.raid_context.type = 0;
3243 	io_request->RaidContext.raid_context.nseg = 0;
3244 
3245 	memcpy(io_request->CDB.CDB32, scp->cmnd, scp->cmd_len);
3246 	/*
3247 	 * Just the CDB length,rest of the Flags are zero
3248 	 * This will be modified for FP in build_ldio_fusion
3249 	 */
3250 	io_request->IoFlags = cpu_to_le16(scp->cmd_len);
3251 
3252 	switch (cmd_type = megasas_cmd_type(scp)) {
3253 	case READ_WRITE_LDIO:
3254 		megasas_build_ldio_fusion(instance, scp, cmd);
3255 		break;
3256 	case NON_READ_WRITE_LDIO:
3257 		megasas_build_ld_nonrw_fusion(instance, scp, cmd);
3258 		break;
3259 	case READ_WRITE_SYSPDIO:
3260 		megasas_build_syspd_fusion(instance, scp, cmd, true);
3261 		break;
3262 	case NON_READ_WRITE_SYSPDIO:
3263 		if (instance->secure_jbod_support ||
3264 		    mr_device_priv_data->is_tm_capable)
3265 			megasas_build_syspd_fusion(instance, scp, cmd, false);
3266 		else
3267 			megasas_build_syspd_fusion(instance, scp, cmd, true);
3268 		break;
3269 	default:
3270 		break;
3271 	}
3272 
3273 	/*
3274 	 * Construct SGL
3275 	 */
3276 
3277 	sge_count = megasas_make_sgl(instance, scp, cmd);
3278 
3279 	if (sge_count > instance->max_num_sge || (sge_count < 0)) {
3280 		dev_err(&instance->pdev->dev,
3281 			"%s %d sge_count (%d) is out of range. Range is:  0-%d\n",
3282 			__func__, __LINE__, sge_count, instance->max_num_sge);
3283 		return 1;
3284 	}
3285 
3286 	if (instance->adapter_type >= VENTURA_SERIES) {
3287 		set_num_sge(&io_request->RaidContext.raid_context_g35, sge_count);
3288 		cpu_to_le16s(&io_request->RaidContext.raid_context_g35.routing_flags);
3289 		cpu_to_le16s(&io_request->RaidContext.raid_context_g35.nseg_type);
3290 	} else {
3291 		/* numSGE store lower 8 bit of sge_count.
3292 		 * numSGEExt store higher 8 bit of sge_count
3293 		 */
3294 		io_request->RaidContext.raid_context.num_sge = sge_count;
3295 		io_request->RaidContext.raid_context.num_sge_ext =
3296 			(u8)(sge_count >> 8);
3297 	}
3298 
3299 	io_request->SGLFlags = cpu_to_le16(MPI2_SGE_FLAGS_64_BIT_ADDRESSING);
3300 
3301 	if (scp->sc_data_direction == DMA_TO_DEVICE)
3302 		io_request->Control |= cpu_to_le32(MPI2_SCSIIO_CONTROL_WRITE);
3303 	else if (scp->sc_data_direction == DMA_FROM_DEVICE)
3304 		io_request->Control |= cpu_to_le32(MPI2_SCSIIO_CONTROL_READ);
3305 
3306 	io_request->SGLOffset0 =
3307 		offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL) / 4;
3308 
3309 	io_request->SenseBufferLowAddress =
3310 		cpu_to_le32(lower_32_bits(cmd->sense_phys_addr));
3311 	io_request->SenseBufferLength = SCSI_SENSE_BUFFERSIZE;
3312 
3313 	cmd->scmd = scp;
3314 	scp->SCp.ptr = (char *)cmd;
3315 
3316 	return 0;
3317 }
3318 
3319 static union MEGASAS_REQUEST_DESCRIPTOR_UNION *
3320 megasas_get_request_descriptor(struct megasas_instance *instance, u16 index)
3321 {
3322 	u8 *p;
3323 	struct fusion_context *fusion;
3324 
3325 	fusion = instance->ctrl_context;
3326 	p = fusion->req_frames_desc +
3327 		sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) * index;
3328 
3329 	return (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)p;
3330 }
3331 
3332 
3333 /* megasas_prepate_secondRaid1_IO
3334  *  It prepares the raid 1 second IO
3335  */
3336 static void megasas_prepare_secondRaid1_IO(struct megasas_instance *instance,
3337 					   struct megasas_cmd_fusion *cmd,
3338 					   struct megasas_cmd_fusion *r1_cmd)
3339 {
3340 	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc, *req_desc2 = NULL;
3341 	struct fusion_context *fusion;
3342 	fusion = instance->ctrl_context;
3343 	req_desc = cmd->request_desc;
3344 	/* copy the io request frame as well as 8 SGEs data for r1 command*/
3345 	memcpy(r1_cmd->io_request, cmd->io_request,
3346 	       (sizeof(struct MPI2_RAID_SCSI_IO_REQUEST)));
3347 	memcpy(&r1_cmd->io_request->SGL, &cmd->io_request->SGL,
3348 	       (fusion->max_sge_in_main_msg * sizeof(union MPI2_SGE_IO_UNION)));
3349 	/*sense buffer is different for r1 command*/
3350 	r1_cmd->io_request->SenseBufferLowAddress =
3351 			cpu_to_le32(lower_32_bits(r1_cmd->sense_phys_addr));
3352 	r1_cmd->scmd = cmd->scmd;
3353 	req_desc2 = megasas_get_request_descriptor(instance,
3354 						   (r1_cmd->index - 1));
3355 	req_desc2->Words = 0;
3356 	r1_cmd->request_desc = req_desc2;
3357 	req_desc2->SCSIIO.SMID = cpu_to_le16(r1_cmd->index);
3358 	req_desc2->SCSIIO.RequestFlags = req_desc->SCSIIO.RequestFlags;
3359 	r1_cmd->request_desc->SCSIIO.DevHandle = cmd->r1_alt_dev_handle;
3360 	r1_cmd->io_request->DevHandle = cmd->r1_alt_dev_handle;
3361 	r1_cmd->r1_alt_dev_handle = cmd->io_request->DevHandle;
3362 	cmd->io_request->RaidContext.raid_context_g35.flow_specific.peer_smid =
3363 			cpu_to_le16(r1_cmd->index);
3364 	r1_cmd->io_request->RaidContext.raid_context_g35.flow_specific.peer_smid =
3365 			cpu_to_le16(cmd->index);
3366 	/*MSIxIndex of both commands request descriptors should be same*/
3367 	r1_cmd->request_desc->SCSIIO.MSIxIndex =
3368 			cmd->request_desc->SCSIIO.MSIxIndex;
3369 	/*span arm is different for r1 cmd*/
3370 	r1_cmd->io_request->RaidContext.raid_context_g35.span_arm =
3371 			cmd->io_request->RaidContext.raid_context_g35.span_arm + 1;
3372 }
3373 
3374 /**
3375  * megasas_build_and_issue_cmd_fusion -Main routine for building and
3376  *                                     issuing non IOCTL cmd
3377  * @instance:			Adapter soft state
3378  * @scmd:			pointer to scsi cmd from OS
3379  */
3380 static u32
3381 megasas_build_and_issue_cmd_fusion(struct megasas_instance *instance,
3382 				   struct scsi_cmnd *scmd)
3383 {
3384 	struct megasas_cmd_fusion *cmd, *r1_cmd = NULL;
3385 	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
3386 	u32 index;
3387 
3388 	if ((megasas_cmd_type(scmd) == READ_WRITE_LDIO) &&
3389 		instance->ldio_threshold &&
3390 		(atomic_inc_return(&instance->ldio_outstanding) >
3391 		instance->ldio_threshold)) {
3392 		atomic_dec(&instance->ldio_outstanding);
3393 		return SCSI_MLQUEUE_DEVICE_BUSY;
3394 	}
3395 
3396 	if (atomic_inc_return(&instance->fw_outstanding) >
3397 			instance->host->can_queue) {
3398 		atomic_dec(&instance->fw_outstanding);
3399 		return SCSI_MLQUEUE_HOST_BUSY;
3400 	}
3401 
3402 	cmd = megasas_get_cmd_fusion(instance, scmd->request->tag);
3403 
3404 	if (!cmd) {
3405 		atomic_dec(&instance->fw_outstanding);
3406 		return SCSI_MLQUEUE_HOST_BUSY;
3407 	}
3408 
3409 	index = cmd->index;
3410 
3411 	req_desc = megasas_get_request_descriptor(instance, index-1);
3412 
3413 	req_desc->Words = 0;
3414 	cmd->request_desc = req_desc;
3415 
3416 	if (megasas_build_io_fusion(instance, scmd, cmd)) {
3417 		megasas_return_cmd_fusion(instance, cmd);
3418 		dev_err(&instance->pdev->dev, "Error building command\n");
3419 		cmd->request_desc = NULL;
3420 		atomic_dec(&instance->fw_outstanding);
3421 		return SCSI_MLQUEUE_HOST_BUSY;
3422 	}
3423 
3424 	req_desc = cmd->request_desc;
3425 	req_desc->SCSIIO.SMID = cpu_to_le16(index);
3426 
3427 	if (cmd->io_request->ChainOffset != 0 &&
3428 	    cmd->io_request->ChainOffset != 0xF)
3429 		dev_err(&instance->pdev->dev, "The chain offset value is not "
3430 		       "correct : %x\n", cmd->io_request->ChainOffset);
3431 	/*
3432 	 *	if it is raid 1/10 fp write capable.
3433 	 *	try to get second command from pool and construct it.
3434 	 *	From FW, it has confirmed that lba values of two PDs
3435 	 *	corresponds to single R1/10 LD are always same
3436 	 *
3437 	 */
3438 	/*	driver side count always should be less than max_fw_cmds
3439 	 *	to get new command
3440 	 */
3441 	if (cmd->r1_alt_dev_handle != MR_DEVHANDLE_INVALID) {
3442 		r1_cmd = megasas_get_cmd_fusion(instance,
3443 				(scmd->request->tag + instance->max_fw_cmds));
3444 		megasas_prepare_secondRaid1_IO(instance, cmd, r1_cmd);
3445 	}
3446 
3447 
3448 	/*
3449 	 * Issue the command to the FW
3450 	 */
3451 
3452 	megasas_fire_cmd_fusion(instance, req_desc);
3453 
3454 	if (r1_cmd)
3455 		megasas_fire_cmd_fusion(instance, r1_cmd->request_desc);
3456 
3457 
3458 	return 0;
3459 }
3460 
3461 /**
3462  * megasas_complete_r1_command -
3463  * completes R1 FP write commands which has valid peer smid
3464  * @instance:			Adapter soft state
3465  * @cmd_fusion:			MPT command frame
3466  *
3467  */
3468 static inline void
3469 megasas_complete_r1_command(struct megasas_instance *instance,
3470 			    struct megasas_cmd_fusion *cmd)
3471 {
3472 	u8 *sense, status, ex_status;
3473 	u32 data_length;
3474 	u16 peer_smid;
3475 	struct fusion_context *fusion;
3476 	struct megasas_cmd_fusion *r1_cmd = NULL;
3477 	struct scsi_cmnd *scmd_local = NULL;
3478 	struct RAID_CONTEXT_G35 *rctx_g35;
3479 
3480 	rctx_g35 = &cmd->io_request->RaidContext.raid_context_g35;
3481 	fusion = instance->ctrl_context;
3482 	peer_smid = le16_to_cpu(rctx_g35->flow_specific.peer_smid);
3483 
3484 	r1_cmd = fusion->cmd_list[peer_smid - 1];
3485 	scmd_local = cmd->scmd;
3486 	status = rctx_g35->status;
3487 	ex_status = rctx_g35->ex_status;
3488 	data_length = cmd->io_request->DataLength;
3489 	sense = cmd->sense;
3490 
3491 	cmd->cmd_completed = true;
3492 
3493 	/* Check if peer command is completed or not*/
3494 	if (r1_cmd->cmd_completed) {
3495 		rctx_g35 = &r1_cmd->io_request->RaidContext.raid_context_g35;
3496 		if (rctx_g35->status != MFI_STAT_OK) {
3497 			status = rctx_g35->status;
3498 			ex_status = rctx_g35->ex_status;
3499 			data_length = r1_cmd->io_request->DataLength;
3500 			sense = r1_cmd->sense;
3501 		}
3502 
3503 		megasas_return_cmd_fusion(instance, r1_cmd);
3504 		map_cmd_status(fusion, scmd_local, status, ex_status,
3505 			       le32_to_cpu(data_length), sense);
3506 		if (instance->ldio_threshold &&
3507 		    megasas_cmd_type(scmd_local) == READ_WRITE_LDIO)
3508 			atomic_dec(&instance->ldio_outstanding);
3509 		scmd_local->SCp.ptr = NULL;
3510 		megasas_return_cmd_fusion(instance, cmd);
3511 		scsi_dma_unmap(scmd_local);
3512 		scmd_local->scsi_done(scmd_local);
3513 	}
3514 }
3515 
3516 /**
3517  * complete_cmd_fusion -	Completes command
3518  * @instance:			Adapter soft state
3519  * Completes all commands that is in reply descriptor queue
3520  */
3521 static int
3522 complete_cmd_fusion(struct megasas_instance *instance, u32 MSIxIndex,
3523 		    struct megasas_irq_context *irq_context)
3524 {
3525 	union MPI2_REPLY_DESCRIPTORS_UNION *desc;
3526 	struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *reply_desc;
3527 	struct MPI2_RAID_SCSI_IO_REQUEST *scsi_io_req;
3528 	struct fusion_context *fusion;
3529 	struct megasas_cmd *cmd_mfi;
3530 	struct megasas_cmd_fusion *cmd_fusion;
3531 	u16 smid, num_completed;
3532 	u8 reply_descript_type, *sense, status, extStatus;
3533 	u32 device_id, data_length;
3534 	union desc_value d_val;
3535 	struct LD_LOAD_BALANCE_INFO *lbinfo;
3536 	int threshold_reply_count = 0;
3537 	struct scsi_cmnd *scmd_local = NULL;
3538 	struct MR_TASK_MANAGE_REQUEST *mr_tm_req;
3539 	struct MPI2_SCSI_TASK_MANAGE_REQUEST *mpi_tm_req;
3540 
3541 	fusion = instance->ctrl_context;
3542 
3543 	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
3544 		return IRQ_HANDLED;
3545 
3546 	desc = fusion->reply_frames_desc[MSIxIndex] +
3547 				fusion->last_reply_idx[MSIxIndex];
3548 
3549 	reply_desc = (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;
3550 
3551 	d_val.word = desc->Words;
3552 
3553 	reply_descript_type = reply_desc->ReplyFlags &
3554 		MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
3555 
3556 	if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
3557 		return IRQ_NONE;
3558 
3559 	num_completed = 0;
3560 
3561 	while (d_val.u.low != cpu_to_le32(UINT_MAX) &&
3562 	       d_val.u.high != cpu_to_le32(UINT_MAX)) {
3563 
3564 		smid = le16_to_cpu(reply_desc->SMID);
3565 		cmd_fusion = fusion->cmd_list[smid - 1];
3566 		scsi_io_req = (struct MPI2_RAID_SCSI_IO_REQUEST *)
3567 						cmd_fusion->io_request;
3568 
3569 		scmd_local = cmd_fusion->scmd;
3570 		status = scsi_io_req->RaidContext.raid_context.status;
3571 		extStatus = scsi_io_req->RaidContext.raid_context.ex_status;
3572 		sense = cmd_fusion->sense;
3573 		data_length = scsi_io_req->DataLength;
3574 
3575 		switch (scsi_io_req->Function) {
3576 		case MPI2_FUNCTION_SCSI_TASK_MGMT:
3577 			mr_tm_req = (struct MR_TASK_MANAGE_REQUEST *)
3578 						cmd_fusion->io_request;
3579 			mpi_tm_req = (struct MPI2_SCSI_TASK_MANAGE_REQUEST *)
3580 						&mr_tm_req->TmRequest;
3581 			dev_dbg(&instance->pdev->dev, "TM completion:"
3582 				"type: 0x%x TaskMID: 0x%x\n",
3583 				mpi_tm_req->TaskType, mpi_tm_req->TaskMID);
3584 			complete(&cmd_fusion->done);
3585 			break;
3586 		case MPI2_FUNCTION_SCSI_IO_REQUEST:  /*Fast Path IO.*/
3587 			/* Update load balancing info */
3588 			if (fusion->load_balance_info &&
3589 			    (cmd_fusion->scmd->SCp.Status &
3590 			    MEGASAS_LOAD_BALANCE_FLAG)) {
3591 				device_id = MEGASAS_DEV_INDEX(scmd_local);
3592 				lbinfo = &fusion->load_balance_info[device_id];
3593 				atomic_dec(&lbinfo->scsi_pending_cmds[cmd_fusion->pd_r1_lb]);
3594 				cmd_fusion->scmd->SCp.Status &= ~MEGASAS_LOAD_BALANCE_FLAG;
3595 			}
3596 			/* Fall through - and complete IO */
3597 		case MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST: /* LD-IO Path */
3598 			atomic_dec(&instance->fw_outstanding);
3599 			if (cmd_fusion->r1_alt_dev_handle == MR_DEVHANDLE_INVALID) {
3600 				map_cmd_status(fusion, scmd_local, status,
3601 					       extStatus, le32_to_cpu(data_length),
3602 					       sense);
3603 				if (instance->ldio_threshold &&
3604 				    (megasas_cmd_type(scmd_local) == READ_WRITE_LDIO))
3605 					atomic_dec(&instance->ldio_outstanding);
3606 				scmd_local->SCp.ptr = NULL;
3607 				megasas_return_cmd_fusion(instance, cmd_fusion);
3608 				scsi_dma_unmap(scmd_local);
3609 				scmd_local->scsi_done(scmd_local);
3610 			} else	/* Optimal VD - R1 FP command completion. */
3611 				megasas_complete_r1_command(instance, cmd_fusion);
3612 			break;
3613 		case MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST: /*MFI command */
3614 			cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
3615 			/* Poll mode. Dummy free.
3616 			 * In case of Interrupt mode, caller has reverse check.
3617 			 */
3618 			if (cmd_mfi->flags & DRV_DCMD_POLLED_MODE) {
3619 				cmd_mfi->flags &= ~DRV_DCMD_POLLED_MODE;
3620 				megasas_return_cmd(instance, cmd_mfi);
3621 			} else
3622 				megasas_complete_cmd(instance, cmd_mfi, DID_OK);
3623 			break;
3624 		}
3625 
3626 		fusion->last_reply_idx[MSIxIndex]++;
3627 		if (fusion->last_reply_idx[MSIxIndex] >=
3628 		    fusion->reply_q_depth)
3629 			fusion->last_reply_idx[MSIxIndex] = 0;
3630 
3631 		desc->Words = cpu_to_le64(ULLONG_MAX);
3632 		num_completed++;
3633 		threshold_reply_count++;
3634 
3635 		/* Get the next reply descriptor */
3636 		if (!fusion->last_reply_idx[MSIxIndex])
3637 			desc = fusion->reply_frames_desc[MSIxIndex];
3638 		else
3639 			desc++;
3640 
3641 		reply_desc =
3642 		  (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;
3643 
3644 		d_val.word = desc->Words;
3645 
3646 		reply_descript_type = reply_desc->ReplyFlags &
3647 			MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
3648 
3649 		if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
3650 			break;
3651 		/*
3652 		 * Write to reply post host index register after completing threshold
3653 		 * number of reply counts and still there are more replies in reply queue
3654 		 * pending to be completed
3655 		 */
3656 		if (threshold_reply_count >= instance->threshold_reply_count) {
3657 			if (instance->msix_combined)
3658 				writel(((MSIxIndex & 0x7) << 24) |
3659 					fusion->last_reply_idx[MSIxIndex],
3660 					instance->reply_post_host_index_addr[MSIxIndex/8]);
3661 			else
3662 				writel((MSIxIndex << 24) |
3663 					fusion->last_reply_idx[MSIxIndex],
3664 					instance->reply_post_host_index_addr[0]);
3665 			threshold_reply_count = 0;
3666 			if (irq_context) {
3667 				if (!irq_context->irq_poll_scheduled) {
3668 					irq_context->irq_poll_scheduled = true;
3669 					irq_context->irq_line_enable = true;
3670 					irq_poll_sched(&irq_context->irqpoll);
3671 				}
3672 				return num_completed;
3673 			}
3674 		}
3675 	}
3676 
3677 	if (num_completed) {
3678 		wmb();
3679 		if (instance->msix_combined)
3680 			writel(((MSIxIndex & 0x7) << 24) |
3681 				fusion->last_reply_idx[MSIxIndex],
3682 				instance->reply_post_host_index_addr[MSIxIndex/8]);
3683 		else
3684 			writel((MSIxIndex << 24) |
3685 				fusion->last_reply_idx[MSIxIndex],
3686 				instance->reply_post_host_index_addr[0]);
3687 		megasas_check_and_restore_queue_depth(instance);
3688 	}
3689 	return num_completed;
3690 }
3691 
3692 /**
3693  * megasas_enable_irq_poll() - enable irqpoll
3694  */
3695 static void megasas_enable_irq_poll(struct megasas_instance *instance)
3696 {
3697 	u32 count, i;
3698 	struct megasas_irq_context *irq_ctx;
3699 
3700 	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
3701 
3702 	for (i = 0; i < count; i++) {
3703 		irq_ctx = &instance->irq_context[i];
3704 		irq_poll_enable(&irq_ctx->irqpoll);
3705 	}
3706 }
3707 
3708 /**
3709  * megasas_sync_irqs -	Synchronizes all IRQs owned by adapter
3710  * @instance:			Adapter soft state
3711  */
3712 static void megasas_sync_irqs(unsigned long instance_addr)
3713 {
3714 	u32 count, i;
3715 	struct megasas_instance *instance =
3716 		(struct megasas_instance *)instance_addr;
3717 	struct megasas_irq_context *irq_ctx;
3718 
3719 	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
3720 
3721 	for (i = 0; i < count; i++) {
3722 		synchronize_irq(pci_irq_vector(instance->pdev, i));
3723 		irq_ctx = &instance->irq_context[i];
3724 		irq_poll_disable(&irq_ctx->irqpoll);
3725 		if (irq_ctx->irq_poll_scheduled) {
3726 			irq_ctx->irq_poll_scheduled = false;
3727 			enable_irq(irq_ctx->os_irq);
3728 		}
3729 	}
3730 }
3731 
3732 /**
3733  * megasas_irqpoll() - process a queue for completed reply descriptors
3734  * @irqpoll:	IRQ poll structure associated with queue to poll.
3735  * @budget:	Threshold of reply descriptors to process per poll.
3736  *
3737  * Return: The number of entries processed.
3738  */
3739 
3740 int megasas_irqpoll(struct irq_poll *irqpoll, int budget)
3741 {
3742 	struct megasas_irq_context *irq_ctx;
3743 	struct megasas_instance *instance;
3744 	int num_entries;
3745 
3746 	irq_ctx = container_of(irqpoll, struct megasas_irq_context, irqpoll);
3747 	instance = irq_ctx->instance;
3748 
3749 	if (irq_ctx->irq_line_enable) {
3750 		disable_irq(irq_ctx->os_irq);
3751 		irq_ctx->irq_line_enable = false;
3752 	}
3753 
3754 	num_entries = complete_cmd_fusion(instance, irq_ctx->MSIxIndex, irq_ctx);
3755 	if (num_entries < budget) {
3756 		irq_poll_complete(irqpoll);
3757 		irq_ctx->irq_poll_scheduled = false;
3758 		enable_irq(irq_ctx->os_irq);
3759 	}
3760 
3761 	return num_entries;
3762 }
3763 
3764 /**
3765  * megasas_complete_cmd_dpc_fusion -	Completes command
3766  * @instance:			Adapter soft state
3767  *
3768  * Tasklet to complete cmds
3769  */
3770 static void
3771 megasas_complete_cmd_dpc_fusion(unsigned long instance_addr)
3772 {
3773 	struct megasas_instance *instance =
3774 		(struct megasas_instance *)instance_addr;
3775 	u32 count, MSIxIndex;
3776 
3777 	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
3778 
3779 	/* If we have already declared adapter dead, donot complete cmds */
3780 	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
3781 		return;
3782 
3783 	for (MSIxIndex = 0 ; MSIxIndex < count; MSIxIndex++)
3784 		complete_cmd_fusion(instance, MSIxIndex, NULL);
3785 }
3786 
3787 /**
3788  * megasas_isr_fusion - isr entry point
3789  */
3790 static irqreturn_t megasas_isr_fusion(int irq, void *devp)
3791 {
3792 	struct megasas_irq_context *irq_context = devp;
3793 	struct megasas_instance *instance = irq_context->instance;
3794 	u32 mfiStatus;
3795 
3796 	if (instance->mask_interrupts)
3797 		return IRQ_NONE;
3798 
3799 #if defined(ENABLE_IRQ_POLL)
3800 	if (irq_context->irq_poll_scheduled)
3801 		return IRQ_HANDLED;
3802 #endif
3803 
3804 	if (!instance->msix_vectors) {
3805 		mfiStatus = instance->instancet->clear_intr(instance);
3806 		if (!mfiStatus)
3807 			return IRQ_NONE;
3808 	}
3809 
3810 	/* If we are resetting, bail */
3811 	if (test_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags)) {
3812 		instance->instancet->clear_intr(instance);
3813 		return IRQ_HANDLED;
3814 	}
3815 
3816 	return complete_cmd_fusion(instance, irq_context->MSIxIndex, irq_context)
3817 			? IRQ_HANDLED : IRQ_NONE;
3818 }
3819 
3820 /**
3821  * build_mpt_mfi_pass_thru - builds a cmd fo MFI Pass thru
3822  * @instance:			Adapter soft state
3823  * mfi_cmd:			megasas_cmd pointer
3824  *
3825  */
3826 static void
3827 build_mpt_mfi_pass_thru(struct megasas_instance *instance,
3828 			struct megasas_cmd *mfi_cmd)
3829 {
3830 	struct MPI25_IEEE_SGE_CHAIN64 *mpi25_ieee_chain;
3831 	struct MPI2_RAID_SCSI_IO_REQUEST *io_req;
3832 	struct megasas_cmd_fusion *cmd;
3833 	struct fusion_context *fusion;
3834 	struct megasas_header *frame_hdr = &mfi_cmd->frame->hdr;
3835 
3836 	fusion = instance->ctrl_context;
3837 
3838 	cmd = megasas_get_cmd_fusion(instance,
3839 			instance->max_scsi_cmds + mfi_cmd->index);
3840 
3841 	/*  Save the smid. To be used for returning the cmd */
3842 	mfi_cmd->context.smid = cmd->index;
3843 
3844 	/*
3845 	 * For cmds where the flag is set, store the flag and check
3846 	 * on completion. For cmds with this flag, don't call
3847 	 * megasas_complete_cmd
3848 	 */
3849 
3850 	if (frame_hdr->flags & cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE))
3851 		mfi_cmd->flags |= DRV_DCMD_POLLED_MODE;
3852 
3853 	io_req = cmd->io_request;
3854 
3855 	if (instance->adapter_type >= INVADER_SERIES) {
3856 		struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr_end =
3857 			(struct MPI25_IEEE_SGE_CHAIN64 *)&io_req->SGL;
3858 		sgl_ptr_end += fusion->max_sge_in_main_msg - 1;
3859 		sgl_ptr_end->Flags = 0;
3860 	}
3861 
3862 	mpi25_ieee_chain =
3863 	  (struct MPI25_IEEE_SGE_CHAIN64 *)&io_req->SGL.IeeeChain;
3864 
3865 	io_req->Function    = MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST;
3866 	io_req->SGLOffset0  = offsetof(struct MPI2_RAID_SCSI_IO_REQUEST,
3867 				       SGL) / 4;
3868 	io_req->ChainOffset = fusion->chain_offset_mfi_pthru;
3869 
3870 	mpi25_ieee_chain->Address = cpu_to_le64(mfi_cmd->frame_phys_addr);
3871 
3872 	mpi25_ieee_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3873 		MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR;
3874 
3875 	mpi25_ieee_chain->Length = cpu_to_le32(instance->mfi_frame_size);
3876 }
3877 
3878 /**
3879  * build_mpt_cmd - Calls helper function to build a cmd MFI Pass thru cmd
3880  * @instance:			Adapter soft state
3881  * @cmd:			mfi cmd to build
3882  *
3883  */
3884 static union MEGASAS_REQUEST_DESCRIPTOR_UNION *
3885 build_mpt_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
3886 {
3887 	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc = NULL;
3888 	u16 index;
3889 
3890 	build_mpt_mfi_pass_thru(instance, cmd);
3891 	index = cmd->context.smid;
3892 
3893 	req_desc = megasas_get_request_descriptor(instance, index - 1);
3894 
3895 	req_desc->Words = 0;
3896 	req_desc->SCSIIO.RequestFlags = (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
3897 					 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
3898 
3899 	req_desc->SCSIIO.SMID = cpu_to_le16(index);
3900 
3901 	return req_desc;
3902 }
3903 
3904 /**
3905  * megasas_issue_dcmd_fusion - Issues a MFI Pass thru cmd
3906  * @instance:			Adapter soft state
3907  * @cmd:			mfi cmd pointer
3908  *
3909  */
3910 static void
3911 megasas_issue_dcmd_fusion(struct megasas_instance *instance,
3912 			  struct megasas_cmd *cmd)
3913 {
3914 	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
3915 
3916 	req_desc = build_mpt_cmd(instance, cmd);
3917 
3918 	megasas_fire_cmd_fusion(instance, req_desc);
3919 	return;
3920 }
3921 
3922 /**
3923  * megasas_release_fusion -	Reverses the FW initialization
3924  * @instance:			Adapter soft state
3925  */
3926 void
3927 megasas_release_fusion(struct megasas_instance *instance)
3928 {
3929 	megasas_free_ioc_init_cmd(instance);
3930 	megasas_free_cmds(instance);
3931 	megasas_free_cmds_fusion(instance);
3932 
3933 	iounmap(instance->reg_set);
3934 
3935 	pci_release_selected_regions(instance->pdev, 1<<instance->bar);
3936 }
3937 
3938 /**
3939  * megasas_read_fw_status_reg_fusion - returns the current FW status value
3940  * @regs:			MFI register set
3941  */
3942 static u32
3943 megasas_read_fw_status_reg_fusion(struct megasas_instance *instance)
3944 {
3945 	return megasas_readl(instance, &instance->reg_set->outbound_scratch_pad_0);
3946 }
3947 
3948 /**
3949  * megasas_alloc_host_crash_buffer -	Host buffers for Crash dump collection from Firmware
3950  * @instance:				Controller's soft instance
3951  * return:			        Number of allocated host crash buffers
3952  */
3953 static void
3954 megasas_alloc_host_crash_buffer(struct megasas_instance *instance)
3955 {
3956 	unsigned int i;
3957 
3958 	for (i = 0; i < MAX_CRASH_DUMP_SIZE; i++) {
3959 		instance->crash_buf[i] = vzalloc(CRASH_DMA_BUF_SIZE);
3960 		if (!instance->crash_buf[i]) {
3961 			dev_info(&instance->pdev->dev, "Firmware crash dump "
3962 				"memory allocation failed at index %d\n", i);
3963 			break;
3964 		}
3965 	}
3966 	instance->drv_buf_alloc = i;
3967 }
3968 
3969 /**
3970  * megasas_free_host_crash_buffer -	Host buffers for Crash dump collection from Firmware
3971  * @instance:				Controller's soft instance
3972  */
3973 void
3974 megasas_free_host_crash_buffer(struct megasas_instance *instance)
3975 {
3976 	unsigned int i;
3977 	for (i = 0; i < instance->drv_buf_alloc; i++) {
3978 		if (instance->crash_buf[i])
3979 			vfree(instance->crash_buf[i]);
3980 	}
3981 	instance->drv_buf_index = 0;
3982 	instance->drv_buf_alloc = 0;
3983 	instance->fw_crash_state = UNAVAILABLE;
3984 	instance->fw_crash_buffer_size = 0;
3985 }
3986 
3987 /**
3988  * megasas_adp_reset_fusion -	For controller reset
3989  * @regs:				MFI register set
3990  */
3991 static int
3992 megasas_adp_reset_fusion(struct megasas_instance *instance,
3993 			 struct megasas_register_set __iomem *regs)
3994 {
3995 	u32 host_diag, abs_state, retry;
3996 
3997 	/* Now try to reset the chip */
3998 	writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3999 	writel(MPI2_WRSEQ_1ST_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
4000 	writel(MPI2_WRSEQ_2ND_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
4001 	writel(MPI2_WRSEQ_3RD_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
4002 	writel(MPI2_WRSEQ_4TH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
4003 	writel(MPI2_WRSEQ_5TH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
4004 	writel(MPI2_WRSEQ_6TH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
4005 
4006 	/* Check that the diag write enable (DRWE) bit is on */
4007 	host_diag = megasas_readl(instance, &instance->reg_set->fusion_host_diag);
4008 	retry = 0;
4009 	while (!(host_diag & HOST_DIAG_WRITE_ENABLE)) {
4010 		msleep(100);
4011 		host_diag = megasas_readl(instance,
4012 					  &instance->reg_set->fusion_host_diag);
4013 		if (retry++ == 100) {
4014 			dev_warn(&instance->pdev->dev,
4015 				"Host diag unlock failed from %s %d\n",
4016 				__func__, __LINE__);
4017 			break;
4018 		}
4019 	}
4020 	if (!(host_diag & HOST_DIAG_WRITE_ENABLE))
4021 		return -1;
4022 
4023 	/* Send chip reset command */
4024 	writel(host_diag | HOST_DIAG_RESET_ADAPTER,
4025 		&instance->reg_set->fusion_host_diag);
4026 	msleep(3000);
4027 
4028 	/* Make sure reset adapter bit is cleared */
4029 	host_diag = megasas_readl(instance, &instance->reg_set->fusion_host_diag);
4030 	retry = 0;
4031 	while (host_diag & HOST_DIAG_RESET_ADAPTER) {
4032 		msleep(100);
4033 		host_diag = megasas_readl(instance,
4034 					  &instance->reg_set->fusion_host_diag);
4035 		if (retry++ == 1000) {
4036 			dev_warn(&instance->pdev->dev,
4037 				"Diag reset adapter never cleared %s %d\n",
4038 				__func__, __LINE__);
4039 			break;
4040 		}
4041 	}
4042 	if (host_diag & HOST_DIAG_RESET_ADAPTER)
4043 		return -1;
4044 
4045 	abs_state = instance->instancet->read_fw_status_reg(instance)
4046 			& MFI_STATE_MASK;
4047 	retry = 0;
4048 
4049 	while ((abs_state <= MFI_STATE_FW_INIT) && (retry++ < 1000)) {
4050 		msleep(100);
4051 		abs_state = instance->instancet->
4052 			read_fw_status_reg(instance) & MFI_STATE_MASK;
4053 	}
4054 	if (abs_state <= MFI_STATE_FW_INIT) {
4055 		dev_warn(&instance->pdev->dev,
4056 			"fw state < MFI_STATE_FW_INIT, state = 0x%x %s %d\n",
4057 			abs_state, __func__, __LINE__);
4058 		return -1;
4059 	}
4060 
4061 	return 0;
4062 }
4063 
4064 /**
4065  * megasas_check_reset_fusion -	For controller reset check
4066  * @regs:				MFI register set
4067  */
4068 static int
4069 megasas_check_reset_fusion(struct megasas_instance *instance,
4070 			   struct megasas_register_set __iomem *regs)
4071 {
4072 	return 0;
4073 }
4074 
4075 /**
4076  * megasas_trigger_snap_dump -	Trigger snap dump in FW
4077  * @instance:			Soft instance of adapter
4078  */
4079 static inline void megasas_trigger_snap_dump(struct megasas_instance *instance)
4080 {
4081 	int j;
4082 	u32 fw_state, abs_state;
4083 
4084 	if (!instance->disableOnlineCtrlReset) {
4085 		dev_info(&instance->pdev->dev, "Trigger snap dump\n");
4086 		writel(MFI_ADP_TRIGGER_SNAP_DUMP,
4087 		       &instance->reg_set->doorbell);
4088 		readl(&instance->reg_set->doorbell);
4089 	}
4090 
4091 	for (j = 0; j < instance->snapdump_wait_time; j++) {
4092 		abs_state = instance->instancet->read_fw_status_reg(instance);
4093 		fw_state = abs_state & MFI_STATE_MASK;
4094 		if (fw_state == MFI_STATE_FAULT) {
4095 			dev_printk(KERN_ERR, &instance->pdev->dev,
4096 				   "FW in FAULT state Fault code:0x%x subcode:0x%x func:%s\n",
4097 				   abs_state & MFI_STATE_FAULT_CODE,
4098 				   abs_state & MFI_STATE_FAULT_SUBCODE, __func__);
4099 			return;
4100 		}
4101 		msleep(1000);
4102 	}
4103 }
4104 
4105 /* This function waits for outstanding commands on fusion to complete */
4106 static int
4107 megasas_wait_for_outstanding_fusion(struct megasas_instance *instance,
4108 				    int reason, int *convert)
4109 {
4110 	int i, outstanding, retval = 0, hb_seconds_missed = 0;
4111 	u32 fw_state, abs_state;
4112 	u32 waittime_for_io_completion;
4113 
4114 	waittime_for_io_completion =
4115 		min_t(u32, resetwaittime,
4116 			(resetwaittime - instance->snapdump_wait_time));
4117 
4118 	if (reason == MFI_IO_TIMEOUT_OCR) {
4119 		dev_info(&instance->pdev->dev,
4120 			"MFI command is timed out\n");
4121 		megasas_complete_cmd_dpc_fusion((unsigned long)instance);
4122 		if (instance->snapdump_wait_time)
4123 			megasas_trigger_snap_dump(instance);
4124 		retval = 1;
4125 		goto out;
4126 	}
4127 
4128 	for (i = 0; i < waittime_for_io_completion; i++) {
4129 		/* Check if firmware is in fault state */
4130 		abs_state = instance->instancet->read_fw_status_reg(instance);
4131 		fw_state = abs_state & MFI_STATE_MASK;
4132 		if (fw_state == MFI_STATE_FAULT) {
4133 			dev_printk(KERN_ERR, &instance->pdev->dev,
4134 				   "FW in FAULT state Fault code:0x%x subcode:0x%x func:%s\n",
4135 				   abs_state & MFI_STATE_FAULT_CODE,
4136 				   abs_state & MFI_STATE_FAULT_SUBCODE, __func__);
4137 			megasas_complete_cmd_dpc_fusion((unsigned long)instance);
4138 			if (instance->requestorId && reason) {
4139 				dev_warn(&instance->pdev->dev, "SR-IOV Found FW in FAULT"
4140 				" state while polling during"
4141 				" I/O timeout handling for %d\n",
4142 				instance->host->host_no);
4143 				*convert = 1;
4144 			}
4145 
4146 			retval = 1;
4147 			goto out;
4148 		}
4149 
4150 
4151 		/* If SR-IOV VF mode & heartbeat timeout, don't wait */
4152 		if (instance->requestorId && !reason) {
4153 			retval = 1;
4154 			goto out;
4155 		}
4156 
4157 		/* If SR-IOV VF mode & I/O timeout, check for HB timeout */
4158 		if (instance->requestorId && (reason == SCSIIO_TIMEOUT_OCR)) {
4159 			if (instance->hb_host_mem->HB.fwCounter !=
4160 			    instance->hb_host_mem->HB.driverCounter) {
4161 				instance->hb_host_mem->HB.driverCounter =
4162 					instance->hb_host_mem->HB.fwCounter;
4163 				hb_seconds_missed = 0;
4164 			} else {
4165 				hb_seconds_missed++;
4166 				if (hb_seconds_missed ==
4167 				    (MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF/HZ)) {
4168 					dev_warn(&instance->pdev->dev, "SR-IOV:"
4169 					       " Heartbeat never completed "
4170 					       " while polling during I/O "
4171 					       " timeout handling for "
4172 					       "scsi%d.\n",
4173 					       instance->host->host_no);
4174 					       *convert = 1;
4175 					       retval = 1;
4176 					       goto out;
4177 				}
4178 			}
4179 		}
4180 
4181 		megasas_complete_cmd_dpc_fusion((unsigned long)instance);
4182 		outstanding = atomic_read(&instance->fw_outstanding);
4183 		if (!outstanding)
4184 			goto out;
4185 
4186 		if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
4187 			dev_notice(&instance->pdev->dev, "[%2d]waiting for %d "
4188 			       "commands to complete for scsi%d\n", i,
4189 			       outstanding, instance->host->host_no);
4190 		}
4191 		msleep(1000);
4192 	}
4193 
4194 	if (instance->snapdump_wait_time) {
4195 		megasas_trigger_snap_dump(instance);
4196 		retval = 1;
4197 		goto out;
4198 	}
4199 
4200 	if (atomic_read(&instance->fw_outstanding)) {
4201 		dev_err(&instance->pdev->dev, "pending commands remain after waiting, "
4202 		       "will reset adapter scsi%d.\n",
4203 		       instance->host->host_no);
4204 		*convert = 1;
4205 		retval = 1;
4206 	}
4207 
4208 out:
4209 	return retval;
4210 }
4211 
4212 void  megasas_reset_reply_desc(struct megasas_instance *instance)
4213 {
4214 	int i, j, count;
4215 	struct fusion_context *fusion;
4216 	union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
4217 
4218 	fusion = instance->ctrl_context;
4219 	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
4220 	for (i = 0 ; i < count ; i++) {
4221 		fusion->last_reply_idx[i] = 0;
4222 		reply_desc = fusion->reply_frames_desc[i];
4223 		for (j = 0 ; j < fusion->reply_q_depth; j++, reply_desc++)
4224 			reply_desc->Words = cpu_to_le64(ULLONG_MAX);
4225 	}
4226 }
4227 
4228 /*
4229  * megasas_refire_mgmt_cmd :	Re-fire management commands
4230  * @instance:				Controller's soft instance
4231 */
4232 void megasas_refire_mgmt_cmd(struct megasas_instance *instance,
4233 			     bool return_ioctl)
4234 {
4235 	int j;
4236 	struct megasas_cmd_fusion *cmd_fusion;
4237 	struct fusion_context *fusion;
4238 	struct megasas_cmd *cmd_mfi;
4239 	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
4240 	u16 smid;
4241 	bool refire_cmd = 0;
4242 	u8 result;
4243 	u32 opcode = 0;
4244 
4245 	fusion = instance->ctrl_context;
4246 
4247 	/* Re-fire management commands.
4248 	 * Do not traverse complet MPT frame pool. Start from max_scsi_cmds.
4249 	 */
4250 	for (j = instance->max_scsi_cmds ; j < instance->max_fw_cmds; j++) {
4251 		cmd_fusion = fusion->cmd_list[j];
4252 		cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
4253 		smid = le16_to_cpu(cmd_mfi->context.smid);
4254 		result = REFIRE_CMD;
4255 
4256 		if (!smid)
4257 			continue;
4258 
4259 		req_desc = megasas_get_request_descriptor(instance, smid - 1);
4260 
4261 		switch (cmd_mfi->frame->hdr.cmd) {
4262 		case MFI_CMD_DCMD:
4263 			opcode = le32_to_cpu(cmd_mfi->frame->dcmd.opcode);
4264 			 /* Do not refire shutdown command */
4265 			if (opcode == MR_DCMD_CTRL_SHUTDOWN) {
4266 				cmd_mfi->frame->dcmd.cmd_status = MFI_STAT_OK;
4267 				result = COMPLETE_CMD;
4268 				break;
4269 			}
4270 
4271 			refire_cmd = ((opcode != MR_DCMD_LD_MAP_GET_INFO)) &&
4272 				      (opcode != MR_DCMD_SYSTEM_PD_MAP_GET_INFO) &&
4273 				      !(cmd_mfi->flags & DRV_DCMD_SKIP_REFIRE);
4274 
4275 			if (!refire_cmd)
4276 				result = RETURN_CMD;
4277 
4278 			break;
4279 		case MFI_CMD_NVME:
4280 			if (!instance->support_nvme_passthru) {
4281 				cmd_mfi->frame->hdr.cmd_status = MFI_STAT_INVALID_CMD;
4282 				result = COMPLETE_CMD;
4283 			}
4284 
4285 			break;
4286 		case MFI_CMD_TOOLBOX:
4287 			if (!instance->support_pci_lane_margining) {
4288 				cmd_mfi->frame->hdr.cmd_status = MFI_STAT_INVALID_CMD;
4289 				result = COMPLETE_CMD;
4290 			}
4291 
4292 			break;
4293 		default:
4294 			break;
4295 		}
4296 
4297 		if (return_ioctl && cmd_mfi->sync_cmd &&
4298 		    cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT) {
4299 			dev_err(&instance->pdev->dev,
4300 				"return -EBUSY from %s %d cmd 0x%x opcode 0x%x\n",
4301 				__func__, __LINE__, cmd_mfi->frame->hdr.cmd,
4302 				le32_to_cpu(cmd_mfi->frame->dcmd.opcode));
4303 			cmd_mfi->cmd_status_drv = DCMD_BUSY;
4304 			result = COMPLETE_CMD;
4305 		}
4306 
4307 		switch (result) {
4308 		case REFIRE_CMD:
4309 			megasas_fire_cmd_fusion(instance, req_desc);
4310 			break;
4311 		case RETURN_CMD:
4312 			megasas_return_cmd(instance, cmd_mfi);
4313 			break;
4314 		case COMPLETE_CMD:
4315 			megasas_complete_cmd(instance, cmd_mfi, DID_OK);
4316 			break;
4317 		}
4318 	}
4319 }
4320 
4321 /*
4322  * megasas_return_polled_cmds: Return polled mode commands back to the pool
4323  *			       before initiating an OCR.
4324  * @instance:                  Controller's soft instance
4325  */
4326 static void
4327 megasas_return_polled_cmds(struct megasas_instance *instance)
4328 {
4329 	int i;
4330 	struct megasas_cmd_fusion *cmd_fusion;
4331 	struct fusion_context *fusion;
4332 	struct megasas_cmd *cmd_mfi;
4333 
4334 	fusion = instance->ctrl_context;
4335 
4336 	for (i = instance->max_scsi_cmds; i < instance->max_fw_cmds; i++) {
4337 		cmd_fusion = fusion->cmd_list[i];
4338 		cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
4339 
4340 		if (cmd_mfi->flags & DRV_DCMD_POLLED_MODE) {
4341 			if (megasas_dbg_lvl & OCR_DEBUG)
4342 				dev_info(&instance->pdev->dev,
4343 					 "%s %d return cmd 0x%x opcode 0x%x\n",
4344 					 __func__, __LINE__, cmd_mfi->frame->hdr.cmd,
4345 					 le32_to_cpu(cmd_mfi->frame->dcmd.opcode));
4346 			cmd_mfi->flags &= ~DRV_DCMD_POLLED_MODE;
4347 			megasas_return_cmd(instance, cmd_mfi);
4348 		}
4349 	}
4350 }
4351 
4352 /*
4353  * megasas_track_scsiio : Track SCSI IOs outstanding to a SCSI device
4354  * @instance: per adapter struct
4355  * @channel: the channel assigned by the OS
4356  * @id: the id assigned by the OS
4357  *
4358  * Returns SUCCESS if no IOs pending to SCSI device, else return FAILED
4359  */
4360 
4361 static int megasas_track_scsiio(struct megasas_instance *instance,
4362 		int id, int channel)
4363 {
4364 	int i, found = 0;
4365 	struct megasas_cmd_fusion *cmd_fusion;
4366 	struct fusion_context *fusion;
4367 	fusion = instance->ctrl_context;
4368 
4369 	for (i = 0 ; i < instance->max_scsi_cmds; i++) {
4370 		cmd_fusion = fusion->cmd_list[i];
4371 		if (cmd_fusion->scmd &&
4372 			(cmd_fusion->scmd->device->id == id &&
4373 			cmd_fusion->scmd->device->channel == channel)) {
4374 			dev_info(&instance->pdev->dev,
4375 				"SCSI commands pending to target"
4376 				"channel %d id %d \tSMID: 0x%x\n",
4377 				channel, id, cmd_fusion->index);
4378 			scsi_print_command(cmd_fusion->scmd);
4379 			found = 1;
4380 			break;
4381 		}
4382 	}
4383 
4384 	return found ? FAILED : SUCCESS;
4385 }
4386 
4387 /**
4388  * megasas_tm_response_code - translation of device response code
4389  * @ioc: per adapter object
4390  * @mpi_reply: MPI reply returned by firmware
4391  *
4392  * Return nothing.
4393  */
4394 static void
4395 megasas_tm_response_code(struct megasas_instance *instance,
4396 		struct MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply)
4397 {
4398 	char *desc;
4399 
4400 	switch (mpi_reply->ResponseCode) {
4401 	case MPI2_SCSITASKMGMT_RSP_TM_COMPLETE:
4402 		desc = "task management request completed";
4403 		break;
4404 	case MPI2_SCSITASKMGMT_RSP_INVALID_FRAME:
4405 		desc = "invalid frame";
4406 		break;
4407 	case MPI2_SCSITASKMGMT_RSP_TM_NOT_SUPPORTED:
4408 		desc = "task management request not supported";
4409 		break;
4410 	case MPI2_SCSITASKMGMT_RSP_TM_FAILED:
4411 		desc = "task management request failed";
4412 		break;
4413 	case MPI2_SCSITASKMGMT_RSP_TM_SUCCEEDED:
4414 		desc = "task management request succeeded";
4415 		break;
4416 	case MPI2_SCSITASKMGMT_RSP_TM_INVALID_LUN:
4417 		desc = "invalid lun";
4418 		break;
4419 	case 0xA:
4420 		desc = "overlapped tag attempted";
4421 		break;
4422 	case MPI2_SCSITASKMGMT_RSP_IO_QUEUED_ON_IOC:
4423 		desc = "task queued, however not sent to target";
4424 		break;
4425 	default:
4426 		desc = "unknown";
4427 		break;
4428 	}
4429 	dev_dbg(&instance->pdev->dev, "response_code(%01x): %s\n",
4430 		mpi_reply->ResponseCode, desc);
4431 	dev_dbg(&instance->pdev->dev,
4432 		"TerminationCount/DevHandle/Function/TaskType/IOCStat/IOCLoginfo"
4433 		" 0x%x/0x%x/0x%x/0x%x/0x%x/0x%x\n",
4434 		mpi_reply->TerminationCount, mpi_reply->DevHandle,
4435 		mpi_reply->Function, mpi_reply->TaskType,
4436 		mpi_reply->IOCStatus, mpi_reply->IOCLogInfo);
4437 }
4438 
4439 /**
4440  * megasas_issue_tm - main routine for sending tm requests
4441  * @instance: per adapter struct
4442  * @device_handle: device handle
4443  * @channel: the channel assigned by the OS
4444  * @id: the id assigned by the OS
4445  * @type: MPI2_SCSITASKMGMT_TASKTYPE__XXX (defined in megaraid_sas_fusion.c)
4446  * @smid_task: smid assigned to the task
4447  * @m_type: TM_MUTEX_ON or TM_MUTEX_OFF
4448  * Context: user
4449  *
4450  * MegaRaid use MPT interface for Task Magement request.
4451  * A generic API for sending task management requests to firmware.
4452  *
4453  * Return SUCCESS or FAILED.
4454  */
4455 static int
4456 megasas_issue_tm(struct megasas_instance *instance, u16 device_handle,
4457 	uint channel, uint id, u16 smid_task, u8 type,
4458 	struct MR_PRIV_DEVICE *mr_device_priv_data)
4459 {
4460 	struct MR_TASK_MANAGE_REQUEST *mr_request;
4461 	struct MPI2_SCSI_TASK_MANAGE_REQUEST *mpi_request;
4462 	unsigned long timeleft;
4463 	struct megasas_cmd_fusion *cmd_fusion;
4464 	struct megasas_cmd *cmd_mfi;
4465 	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
4466 	struct fusion_context *fusion = NULL;
4467 	struct megasas_cmd_fusion *scsi_lookup;
4468 	int rc;
4469 	int timeout = MEGASAS_DEFAULT_TM_TIMEOUT;
4470 	struct MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply;
4471 
4472 	fusion = instance->ctrl_context;
4473 
4474 	cmd_mfi = megasas_get_cmd(instance);
4475 
4476 	if (!cmd_mfi) {
4477 		dev_err(&instance->pdev->dev, "Failed from %s %d\n",
4478 			__func__, __LINE__);
4479 		return -ENOMEM;
4480 	}
4481 
4482 	cmd_fusion = megasas_get_cmd_fusion(instance,
4483 			instance->max_scsi_cmds + cmd_mfi->index);
4484 
4485 	/*  Save the smid. To be used for returning the cmd */
4486 	cmd_mfi->context.smid = cmd_fusion->index;
4487 
4488 	req_desc = megasas_get_request_descriptor(instance,
4489 			(cmd_fusion->index - 1));
4490 
4491 	cmd_fusion->request_desc = req_desc;
4492 	req_desc->Words = 0;
4493 
4494 	mr_request = (struct MR_TASK_MANAGE_REQUEST *) cmd_fusion->io_request;
4495 	memset(mr_request, 0, sizeof(struct MR_TASK_MANAGE_REQUEST));
4496 	mpi_request = (struct MPI2_SCSI_TASK_MANAGE_REQUEST *) &mr_request->TmRequest;
4497 	mpi_request->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
4498 	mpi_request->DevHandle = cpu_to_le16(device_handle);
4499 	mpi_request->TaskType = type;
4500 	mpi_request->TaskMID = cpu_to_le16(smid_task);
4501 	mpi_request->LUN[1] = 0;
4502 
4503 
4504 	req_desc = cmd_fusion->request_desc;
4505 	req_desc->HighPriority.SMID = cpu_to_le16(cmd_fusion->index);
4506 	req_desc->HighPriority.RequestFlags =
4507 		(MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY <<
4508 		MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
4509 	req_desc->HighPriority.MSIxIndex =  0;
4510 	req_desc->HighPriority.LMID = 0;
4511 	req_desc->HighPriority.Reserved1 = 0;
4512 
4513 	if (channel < MEGASAS_MAX_PD_CHANNELS)
4514 		mr_request->tmReqFlags.isTMForPD = 1;
4515 	else
4516 		mr_request->tmReqFlags.isTMForLD = 1;
4517 
4518 	init_completion(&cmd_fusion->done);
4519 	megasas_fire_cmd_fusion(instance, req_desc);
4520 
4521 	switch (type) {
4522 	case MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK:
4523 		timeout = mr_device_priv_data->task_abort_tmo;
4524 		break;
4525 	case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
4526 		timeout = mr_device_priv_data->target_reset_tmo;
4527 		break;
4528 	}
4529 
4530 	timeleft = wait_for_completion_timeout(&cmd_fusion->done, timeout * HZ);
4531 
4532 	if (!timeleft) {
4533 		dev_err(&instance->pdev->dev,
4534 			"task mgmt type 0x%x timed out\n", type);
4535 		cmd_mfi->flags |= DRV_DCMD_SKIP_REFIRE;
4536 		mutex_unlock(&instance->reset_mutex);
4537 		rc = megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR);
4538 		mutex_lock(&instance->reset_mutex);
4539 		return rc;
4540 	}
4541 
4542 	mpi_reply = (struct MPI2_SCSI_TASK_MANAGE_REPLY *) &mr_request->TMReply;
4543 	megasas_tm_response_code(instance, mpi_reply);
4544 
4545 	megasas_return_cmd(instance, cmd_mfi);
4546 	rc = SUCCESS;
4547 	switch (type) {
4548 	case MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK:
4549 		scsi_lookup = fusion->cmd_list[smid_task - 1];
4550 
4551 		if (scsi_lookup->scmd == NULL)
4552 			break;
4553 		else {
4554 			instance->instancet->disable_intr(instance);
4555 			megasas_sync_irqs((unsigned long)instance);
4556 			instance->instancet->enable_intr(instance);
4557 			megasas_enable_irq_poll(instance);
4558 			if (scsi_lookup->scmd == NULL)
4559 				break;
4560 		}
4561 		rc = FAILED;
4562 		break;
4563 
4564 	case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
4565 		if ((channel == 0xFFFFFFFF) && (id == 0xFFFFFFFF))
4566 			break;
4567 		instance->instancet->disable_intr(instance);
4568 		megasas_sync_irqs((unsigned long)instance);
4569 		rc = megasas_track_scsiio(instance, id, channel);
4570 		instance->instancet->enable_intr(instance);
4571 		megasas_enable_irq_poll(instance);
4572 
4573 		break;
4574 	case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
4575 	case MPI2_SCSITASKMGMT_TASKTYPE_QUERY_TASK:
4576 		break;
4577 	default:
4578 		rc = FAILED;
4579 		break;
4580 	}
4581 
4582 	return rc;
4583 
4584 }
4585 
4586 /*
4587  * megasas_fusion_smid_lookup : Look for fusion command correpspodning to SCSI
4588  * @instance: per adapter struct
4589  *
4590  * Return Non Zero index, if SMID found in outstanding commands
4591  */
4592 static u16 megasas_fusion_smid_lookup(struct scsi_cmnd *scmd)
4593 {
4594 	int i, ret = 0;
4595 	struct megasas_instance *instance;
4596 	struct megasas_cmd_fusion *cmd_fusion;
4597 	struct fusion_context *fusion;
4598 
4599 	instance = (struct megasas_instance *)scmd->device->host->hostdata;
4600 
4601 	fusion = instance->ctrl_context;
4602 
4603 	for (i = 0; i < instance->max_scsi_cmds; i++) {
4604 		cmd_fusion = fusion->cmd_list[i];
4605 		if (cmd_fusion->scmd && (cmd_fusion->scmd == scmd)) {
4606 			scmd_printk(KERN_NOTICE, scmd, "Abort request is for"
4607 				" SMID: %d\n", cmd_fusion->index);
4608 			ret = cmd_fusion->index;
4609 			break;
4610 		}
4611 	}
4612 
4613 	return ret;
4614 }
4615 
4616 /*
4617 * megasas_get_tm_devhandle - Get devhandle for TM request
4618 * @sdev-		     OS provided scsi device
4619 *
4620 * Returns-		     devhandle/targetID of SCSI device
4621 */
4622 static u16 megasas_get_tm_devhandle(struct scsi_device *sdev)
4623 {
4624 	u16 pd_index = 0;
4625 	u32 device_id;
4626 	struct megasas_instance *instance;
4627 	struct fusion_context *fusion;
4628 	struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
4629 	u16 devhandle = (u16)ULONG_MAX;
4630 
4631 	instance = (struct megasas_instance *)sdev->host->hostdata;
4632 	fusion = instance->ctrl_context;
4633 
4634 	if (!MEGASAS_IS_LOGICAL(sdev)) {
4635 		if (instance->use_seqnum_jbod_fp) {
4636 			pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL)
4637 				    + sdev->id;
4638 			pd_sync = (void *)fusion->pd_seq_sync
4639 					[(instance->pd_seq_map_id - 1) & 1];
4640 			devhandle = pd_sync->seq[pd_index].devHandle;
4641 		} else
4642 			sdev_printk(KERN_ERR, sdev, "Firmware expose tmCapable"
4643 				" without JBOD MAP support from %s %d\n", __func__, __LINE__);
4644 	} else {
4645 		device_id = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL)
4646 				+ sdev->id;
4647 		devhandle = device_id;
4648 	}
4649 
4650 	return devhandle;
4651 }
4652 
4653 /*
4654  * megasas_task_abort_fusion : SCSI task abort function for fusion adapters
4655  * @scmd : pointer to scsi command object
4656  *
4657  * Return SUCCESS, if command aborted else FAILED
4658  */
4659 
4660 int megasas_task_abort_fusion(struct scsi_cmnd *scmd)
4661 {
4662 	struct megasas_instance *instance;
4663 	u16 smid, devhandle;
4664 	int ret;
4665 	struct MR_PRIV_DEVICE *mr_device_priv_data;
4666 	mr_device_priv_data = scmd->device->hostdata;
4667 
4668 	instance = (struct megasas_instance *)scmd->device->host->hostdata;
4669 
4670 	if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
4671 		dev_err(&instance->pdev->dev, "Controller is not OPERATIONAL,"
4672 		"SCSI host:%d\n", instance->host->host_no);
4673 		ret = FAILED;
4674 		return ret;
4675 	}
4676 
4677 	if (!mr_device_priv_data) {
4678 		sdev_printk(KERN_INFO, scmd->device, "device been deleted! "
4679 			"scmd(%p)\n", scmd);
4680 		scmd->result = DID_NO_CONNECT << 16;
4681 		ret = SUCCESS;
4682 		goto out;
4683 	}
4684 
4685 	if (!mr_device_priv_data->is_tm_capable) {
4686 		ret = FAILED;
4687 		goto out;
4688 	}
4689 
4690 	mutex_lock(&instance->reset_mutex);
4691 
4692 	smid = megasas_fusion_smid_lookup(scmd);
4693 
4694 	if (!smid) {
4695 		ret = SUCCESS;
4696 		scmd_printk(KERN_NOTICE, scmd, "Command for which abort is"
4697 			" issued is not found in outstanding commands\n");
4698 		mutex_unlock(&instance->reset_mutex);
4699 		goto out;
4700 	}
4701 
4702 	devhandle = megasas_get_tm_devhandle(scmd->device);
4703 
4704 	if (devhandle == (u16)ULONG_MAX) {
4705 		ret = SUCCESS;
4706 		sdev_printk(KERN_INFO, scmd->device,
4707 			"task abort issued for invalid devhandle\n");
4708 		mutex_unlock(&instance->reset_mutex);
4709 		goto out;
4710 	}
4711 	sdev_printk(KERN_INFO, scmd->device,
4712 		"attempting task abort! scmd(0x%p) tm_dev_handle 0x%x\n",
4713 		scmd, devhandle);
4714 
4715 	mr_device_priv_data->tm_busy = 1;
4716 	ret = megasas_issue_tm(instance, devhandle,
4717 			scmd->device->channel, scmd->device->id, smid,
4718 			MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK,
4719 			mr_device_priv_data);
4720 	mr_device_priv_data->tm_busy = 0;
4721 
4722 	mutex_unlock(&instance->reset_mutex);
4723 	scmd_printk(KERN_INFO, scmd, "task abort %s!! scmd(0x%p)\n",
4724 			((ret == SUCCESS) ? "SUCCESS" : "FAILED"), scmd);
4725 out:
4726 	scsi_print_command(scmd);
4727 	if (megasas_dbg_lvl & TM_DEBUG)
4728 		megasas_dump_fusion_io(scmd);
4729 
4730 	return ret;
4731 }
4732 
4733 /*
4734  * megasas_reset_target_fusion : target reset function for fusion adapters
4735  * scmd: SCSI command pointer
4736  *
4737  * Returns SUCCESS if all commands associated with target aborted else FAILED
4738  */
4739 
4740 int megasas_reset_target_fusion(struct scsi_cmnd *scmd)
4741 {
4742 
4743 	struct megasas_instance *instance;
4744 	int ret = FAILED;
4745 	u16 devhandle;
4746 	struct MR_PRIV_DEVICE *mr_device_priv_data;
4747 	mr_device_priv_data = scmd->device->hostdata;
4748 
4749 	instance = (struct megasas_instance *)scmd->device->host->hostdata;
4750 
4751 	if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
4752 		dev_err(&instance->pdev->dev, "Controller is not OPERATIONAL,"
4753 		"SCSI host:%d\n", instance->host->host_no);
4754 		ret = FAILED;
4755 		return ret;
4756 	}
4757 
4758 	if (!mr_device_priv_data) {
4759 		sdev_printk(KERN_INFO, scmd->device,
4760 			    "device been deleted! scmd: (0x%p)\n", scmd);
4761 		scmd->result = DID_NO_CONNECT << 16;
4762 		ret = SUCCESS;
4763 		goto out;
4764 	}
4765 
4766 	if (!mr_device_priv_data->is_tm_capable) {
4767 		ret = FAILED;
4768 		goto out;
4769 	}
4770 
4771 	mutex_lock(&instance->reset_mutex);
4772 	devhandle = megasas_get_tm_devhandle(scmd->device);
4773 
4774 	if (devhandle == (u16)ULONG_MAX) {
4775 		ret = SUCCESS;
4776 		sdev_printk(KERN_INFO, scmd->device,
4777 			"target reset issued for invalid devhandle\n");
4778 		mutex_unlock(&instance->reset_mutex);
4779 		goto out;
4780 	}
4781 
4782 	sdev_printk(KERN_INFO, scmd->device,
4783 		"attempting target reset! scmd(0x%p) tm_dev_handle: 0x%x\n",
4784 		scmd, devhandle);
4785 	mr_device_priv_data->tm_busy = 1;
4786 	ret = megasas_issue_tm(instance, devhandle,
4787 			scmd->device->channel, scmd->device->id, 0,
4788 			MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET,
4789 			mr_device_priv_data);
4790 	mr_device_priv_data->tm_busy = 0;
4791 	mutex_unlock(&instance->reset_mutex);
4792 	scmd_printk(KERN_NOTICE, scmd, "target reset %s!!\n",
4793 		(ret == SUCCESS) ? "SUCCESS" : "FAILED");
4794 
4795 out:
4796 	return ret;
4797 }
4798 
4799 /*SRIOV get other instance in cluster if any*/
4800 static struct
4801 megasas_instance *megasas_get_peer_instance(struct megasas_instance *instance)
4802 {
4803 	int i;
4804 
4805 	for (i = 0; i < MAX_MGMT_ADAPTERS; i++) {
4806 		if (megasas_mgmt_info.instance[i] &&
4807 			(megasas_mgmt_info.instance[i] != instance) &&
4808 			 megasas_mgmt_info.instance[i]->requestorId &&
4809 			 megasas_mgmt_info.instance[i]->peerIsPresent &&
4810 			(memcmp((megasas_mgmt_info.instance[i]->clusterId),
4811 			instance->clusterId, MEGASAS_CLUSTER_ID_SIZE) == 0))
4812 			return megasas_mgmt_info.instance[i];
4813 	}
4814 	return NULL;
4815 }
4816 
4817 /* Check for a second path that is currently UP */
4818 int megasas_check_mpio_paths(struct megasas_instance *instance,
4819 	struct scsi_cmnd *scmd)
4820 {
4821 	struct megasas_instance *peer_instance = NULL;
4822 	int retval = (DID_REQUEUE << 16);
4823 
4824 	if (instance->peerIsPresent) {
4825 		peer_instance = megasas_get_peer_instance(instance);
4826 		if ((peer_instance) &&
4827 			(atomic_read(&peer_instance->adprecovery) ==
4828 			MEGASAS_HBA_OPERATIONAL))
4829 			retval = (DID_NO_CONNECT << 16);
4830 	}
4831 	return retval;
4832 }
4833 
4834 /* Core fusion reset function */
4835 int megasas_reset_fusion(struct Scsi_Host *shost, int reason)
4836 {
4837 	int retval = SUCCESS, i, j, convert = 0;
4838 	struct megasas_instance *instance;
4839 	struct megasas_cmd_fusion *cmd_fusion, *r1_cmd;
4840 	struct fusion_context *fusion;
4841 	u32 abs_state, status_reg, reset_adapter, fpio_count = 0;
4842 	u32 io_timeout_in_crash_mode = 0;
4843 	struct scsi_cmnd *scmd_local = NULL;
4844 	struct scsi_device *sdev;
4845 	int ret_target_prop = DCMD_FAILED;
4846 	bool is_target_prop = false;
4847 	bool do_adp_reset = true;
4848 	int max_reset_tries = MEGASAS_FUSION_MAX_RESET_TRIES;
4849 
4850 	instance = (struct megasas_instance *)shost->hostdata;
4851 	fusion = instance->ctrl_context;
4852 
4853 	mutex_lock(&instance->reset_mutex);
4854 
4855 	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
4856 		dev_warn(&instance->pdev->dev, "Hardware critical error, "
4857 		       "returning FAILED for scsi%d.\n",
4858 			instance->host->host_no);
4859 		mutex_unlock(&instance->reset_mutex);
4860 		return FAILED;
4861 	}
4862 	status_reg = instance->instancet->read_fw_status_reg(instance);
4863 	abs_state = status_reg & MFI_STATE_MASK;
4864 
4865 	/* IO timeout detected, forcibly put FW in FAULT state */
4866 	if (abs_state != MFI_STATE_FAULT && instance->crash_dump_buf &&
4867 		instance->crash_dump_app_support && reason) {
4868 		dev_info(&instance->pdev->dev, "IO/DCMD timeout is detected, "
4869 			"forcibly FAULT Firmware\n");
4870 		atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
4871 		status_reg = megasas_readl(instance, &instance->reg_set->doorbell);
4872 		writel(status_reg | MFI_STATE_FORCE_OCR,
4873 			&instance->reg_set->doorbell);
4874 		readl(&instance->reg_set->doorbell);
4875 		mutex_unlock(&instance->reset_mutex);
4876 		do {
4877 			ssleep(3);
4878 			io_timeout_in_crash_mode++;
4879 			dev_dbg(&instance->pdev->dev, "waiting for [%d] "
4880 				"seconds for crash dump collection and OCR "
4881 				"to be done\n", (io_timeout_in_crash_mode * 3));
4882 		} while ((atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) &&
4883 			(io_timeout_in_crash_mode < 80));
4884 
4885 		if (atomic_read(&instance->adprecovery) == MEGASAS_HBA_OPERATIONAL) {
4886 			dev_info(&instance->pdev->dev, "OCR done for IO "
4887 				"timeout case\n");
4888 			retval = SUCCESS;
4889 		} else {
4890 			dev_info(&instance->pdev->dev, "Controller is not "
4891 				"operational after 240 seconds wait for IO "
4892 				"timeout case in FW crash dump mode\n do "
4893 				"OCR/kill adapter\n");
4894 			retval = megasas_reset_fusion(shost, 0);
4895 		}
4896 		return retval;
4897 	}
4898 
4899 	if (instance->requestorId && !instance->skip_heartbeat_timer_del)
4900 		del_timer_sync(&instance->sriov_heartbeat_timer);
4901 	set_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
4902 	set_bit(MEGASAS_FUSION_OCR_NOT_POSSIBLE, &instance->reset_flags);
4903 	atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_POLLING);
4904 	instance->instancet->disable_intr(instance);
4905 	megasas_sync_irqs((unsigned long)instance);
4906 
4907 	/* First try waiting for commands to complete */
4908 	if (megasas_wait_for_outstanding_fusion(instance, reason,
4909 						&convert)) {
4910 		atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
4911 		dev_warn(&instance->pdev->dev, "resetting fusion "
4912 		       "adapter scsi%d.\n", instance->host->host_no);
4913 		if (convert)
4914 			reason = 0;
4915 
4916 		if (megasas_dbg_lvl & OCR_DEBUG)
4917 			dev_info(&instance->pdev->dev, "\nPending SCSI commands:\n");
4918 
4919 		/* Now return commands back to the OS */
4920 		for (i = 0 ; i < instance->max_scsi_cmds; i++) {
4921 			cmd_fusion = fusion->cmd_list[i];
4922 			/*check for extra commands issued by driver*/
4923 			if (instance->adapter_type >= VENTURA_SERIES) {
4924 				r1_cmd = fusion->cmd_list[i + instance->max_fw_cmds];
4925 				megasas_return_cmd_fusion(instance, r1_cmd);
4926 			}
4927 			scmd_local = cmd_fusion->scmd;
4928 			if (cmd_fusion->scmd) {
4929 				if (megasas_dbg_lvl & OCR_DEBUG) {
4930 					sdev_printk(KERN_INFO,
4931 						cmd_fusion->scmd->device, "SMID: 0x%x\n",
4932 						cmd_fusion->index);
4933 					megasas_dump_fusion_io(cmd_fusion->scmd);
4934 				}
4935 
4936 				if (cmd_fusion->io_request->Function ==
4937 					MPI2_FUNCTION_SCSI_IO_REQUEST)
4938 					fpio_count++;
4939 
4940 				scmd_local->result =
4941 					megasas_check_mpio_paths(instance,
4942 							scmd_local);
4943 				if (instance->ldio_threshold &&
4944 					megasas_cmd_type(scmd_local) == READ_WRITE_LDIO)
4945 					atomic_dec(&instance->ldio_outstanding);
4946 				megasas_return_cmd_fusion(instance, cmd_fusion);
4947 				scsi_dma_unmap(scmd_local);
4948 				scmd_local->scsi_done(scmd_local);
4949 			}
4950 		}
4951 
4952 		dev_info(&instance->pdev->dev, "Outstanding fastpath IOs: %d\n",
4953 			fpio_count);
4954 
4955 		atomic_set(&instance->fw_outstanding, 0);
4956 
4957 		status_reg = instance->instancet->read_fw_status_reg(instance);
4958 		abs_state = status_reg & MFI_STATE_MASK;
4959 		reset_adapter = status_reg & MFI_RESET_ADAPTER;
4960 		if (instance->disableOnlineCtrlReset ||
4961 		    (abs_state == MFI_STATE_FAULT && !reset_adapter)) {
4962 			/* Reset not supported, kill adapter */
4963 			dev_warn(&instance->pdev->dev, "Reset not supported"
4964 			       ", killing adapter scsi%d.\n",
4965 				instance->host->host_no);
4966 			goto kill_hba;
4967 		}
4968 
4969 		/* Let SR-IOV VF & PF sync up if there was a HB failure */
4970 		if (instance->requestorId && !reason) {
4971 			msleep(MEGASAS_OCR_SETTLE_TIME_VF);
4972 			do_adp_reset = false;
4973 			max_reset_tries = MEGASAS_SRIOV_MAX_RESET_TRIES_VF;
4974 		}
4975 
4976 		/* Now try to reset the chip */
4977 		for (i = 0; i < max_reset_tries; i++) {
4978 			/*
4979 			 * Do adp reset and wait for
4980 			 * controller to transition to ready
4981 			 */
4982 			if (megasas_adp_reset_wait_for_ready(instance,
4983 				do_adp_reset, 1) == FAILED)
4984 				continue;
4985 
4986 			/* Wait for FW to become ready */
4987 			if (megasas_transition_to_ready(instance, 1)) {
4988 				dev_warn(&instance->pdev->dev,
4989 					"Failed to transition controller to ready for "
4990 					"scsi%d.\n", instance->host->host_no);
4991 				continue;
4992 			}
4993 			megasas_reset_reply_desc(instance);
4994 			megasas_fusion_update_can_queue(instance, OCR_CONTEXT);
4995 
4996 			if (megasas_ioc_init_fusion(instance)) {
4997 				continue;
4998 			}
4999 
5000 			if (megasas_get_ctrl_info(instance)) {
5001 				dev_info(&instance->pdev->dev,
5002 					"Failed from %s %d\n",
5003 					__func__, __LINE__);
5004 				goto kill_hba;
5005 			}
5006 
5007 			megasas_refire_mgmt_cmd(instance,
5008 						(i == (MEGASAS_FUSION_MAX_RESET_TRIES - 1)
5009 							? 1 : 0));
5010 
5011 			/* Reset load balance info */
5012 			if (fusion->load_balance_info)
5013 				memset(fusion->load_balance_info, 0,
5014 				       (sizeof(struct LD_LOAD_BALANCE_INFO) *
5015 				       MAX_LOGICAL_DRIVES_EXT));
5016 
5017 			if (!megasas_get_map_info(instance)) {
5018 				megasas_sync_map_info(instance);
5019 			} else {
5020 				/*
5021 				 * Return pending polled mode cmds before
5022 				 * retrying OCR
5023 				 */
5024 				megasas_return_polled_cmds(instance);
5025 				continue;
5026 			}
5027 
5028 			megasas_setup_jbod_map(instance);
5029 
5030 			/* reset stream detection array */
5031 			if (instance->adapter_type >= VENTURA_SERIES) {
5032 				for (j = 0; j < MAX_LOGICAL_DRIVES_EXT; ++j) {
5033 					memset(fusion->stream_detect_by_ld[j],
5034 					0, sizeof(struct LD_STREAM_DETECT));
5035 				 fusion->stream_detect_by_ld[j]->mru_bit_map
5036 						= MR_STREAM_BITMAP;
5037 				}
5038 			}
5039 
5040 			clear_bit(MEGASAS_FUSION_IN_RESET,
5041 				  &instance->reset_flags);
5042 			instance->instancet->enable_intr(instance);
5043 			megasas_enable_irq_poll(instance);
5044 			shost_for_each_device(sdev, shost) {
5045 				if ((instance->tgt_prop) &&
5046 				    (instance->nvme_page_size))
5047 					ret_target_prop = megasas_get_target_prop(instance, sdev);
5048 
5049 				is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false;
5050 				megasas_set_dynamic_target_properties(sdev, is_target_prop);
5051 			}
5052 
5053 			status_reg = instance->instancet->read_fw_status_reg
5054 					(instance);
5055 			abs_state = status_reg & MFI_STATE_MASK;
5056 			if (abs_state != MFI_STATE_OPERATIONAL) {
5057 				dev_info(&instance->pdev->dev,
5058 					 "Adapter is not OPERATIONAL, state 0x%x for scsi:%d\n",
5059 					 abs_state, instance->host->host_no);
5060 				goto out;
5061 			}
5062 			atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
5063 
5064 			dev_info(&instance->pdev->dev,
5065 				 "Adapter is OPERATIONAL for scsi:%d\n",
5066 				 instance->host->host_no);
5067 
5068 			/* Restart SR-IOV heartbeat */
5069 			if (instance->requestorId) {
5070 				if (!megasas_sriov_start_heartbeat(instance, 0))
5071 					megasas_start_timer(instance);
5072 				else
5073 					instance->skip_heartbeat_timer_del = 1;
5074 			}
5075 
5076 			if (instance->crash_dump_drv_support &&
5077 				instance->crash_dump_app_support)
5078 				megasas_set_crash_dump_params(instance,
5079 					MR_CRASH_BUF_TURN_ON);
5080 			else
5081 				megasas_set_crash_dump_params(instance,
5082 					MR_CRASH_BUF_TURN_OFF);
5083 
5084 			if (instance->snapdump_wait_time) {
5085 				megasas_get_snapdump_properties(instance);
5086 				dev_info(&instance->pdev->dev,
5087 					 "Snap dump wait time\t: %d\n",
5088 					 instance->snapdump_wait_time);
5089 			}
5090 
5091 			retval = SUCCESS;
5092 
5093 			/* Adapter reset completed successfully */
5094 			dev_warn(&instance->pdev->dev,
5095 				 "Reset successful for scsi%d.\n",
5096 				 instance->host->host_no);
5097 
5098 			goto out;
5099 		}
5100 		/* Reset failed, kill the adapter */
5101 		dev_warn(&instance->pdev->dev, "Reset failed, killing "
5102 		       "adapter scsi%d.\n", instance->host->host_no);
5103 		goto kill_hba;
5104 	} else {
5105 		/* For VF: Restart HB timer if we didn't OCR */
5106 		if (instance->requestorId) {
5107 			megasas_start_timer(instance);
5108 		}
5109 		clear_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
5110 		instance->instancet->enable_intr(instance);
5111 		megasas_enable_irq_poll(instance);
5112 		atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
5113 		goto out;
5114 	}
5115 kill_hba:
5116 	megaraid_sas_kill_hba(instance);
5117 	megasas_enable_irq_poll(instance);
5118 	instance->skip_heartbeat_timer_del = 1;
5119 	retval = FAILED;
5120 out:
5121 	clear_bit(MEGASAS_FUSION_OCR_NOT_POSSIBLE, &instance->reset_flags);
5122 	mutex_unlock(&instance->reset_mutex);
5123 	return retval;
5124 }
5125 
5126 /* Fusion Crash dump collection */
5127 static void  megasas_fusion_crash_dump(struct megasas_instance *instance)
5128 {
5129 	u32 status_reg;
5130 	u8 partial_copy = 0;
5131 	int wait = 0;
5132 
5133 
5134 	status_reg = instance->instancet->read_fw_status_reg(instance);
5135 
5136 	/*
5137 	 * Allocate host crash buffers to copy data from 1 MB DMA crash buffer
5138 	 * to host crash buffers
5139 	 */
5140 	if (instance->drv_buf_index == 0) {
5141 		/* Buffer is already allocated for old Crash dump.
5142 		 * Do OCR and do not wait for crash dump collection
5143 		 */
5144 		if (instance->drv_buf_alloc) {
5145 			dev_info(&instance->pdev->dev, "earlier crash dump is "
5146 				"not yet copied by application, ignoring this "
5147 				"crash dump and initiating OCR\n");
5148 			status_reg |= MFI_STATE_CRASH_DUMP_DONE;
5149 			writel(status_reg,
5150 				&instance->reg_set->outbound_scratch_pad_0);
5151 			readl(&instance->reg_set->outbound_scratch_pad_0);
5152 			return;
5153 		}
5154 		megasas_alloc_host_crash_buffer(instance);
5155 		dev_info(&instance->pdev->dev, "Number of host crash buffers "
5156 			"allocated: %d\n", instance->drv_buf_alloc);
5157 	}
5158 
5159 	while (!(status_reg & MFI_STATE_CRASH_DUMP_DONE) &&
5160 	       (wait < MEGASAS_WATCHDOG_WAIT_COUNT)) {
5161 		if (!(status_reg & MFI_STATE_DMADONE)) {
5162 			/*
5163 			 * Next crash dump buffer is not yet DMA'd by FW
5164 			 * Check after 10ms. Wait for 1 second for FW to
5165 			 * post the next buffer. If not bail out.
5166 			 */
5167 			wait++;
5168 			msleep(MEGASAS_WAIT_FOR_NEXT_DMA_MSECS);
5169 			status_reg = instance->instancet->read_fw_status_reg(
5170 					instance);
5171 			continue;
5172 		}
5173 
5174 		wait = 0;
5175 		if (instance->drv_buf_index >= instance->drv_buf_alloc) {
5176 			dev_info(&instance->pdev->dev,
5177 				 "Driver is done copying the buffer: %d\n",
5178 				 instance->drv_buf_alloc);
5179 			status_reg |= MFI_STATE_CRASH_DUMP_DONE;
5180 			partial_copy = 1;
5181 			break;
5182 		} else {
5183 			memcpy(instance->crash_buf[instance->drv_buf_index],
5184 			       instance->crash_dump_buf, CRASH_DMA_BUF_SIZE);
5185 			instance->drv_buf_index++;
5186 			status_reg &= ~MFI_STATE_DMADONE;
5187 		}
5188 
5189 		writel(status_reg, &instance->reg_set->outbound_scratch_pad_0);
5190 		readl(&instance->reg_set->outbound_scratch_pad_0);
5191 
5192 		msleep(MEGASAS_WAIT_FOR_NEXT_DMA_MSECS);
5193 		status_reg = instance->instancet->read_fw_status_reg(instance);
5194 	}
5195 
5196 	if (status_reg & MFI_STATE_CRASH_DUMP_DONE) {
5197 		dev_info(&instance->pdev->dev, "Crash Dump is available,number "
5198 			"of copied buffers: %d\n", instance->drv_buf_index);
5199 		instance->fw_crash_buffer_size =  instance->drv_buf_index;
5200 		instance->fw_crash_state = AVAILABLE;
5201 		instance->drv_buf_index = 0;
5202 		writel(status_reg, &instance->reg_set->outbound_scratch_pad_0);
5203 		readl(&instance->reg_set->outbound_scratch_pad_0);
5204 		if (!partial_copy)
5205 			megasas_reset_fusion(instance->host, 0);
5206 	}
5207 }
5208 
5209 
5210 /* Fusion OCR work queue */
5211 void megasas_fusion_ocr_wq(struct work_struct *work)
5212 {
5213 	struct megasas_instance *instance =
5214 		container_of(work, struct megasas_instance, work_init);
5215 
5216 	megasas_reset_fusion(instance->host, 0);
5217 }
5218 
5219 /* Allocate fusion context */
5220 int
5221 megasas_alloc_fusion_context(struct megasas_instance *instance)
5222 {
5223 	struct fusion_context *fusion;
5224 
5225 	instance->ctrl_context = kzalloc(sizeof(struct fusion_context),
5226 					 GFP_KERNEL);
5227 	if (!instance->ctrl_context) {
5228 		dev_err(&instance->pdev->dev, "Failed from %s %d\n",
5229 			__func__, __LINE__);
5230 		return -ENOMEM;
5231 	}
5232 
5233 	fusion = instance->ctrl_context;
5234 
5235 	fusion->log_to_span_pages = get_order(MAX_LOGICAL_DRIVES_EXT *
5236 					      sizeof(LD_SPAN_INFO));
5237 	fusion->log_to_span =
5238 		(PLD_SPAN_INFO)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
5239 						fusion->log_to_span_pages);
5240 	if (!fusion->log_to_span) {
5241 		fusion->log_to_span =
5242 			vzalloc(array_size(MAX_LOGICAL_DRIVES_EXT,
5243 					   sizeof(LD_SPAN_INFO)));
5244 		if (!fusion->log_to_span) {
5245 			dev_err(&instance->pdev->dev, "Failed from %s %d\n",
5246 				__func__, __LINE__);
5247 			return -ENOMEM;
5248 		}
5249 	}
5250 
5251 	fusion->load_balance_info_pages = get_order(MAX_LOGICAL_DRIVES_EXT *
5252 		sizeof(struct LD_LOAD_BALANCE_INFO));
5253 	fusion->load_balance_info =
5254 		(struct LD_LOAD_BALANCE_INFO *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
5255 		fusion->load_balance_info_pages);
5256 	if (!fusion->load_balance_info) {
5257 		fusion->load_balance_info =
5258 			vzalloc(array_size(MAX_LOGICAL_DRIVES_EXT,
5259 					   sizeof(struct LD_LOAD_BALANCE_INFO)));
5260 		if (!fusion->load_balance_info)
5261 			dev_err(&instance->pdev->dev, "Failed to allocate load_balance_info, "
5262 				"continuing without Load Balance support\n");
5263 	}
5264 
5265 	return 0;
5266 }
5267 
5268 void
5269 megasas_free_fusion_context(struct megasas_instance *instance)
5270 {
5271 	struct fusion_context *fusion = instance->ctrl_context;
5272 
5273 	if (fusion) {
5274 		if (fusion->load_balance_info) {
5275 			if (is_vmalloc_addr(fusion->load_balance_info))
5276 				vfree(fusion->load_balance_info);
5277 			else
5278 				free_pages((ulong)fusion->load_balance_info,
5279 					fusion->load_balance_info_pages);
5280 		}
5281 
5282 		if (fusion->log_to_span) {
5283 			if (is_vmalloc_addr(fusion->log_to_span))
5284 				vfree(fusion->log_to_span);
5285 			else
5286 				free_pages((ulong)fusion->log_to_span,
5287 					   fusion->log_to_span_pages);
5288 		}
5289 
5290 		kfree(fusion);
5291 	}
5292 }
5293 
5294 struct megasas_instance_template megasas_instance_template_fusion = {
5295 	.enable_intr = megasas_enable_intr_fusion,
5296 	.disable_intr = megasas_disable_intr_fusion,
5297 	.clear_intr = megasas_clear_intr_fusion,
5298 	.read_fw_status_reg = megasas_read_fw_status_reg_fusion,
5299 	.adp_reset = megasas_adp_reset_fusion,
5300 	.check_reset = megasas_check_reset_fusion,
5301 	.service_isr = megasas_isr_fusion,
5302 	.tasklet = megasas_complete_cmd_dpc_fusion,
5303 	.init_adapter = megasas_init_adapter_fusion,
5304 	.build_and_issue_cmd = megasas_build_and_issue_cmd_fusion,
5305 	.issue_dcmd = megasas_issue_dcmd_fusion,
5306 };
5307