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