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