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