File Index
Files and directories
Sign in
FILE

megaraid_sas_base.c

File preview with syntax highlighting.

linux-6.19.14/drivers/scsi/megaraid/megaraid_sas_base.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 *  Linux MegaRAID driver for SAS based RAID controllers
   4 *
   5 *  Copyright (c) 2003-2013  LSI Corporation
   6 *  Copyright (c) 2013-2016  Avago Technologies
   7 *  Copyright (c) 2016-2018  Broadcom Inc.
   8 *
   9 *  Authors: Broadcom Inc.
  10 *           Sreenivas Bagalkote
  11 *           Sumant Patro
  12 *           Bo Yang
  13 *           Adam Radford
  14 *           Kashyap Desai <kashyap.desai@broadcom.com>
  15 *           Sumit Saxena <sumit.saxena@broadcom.com>
  16 *
  17 *  Send feedback to: megaraidlinux.pdl@broadcom.com
  18 */
  19
  20#include <linux/kernel.h>
  21#include <linux/types.h>
  22#include <linux/pci.h>
  23#include <linux/list.h>
  24#include <linux/moduleparam.h>
  25#include <linux/module.h>
  26#include <linux/spinlock.h>
  27#include <linux/interrupt.h>
  28#include <linux/delay.h>
  29#include <linux/uio.h>
  30#include <linux/slab.h>
  31#include <linux/uaccess.h>
  32#include <linux/unaligned.h>
  33#include <linux/fs.h>
  34#include <linux/compat.h>
  35#include <linux/blkdev.h>
  36#include <linux/mutex.h>
  37#include <linux/poll.h>
  38#include <linux/vmalloc.h>
  39#include <linux/irq_poll.h>
  40
  41#include <scsi/scsi.h>
  42#include <scsi/scsi_cmnd.h>
  43#include <scsi/scsi_device.h>
  44#include <scsi/scsi_host.h>
  45#include <scsi/scsi_tcq.h>
  46#include <scsi/scsi_dbg.h>
  47#include "megaraid_sas_fusion.h"
  48#include "megaraid_sas.h"
  49
  50/*
  51 * Number of sectors per IO command
  52 * Will be set in megasas_init_mfi if user does not provide
  53 */
  54static unsigned int max_sectors;
  55module_param_named(max_sectors, max_sectors, int, 0444);
  56MODULE_PARM_DESC(max_sectors,
  57	"Maximum number of sectors per IO command");
  58
  59static int msix_disable;
  60module_param(msix_disable, int, 0444);
  61MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0");
  62
  63static unsigned int msix_vectors;
  64module_param(msix_vectors, int, 0444);
  65MODULE_PARM_DESC(msix_vectors, "MSI-X max vector count. Default: Set by FW");
  66
  67static int allow_vf_ioctls;
  68module_param(allow_vf_ioctls, int, 0444);
  69MODULE_PARM_DESC(allow_vf_ioctls, "Allow ioctls in SR-IOV VF mode. Default: 0");
  70
  71static unsigned int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH;
  72module_param(throttlequeuedepth, int, 0444);
  73MODULE_PARM_DESC(throttlequeuedepth,
  74	"Adapter queue depth when throttled due to I/O timeout. Default: 16");
  75
  76unsigned int resetwaittime = MEGASAS_RESET_WAIT_TIME;
  77module_param(resetwaittime, int, 0444);
  78MODULE_PARM_DESC(resetwaittime, "Wait time in (1-180s) after I/O timeout before resetting adapter. Default: 180s");
  79
  80static int smp_affinity_enable = 1;
  81module_param(smp_affinity_enable, int, 0444);
  82MODULE_PARM_DESC(smp_affinity_enable, "SMP affinity feature enable/disable Default: enable(1)");
  83
  84static int rdpq_enable = 1;
  85module_param(rdpq_enable, int, 0444);
  86MODULE_PARM_DESC(rdpq_enable, "Allocate reply queue in chunks for large queue depth enable/disable Default: enable(1)");
  87
  88unsigned int dual_qdepth_disable;
  89module_param(dual_qdepth_disable, int, 0444);
  90MODULE_PARM_DESC(dual_qdepth_disable, "Disable dual queue depth feature. Default: 0");
  91
  92static unsigned int scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT;
  93module_param(scmd_timeout, int, 0444);
  94MODULE_PARM_DESC(scmd_timeout, "scsi command timeout (10-90s), default 90s. See megasas_reset_timer.");
  95
  96static int perf_mode = -1;
  97module_param(perf_mode, int, 0444);
  98MODULE_PARM_DESC(perf_mode, "Performance mode (only for Aero adapters), options:\n\t\t"
  99		"0 - balanced: High iops and low latency queues are allocated &\n\t\t"
 100		"interrupt coalescing is enabled only on high iops queues\n\t\t"
 101		"1 - iops: High iops queues are not allocated &\n\t\t"
 102		"interrupt coalescing is enabled on all queues\n\t\t"
 103		"2 - latency: High iops queues are not allocated &\n\t\t"
 104		"interrupt coalescing is disabled on all queues\n\t\t"
 105		"default mode is 'balanced'"
 106		);
 107
 108static int event_log_level = MFI_EVT_CLASS_CRITICAL;
 109module_param(event_log_level, int, 0644);
 110MODULE_PARM_DESC(event_log_level, "Asynchronous event logging level- range is: -2(CLASS_DEBUG) to 4(CLASS_DEAD), Default: 2(CLASS_CRITICAL)");
 111
 112static unsigned int enable_sdev_max_qd;
 113module_param(enable_sdev_max_qd, int, 0444);
 114MODULE_PARM_DESC(enable_sdev_max_qd, "Enable sdev max qd as can_queue. Default: 0");
 115
 116static int poll_queues;
 117module_param(poll_queues, int, 0444);
 118MODULE_PARM_DESC(poll_queues, "Number of queues to be use for io_uring poll mode.\n\t\t"
 119		"This parameter is effective only if host_tagset_enable=1 &\n\t\t"
 120		"It is not applicable for MFI_SERIES. &\n\t\t"
 121		"Driver will work in latency mode. &\n\t\t"
 122		"High iops queues are not allocated &\n\t\t"
 123		);
 124
 125static int host_tagset_enable = 1;
 126module_param(host_tagset_enable, int, 0444);
 127MODULE_PARM_DESC(host_tagset_enable, "Shared host tagset enable/disable Default: enable(1)");
 128
 129MODULE_LICENSE("GPL");
 130MODULE_VERSION(MEGASAS_VERSION);
 131MODULE_AUTHOR("megaraidlinux.pdl@broadcom.com");
 132MODULE_DESCRIPTION("Broadcom MegaRAID SAS Driver");
 133
 134int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
 135static int megasas_get_pd_list(struct megasas_instance *instance);
 136static int megasas_ld_list_query(struct megasas_instance *instance,
 137				 u8 query_type);
 138static int megasas_issue_init_mfi(struct megasas_instance *instance);
 139static int megasas_register_aen(struct megasas_instance *instance,
 140				u32 seq_num, u32 class_locale_word);
 141static void megasas_get_pd_info(struct megasas_instance *instance,
 142				struct scsi_device *sdev);
 143static void
 144megasas_set_ld_removed_by_fw(struct megasas_instance *instance);
 145
 146/*
 147 * PCI ID table for all supported controllers
 148 */
 149static const struct pci_device_id megasas_pci_table[] = {
 150
 151	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
 152	/* xscale IOP */
 153	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
 154	/* ppc IOP */
 155	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
 156	/* ppc IOP */
 157	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
 158	/* gen2*/
 159	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
 160	/* gen2*/
 161	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)},
 162	/* skinny*/
 163	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)},
 164	/* skinny*/
 165	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
 166	/* xscale IOP, vega */
 167	{PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
 168	/* xscale IOP */
 169	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)},
 170	/* Fusion */
 171	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_PLASMA)},
 172	/* Plasma */
 173	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)},
 174	/* Invader */
 175	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FURY)},
 176	/* Fury */
 177	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER)},
 178	/* Intruder */
 179	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER_24)},
 180	/* Intruder 24 port*/
 181	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_52)},
 182	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_53)},
 183	/* VENTURA */
 184	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA)},
 185	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER)},
 186	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_HARPOON)},
 187	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_TOMCAT)},
 188	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA_4PORT)},
 189	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER_4PORT)},
 190	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E1)},
 191	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E2)},
 192	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E5)},
 193	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E6)},
 194	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E0)},
 195	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E3)},
 196	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E4)},
 197	{PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E7)},
 198	{}
 199};
 200
 201MODULE_DEVICE_TABLE(pci, megasas_pci_table);
 202
 203static int megasas_mgmt_majorno;
 204struct megasas_mgmt_info megasas_mgmt_info;
 205static struct fasync_struct *megasas_async_queue;
 206static DEFINE_MUTEX(megasas_async_queue_mutex);
 207
 208static int megasas_poll_wait_aen;
 209static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait);
 210static u32 support_poll_for_event;
 211u32 megasas_dbg_lvl;
 212static u32 support_device_change;
 213static bool support_nvme_encapsulation;
 214static bool support_pci_lane_margining;
 215
 216/* define lock for aen poll */
 217static DEFINE_SPINLOCK(poll_aen_lock);
 218
 219extern struct dentry *megasas_debugfs_root;
 220extern int megasas_blk_mq_poll(struct Scsi_Host *shost, unsigned int queue_num);
 221
 222void
 223megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
 224		     u8 alt_status);
 225static u32
 226megasas_read_fw_status_reg_gen2(struct megasas_instance *instance);
 227static int
 228megasas_adp_reset_gen2(struct megasas_instance *instance,
 229		       struct megasas_register_set __iomem *reg_set);
 230static irqreturn_t megasas_isr(int irq, void *devp);
 231static u32
 232megasas_init_adapter_mfi(struct megasas_instance *instance);
 233u32
 234megasas_build_and_issue_cmd(struct megasas_instance *instance,
 235			    struct scsi_cmnd *scmd);
 236static void megasas_complete_cmd_dpc(unsigned long instance_addr);
 237int
 238wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
 239	int seconds);
 240void megasas_fusion_ocr_wq(struct work_struct *work);
 241static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
 242					 int initial);
 243static int
 244megasas_set_dma_mask(struct megasas_instance *instance);
 245static int
 246megasas_alloc_ctrl_mem(struct megasas_instance *instance);
 247static inline void
 248megasas_free_ctrl_mem(struct megasas_instance *instance);
 249static inline int
 250megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance);
 251static inline void
 252megasas_free_ctrl_dma_buffers(struct megasas_instance *instance);
 253static inline void
 254megasas_init_ctrl_params(struct megasas_instance *instance);
 255
 256u32 megasas_readl(struct megasas_instance *instance,
 257		  const volatile void __iomem *addr)
 258{
 259	u32 i = 0, ret_val;
 260	/*
 261	 * Due to a HW errata in Aero controllers, reads to certain
 262	 * Fusion registers could intermittently return all zeroes.
 263	 * This behavior is transient in nature and subsequent reads will
 264	 * return valid value. As a workaround in driver, retry readl for
 265	 * up to thirty times until a non-zero value is read.
 266	 */
 267	if (instance->adapter_type == AERO_SERIES) {
 268		do {
 269			ret_val = readl(addr);
 270			i++;
 271		} while (ret_val == 0 && i < 30);
 272		return ret_val;
 273	} else {
 274		return readl(addr);
 275	}
 276}
 277
 278/**
 279 * megasas_set_dma_settings -	Populate DMA address, length and flags for DCMDs
 280 * @instance:			Adapter soft state
 281 * @dcmd:			DCMD frame inside MFI command
 282 * @dma_addr:			DMA address of buffer to be passed to FW
 283 * @dma_len:			Length of DMA buffer to be passed to FW
 284 * @return:			void
 285 */
 286void megasas_set_dma_settings(struct megasas_instance *instance,
 287			      struct megasas_dcmd_frame *dcmd,
 288			      dma_addr_t dma_addr, u32 dma_len)
 289{
 290	if (instance->consistent_mask_64bit) {
 291		dcmd->sgl.sge64[0].phys_addr = cpu_to_le64(dma_addr);
 292		dcmd->sgl.sge64[0].length = cpu_to_le32(dma_len);
 293		dcmd->flags = cpu_to_le16(dcmd->flags | MFI_FRAME_SGL64);
 294
 295	} else {
 296		dcmd->sgl.sge32[0].phys_addr =
 297				cpu_to_le32(lower_32_bits(dma_addr));
 298		dcmd->sgl.sge32[0].length = cpu_to_le32(dma_len);
 299		dcmd->flags = cpu_to_le16(dcmd->flags);
 300	}
 301}
 302
 303static void
 304megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
 305{
 306	instance->instancet->fire_cmd(instance,
 307		cmd->frame_phys_addr, 0, instance->reg_set);
 308	return;
 309}
 310
 311/**
 312 * megasas_get_cmd -	Get a command from the free pool
 313 * @instance:		Adapter soft state
 314 *
 315 * Returns a free command from the pool
 316 */
 317struct megasas_cmd *megasas_get_cmd(struct megasas_instance
 318						  *instance)
 319{
 320	unsigned long flags;
 321	struct megasas_cmd *cmd = NULL;
 322
 323	spin_lock_irqsave(&instance->mfi_pool_lock, flags);
 324
 325	if (!list_empty(&instance->cmd_pool)) {
 326		cmd = list_entry((&instance->cmd_pool)->next,
 327				 struct megasas_cmd, list);
 328		list_del_init(&cmd->list);
 329	} else {
 330		dev_err(&instance->pdev->dev, "Command pool empty!\n");
 331	}
 332
 333	spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
 334	return cmd;
 335}
 336
 337/**
 338 * megasas_return_cmd -	Return a cmd to free command pool
 339 * @instance:		Adapter soft state
 340 * @cmd:		Command packet to be returned to free command pool
 341 */
 342void
 343megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
 344{
 345	unsigned long flags;
 346	u32 blk_tags;
 347	struct megasas_cmd_fusion *cmd_fusion;
 348	struct fusion_context *fusion = instance->ctrl_context;
 349
 350	/* This flag is used only for fusion adapter.
 351	 * Wait for Interrupt for Polled mode DCMD
 352	 */
 353	if (cmd->flags & DRV_DCMD_POLLED_MODE)
 354		return;
 355
 356	spin_lock_irqsave(&instance->mfi_pool_lock, flags);
 357
 358	if (fusion) {
 359		blk_tags = instance->max_scsi_cmds + cmd->index;
 360		cmd_fusion = fusion->cmd_list[blk_tags];
 361		megasas_return_cmd_fusion(instance, cmd_fusion);
 362	}
 363	cmd->scmd = NULL;
 364	cmd->frame_count = 0;
 365	cmd->flags = 0;
 366	memset(cmd->frame, 0, instance->mfi_frame_size);
 367	cmd->frame->io.context = cpu_to_le32(cmd->index);
 368	if (!fusion && reset_devices)
 369		cmd->frame->hdr.cmd = MFI_CMD_INVALID;
 370	list_add(&cmd->list, (&instance->cmd_pool)->next);
 371
 372	spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
 373
 374}
 375
 376static const char *
 377format_timestamp(uint32_t timestamp)
 378{
 379	static char buffer[32];
 380
 381	if ((timestamp & 0xff000000) == 0xff000000)
 382		snprintf(buffer, sizeof(buffer), "boot + %us", timestamp &
 383		0x00ffffff);
 384	else
 385		snprintf(buffer, sizeof(buffer), "%us", timestamp);
 386	return buffer;
 387}
 388
 389static const char *
 390format_class(int8_t class)
 391{
 392	static char buffer[6];
 393
 394	switch (class) {
 395	case MFI_EVT_CLASS_DEBUG:
 396		return "debug";
 397	case MFI_EVT_CLASS_PROGRESS:
 398		return "progress";
 399	case MFI_EVT_CLASS_INFO:
 400		return "info";
 401	case MFI_EVT_CLASS_WARNING:
 402		return "WARN";
 403	case MFI_EVT_CLASS_CRITICAL:
 404		return "CRIT";
 405	case MFI_EVT_CLASS_FATAL:
 406		return "FATAL";
 407	case MFI_EVT_CLASS_DEAD:
 408		return "DEAD";
 409	default:
 410		snprintf(buffer, sizeof(buffer), "%d", class);
 411		return buffer;
 412	}
 413}
 414
 415/**
 416  * megasas_decode_evt: Decode FW AEN event and print critical event
 417  * for information.
 418  * @instance:			Adapter soft state
 419  */
 420static void
 421megasas_decode_evt(struct megasas_instance *instance)
 422{
 423	struct megasas_evt_detail *evt_detail = instance->evt_detail;
 424	union megasas_evt_class_locale class_locale;
 425	class_locale.word = le32_to_cpu(evt_detail->cl.word);
 426
 427	if ((event_log_level < MFI_EVT_CLASS_DEBUG) ||
 428	    (event_log_level > MFI_EVT_CLASS_DEAD)) {
 429		printk(KERN_WARNING "megaraid_sas: provided event log level is out of range, setting it to default 2(CLASS_CRITICAL), permissible range is: -2 to 4\n");
 430		event_log_level = MFI_EVT_CLASS_CRITICAL;
 431	}
 432
 433	if (class_locale.members.class >= event_log_level)
 434		dev_info(&instance->pdev->dev, "%d (%s/0x%04x/%s) - %s\n",
 435			le32_to_cpu(evt_detail->seq_num),
 436			format_timestamp(le32_to_cpu(evt_detail->time_stamp)),
 437			(class_locale.members.locale),
 438			format_class(class_locale.members.class),
 439			evt_detail->description);
 440
 441	if (megasas_dbg_lvl & LD_PD_DEBUG)
 442		dev_info(&instance->pdev->dev,
 443			 "evt_detail.args.ld.target_id/index %d/%d\n",
 444			 evt_detail->args.ld.target_id, evt_detail->args.ld.ld_index);
 445
 446}
 447
 448/*
 449 * The following functions are defined for xscale
 450 * (deviceid : 1064R, PERC5) controllers
 451 */
 452
 453/**
 454 * megasas_enable_intr_xscale -	Enables interrupts
 455 * @instance:	Adapter soft state
 456 */
 457static inline void
 458megasas_enable_intr_xscale(struct megasas_instance *instance)
 459{
 460	struct megasas_register_set __iomem *regs;
 461
 462	regs = instance->reg_set;
 463	writel(0, &(regs)->outbound_intr_mask);
 464
 465	/* Dummy readl to force pci flush */
 466	readl(&regs->outbound_intr_mask);
 467}
 468
 469/**
 470 * megasas_disable_intr_xscale -Disables interrupt
 471 * @instance:	Adapter soft state
 472 */
 473static inline void
 474megasas_disable_intr_xscale(struct megasas_instance *instance)
 475{
 476	struct megasas_register_set __iomem *regs;
 477	u32 mask = 0x1f;
 478
 479	regs = instance->reg_set;
 480	writel(mask, &regs->outbound_intr_mask);
 481	/* Dummy readl to force pci flush */
 482	readl(&regs->outbound_intr_mask);
 483}
 484
 485/**
 486 * megasas_read_fw_status_reg_xscale - returns the current FW status value
 487 * @instance:	Adapter soft state
 488 */
 489static u32
 490megasas_read_fw_status_reg_xscale(struct megasas_instance *instance)
 491{
 492	return readl(&instance->reg_set->outbound_msg_0);
 493}
 494/**
 495 * megasas_clear_intr_xscale -	Check & clear interrupt
 496 * @instance:	Adapter soft state
 497 */
 498static int
 499megasas_clear_intr_xscale(struct megasas_instance *instance)
 500{
 501	u32 status;
 502	u32 mfiStatus = 0;
 503	struct megasas_register_set __iomem *regs;
 504	regs = instance->reg_set;
 505
 506	/*
 507	 * Check if it is our interrupt
 508	 */
 509	status = readl(&regs->outbound_intr_status);
 510
 511	if (status & MFI_OB_INTR_STATUS_MASK)
 512		mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 513	if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT)
 514		mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 515
 516	/*
 517	 * Clear the interrupt by writing back the same value
 518	 */
 519	if (mfiStatus)
 520		writel(status, &regs->outbound_intr_status);
 521
 522	/* Dummy readl to force pci flush */
 523	readl(&regs->outbound_intr_status);
 524
 525	return mfiStatus;
 526}
 527
 528/**
 529 * megasas_fire_cmd_xscale -	Sends command to the FW
 530 * @instance:		Adapter soft state
 531 * @frame_phys_addr :	Physical address of cmd
 532 * @frame_count :	Number of frames for the command
 533 * @regs :		MFI register set
 534 */
 535static inline void
 536megasas_fire_cmd_xscale(struct megasas_instance *instance,
 537		dma_addr_t frame_phys_addr,
 538		u32 frame_count,
 539		struct megasas_register_set __iomem *regs)
 540{
 541	unsigned long flags;
 542
 543	spin_lock_irqsave(&instance->hba_lock, flags);
 544	writel((frame_phys_addr >> 3)|(frame_count),
 545	       &(regs)->inbound_queue_port);
 546	spin_unlock_irqrestore(&instance->hba_lock, flags);
 547}
 548
 549/**
 550 * megasas_adp_reset_xscale -  For controller reset
 551 * @instance:	Adapter soft state
 552 * @regs:	MFI register set
 553 */
 554static int
 555megasas_adp_reset_xscale(struct megasas_instance *instance,
 556	struct megasas_register_set __iomem *regs)
 557{
 558	u32 i;
 559	u32 pcidata;
 560
 561	writel(MFI_ADP_RESET, &regs->inbound_doorbell);
 562
 563	for (i = 0; i < 3; i++)
 564		msleep(1000); /* sleep for 3 secs */
 565	pcidata  = 0;
 566	pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata);
 567	dev_notice(&instance->pdev->dev, "pcidata = %x\n", pcidata);
 568	if (pcidata & 0x2) {
 569		dev_notice(&instance->pdev->dev, "mfi 1068 offset read=%x\n", pcidata);
 570		pcidata &= ~0x2;
 571		pci_write_config_dword(instance->pdev,
 572				MFI_1068_PCSR_OFFSET, pcidata);
 573
 574		for (i = 0; i < 2; i++)
 575			msleep(1000); /* need to wait 2 secs again */
 576
 577		pcidata  = 0;
 578		pci_read_config_dword(instance->pdev,
 579				MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata);
 580		dev_notice(&instance->pdev->dev, "1068 offset handshake read=%x\n", pcidata);
 581		if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) {
 582			dev_notice(&instance->pdev->dev, "1068 offset pcidt=%x\n", pcidata);
 583			pcidata = 0;
 584			pci_write_config_dword(instance->pdev,
 585				MFI_1068_FW_HANDSHAKE_OFFSET, pcidata);
 586		}
 587	}
 588	return 0;
 589}
 590
 591/**
 592 * megasas_check_reset_xscale -	For controller reset check
 593 * @instance:	Adapter soft state
 594 * @regs:	MFI register set
 595 */
 596static int
 597megasas_check_reset_xscale(struct megasas_instance *instance,
 598		struct megasas_register_set __iomem *regs)
 599{
 600	if ((atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) &&
 601	    (le32_to_cpu(*instance->consumer) ==
 602		MEGASAS_ADPRESET_INPROG_SIGN))
 603		return 1;
 604	return 0;
 605}
 606
 607static struct megasas_instance_template megasas_instance_template_xscale = {
 608
 609	.fire_cmd = megasas_fire_cmd_xscale,
 610	.enable_intr = megasas_enable_intr_xscale,
 611	.disable_intr = megasas_disable_intr_xscale,
 612	.clear_intr = megasas_clear_intr_xscale,
 613	.read_fw_status_reg = megasas_read_fw_status_reg_xscale,
 614	.adp_reset = megasas_adp_reset_xscale,
 615	.check_reset = megasas_check_reset_xscale,
 616	.service_isr = megasas_isr,
 617	.tasklet = megasas_complete_cmd_dpc,
 618	.init_adapter = megasas_init_adapter_mfi,
 619	.build_and_issue_cmd = megasas_build_and_issue_cmd,
 620	.issue_dcmd = megasas_issue_dcmd,
 621};
 622
 623/*
 624 * This is the end of set of functions & definitions specific
 625 * to xscale (deviceid : 1064R, PERC5) controllers
 626 */
 627
 628/*
 629 * The following functions are defined for ppc (deviceid : 0x60)
 630 * controllers
 631 */
 632
 633/**
 634 * megasas_enable_intr_ppc -	Enables interrupts
 635 * @instance:	Adapter soft state
 636 */
 637static inline void
 638megasas_enable_intr_ppc(struct megasas_instance *instance)
 639{
 640	struct megasas_register_set __iomem *regs;
 641
 642	regs = instance->reg_set;
 643	writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
 644
 645	writel(~0x80000000, &(regs)->outbound_intr_mask);
 646
 647	/* Dummy readl to force pci flush */
 648	readl(&regs->outbound_intr_mask);
 649}
 650
 651/**
 652 * megasas_disable_intr_ppc -	Disable interrupt
 653 * @instance:	Adapter soft state
 654 */
 655static inline void
 656megasas_disable_intr_ppc(struct megasas_instance *instance)
 657{
 658	struct megasas_register_set __iomem *regs;
 659	u32 mask = 0xFFFFFFFF;
 660
 661	regs = instance->reg_set;
 662	writel(mask, &regs->outbound_intr_mask);
 663	/* Dummy readl to force pci flush */
 664	readl(&regs->outbound_intr_mask);
 665}
 666
 667/**
 668 * megasas_read_fw_status_reg_ppc - returns the current FW status value
 669 * @instance:	Adapter soft state
 670 */
 671static u32
 672megasas_read_fw_status_reg_ppc(struct megasas_instance *instance)
 673{
 674	return readl(&instance->reg_set->outbound_scratch_pad_0);
 675}
 676
 677/**
 678 * megasas_clear_intr_ppc -	Check & clear interrupt
 679 * @instance:	Adapter soft state
 680 */
 681static int
 682megasas_clear_intr_ppc(struct megasas_instance *instance)
 683{
 684	u32 status, mfiStatus = 0;
 685	struct megasas_register_set __iomem *regs;
 686	regs = instance->reg_set;
 687
 688	/*
 689	 * Check if it is our interrupt
 690	 */
 691	status = readl(&regs->outbound_intr_status);
 692
 693	if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT)
 694		mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 695
 696	if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT)
 697		mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 698
 699	/*
 700	 * Clear the interrupt by writing back the same value
 701	 */
 702	writel(status, &regs->outbound_doorbell_clear);
 703
 704	/* Dummy readl to force pci flush */
 705	readl(&regs->outbound_doorbell_clear);
 706
 707	return mfiStatus;
 708}
 709
 710/**
 711 * megasas_fire_cmd_ppc -	Sends command to the FW
 712 * @instance:		Adapter soft state
 713 * @frame_phys_addr:	Physical address of cmd
 714 * @frame_count:	Number of frames for the command
 715 * @regs:		MFI register set
 716 */
 717static inline void
 718megasas_fire_cmd_ppc(struct megasas_instance *instance,
 719		dma_addr_t frame_phys_addr,
 720		u32 frame_count,
 721		struct megasas_register_set __iomem *regs)
 722{
 723	unsigned long flags;
 724
 725	spin_lock_irqsave(&instance->hba_lock, flags);
 726	writel((frame_phys_addr | (frame_count<<1))|1,
 727			&(regs)->inbound_queue_port);
 728	spin_unlock_irqrestore(&instance->hba_lock, flags);
 729}
 730
 731/**
 732 * megasas_check_reset_ppc -	For controller reset check
 733 * @instance:	Adapter soft state
 734 * @regs:	MFI register set
 735 */
 736static int
 737megasas_check_reset_ppc(struct megasas_instance *instance,
 738			struct megasas_register_set __iomem *regs)
 739{
 740	if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
 741		return 1;
 742
 743	return 0;
 744}
 745
 746static struct megasas_instance_template megasas_instance_template_ppc = {
 747
 748	.fire_cmd = megasas_fire_cmd_ppc,
 749	.enable_intr = megasas_enable_intr_ppc,
 750	.disable_intr = megasas_disable_intr_ppc,
 751	.clear_intr = megasas_clear_intr_ppc,
 752	.read_fw_status_reg = megasas_read_fw_status_reg_ppc,
 753	.adp_reset = megasas_adp_reset_xscale,
 754	.check_reset = megasas_check_reset_ppc,
 755	.service_isr = megasas_isr,
 756	.tasklet = megasas_complete_cmd_dpc,
 757	.init_adapter = megasas_init_adapter_mfi,
 758	.build_and_issue_cmd = megasas_build_and_issue_cmd,
 759	.issue_dcmd = megasas_issue_dcmd,
 760};
 761
 762/**
 763 * megasas_enable_intr_skinny -	Enables interrupts
 764 * @instance:	Adapter soft state
 765 */
 766static inline void
 767megasas_enable_intr_skinny(struct megasas_instance *instance)
 768{
 769	struct megasas_register_set __iomem *regs;
 770
 771	regs = instance->reg_set;
 772	writel(0xFFFFFFFF, &(regs)->outbound_intr_mask);
 773
 774	writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
 775
 776	/* Dummy readl to force pci flush */
 777	readl(&regs->outbound_intr_mask);
 778}
 779
 780/**
 781 * megasas_disable_intr_skinny -	Disables interrupt
 782 * @instance:	Adapter soft state
 783 */
 784static inline void
 785megasas_disable_intr_skinny(struct megasas_instance *instance)
 786{
 787	struct megasas_register_set __iomem *regs;
 788	u32 mask = 0xFFFFFFFF;
 789
 790	regs = instance->reg_set;
 791	writel(mask, &regs->outbound_intr_mask);
 792	/* Dummy readl to force pci flush */
 793	readl(&regs->outbound_intr_mask);
 794}
 795
 796/**
 797 * megasas_read_fw_status_reg_skinny - returns the current FW status value
 798 * @instance:	Adapter soft state
 799 */
 800static u32
 801megasas_read_fw_status_reg_skinny(struct megasas_instance *instance)
 802{
 803	return readl(&instance->reg_set->outbound_scratch_pad_0);
 804}
 805
 806/**
 807 * megasas_clear_intr_skinny -	Check & clear interrupt
 808 * @instance:	Adapter soft state
 809 */
 810static int
 811megasas_clear_intr_skinny(struct megasas_instance *instance)
 812{
 813	u32 status;
 814	u32 mfiStatus = 0;
 815	struct megasas_register_set __iomem *regs;
 816	regs = instance->reg_set;
 817
 818	/*
 819	 * Check if it is our interrupt
 820	 */
 821	status = readl(&regs->outbound_intr_status);
 822
 823	if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) {
 824		return 0;
 825	}
 826
 827	/*
 828	 * Check if it is our interrupt
 829	 */
 830	if ((megasas_read_fw_status_reg_skinny(instance) & MFI_STATE_MASK) ==
 831	    MFI_STATE_FAULT) {
 832		mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 833	} else
 834		mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 835
 836	/*
 837	 * Clear the interrupt by writing back the same value
 838	 */
 839	writel(status, &regs->outbound_intr_status);
 840
 841	/*
 842	 * dummy read to flush PCI
 843	 */
 844	readl(&regs->outbound_intr_status);
 845
 846	return mfiStatus;
 847}
 848
 849/**
 850 * megasas_fire_cmd_skinny -	Sends command to the FW
 851 * @instance:		Adapter soft state
 852 * @frame_phys_addr:	Physical address of cmd
 853 * @frame_count:	Number of frames for the command
 854 * @regs:		MFI register set
 855 */
 856static inline void
 857megasas_fire_cmd_skinny(struct megasas_instance *instance,
 858			dma_addr_t frame_phys_addr,
 859			u32 frame_count,
 860			struct megasas_register_set __iomem *regs)
 861{
 862	unsigned long flags;
 863
 864	spin_lock_irqsave(&instance->hba_lock, flags);
 865	writel(upper_32_bits(frame_phys_addr),
 866	       &(regs)->inbound_high_queue_port);
 867	writel((lower_32_bits(frame_phys_addr) | (frame_count<<1))|1,
 868	       &(regs)->inbound_low_queue_port);
 869	spin_unlock_irqrestore(&instance->hba_lock, flags);
 870}
 871
 872/**
 873 * megasas_check_reset_skinny -	For controller reset check
 874 * @instance:	Adapter soft state
 875 * @regs:	MFI register set
 876 */
 877static int
 878megasas_check_reset_skinny(struct megasas_instance *instance,
 879				struct megasas_register_set __iomem *regs)
 880{
 881	if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
 882		return 1;
 883
 884	return 0;
 885}
 886
 887static struct megasas_instance_template megasas_instance_template_skinny = {
 888
 889	.fire_cmd = megasas_fire_cmd_skinny,
 890	.enable_intr = megasas_enable_intr_skinny,
 891	.disable_intr = megasas_disable_intr_skinny,
 892	.clear_intr = megasas_clear_intr_skinny,
 893	.read_fw_status_reg = megasas_read_fw_status_reg_skinny,
 894	.adp_reset = megasas_adp_reset_gen2,
 895	.check_reset = megasas_check_reset_skinny,
 896	.service_isr = megasas_isr,
 897	.tasklet = megasas_complete_cmd_dpc,
 898	.init_adapter = megasas_init_adapter_mfi,
 899	.build_and_issue_cmd = megasas_build_and_issue_cmd,
 900	.issue_dcmd = megasas_issue_dcmd,
 901};
 902
 903
 904/*
 905 * The following functions are defined for gen2 (deviceid : 0x78 0x79)
 906 * controllers
 907 */
 908
 909/**
 910 * megasas_enable_intr_gen2 -  Enables interrupts
 911 * @instance:	Adapter soft state
 912 */
 913static inline void
 914megasas_enable_intr_gen2(struct megasas_instance *instance)
 915{
 916	struct megasas_register_set __iomem *regs;
 917
 918	regs = instance->reg_set;
 919	writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
 920
 921	/* write ~0x00000005 (4 & 1) to the intr mask*/
 922	writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
 923
 924	/* Dummy readl to force pci flush */
 925	readl(&regs->outbound_intr_mask);
 926}
 927
 928/**
 929 * megasas_disable_intr_gen2 - Disables interrupt
 930 * @instance:	Adapter soft state
 931 */
 932static inline void
 933megasas_disable_intr_gen2(struct megasas_instance *instance)
 934{
 935	struct megasas_register_set __iomem *regs;
 936	u32 mask = 0xFFFFFFFF;
 937
 938	regs = instance->reg_set;
 939	writel(mask, &regs->outbound_intr_mask);
 940	/* Dummy readl to force pci flush */
 941	readl(&regs->outbound_intr_mask);
 942}
 943
 944/**
 945 * megasas_read_fw_status_reg_gen2 - returns the current FW status value
 946 * @instance:	Adapter soft state
 947 */
 948static u32
 949megasas_read_fw_status_reg_gen2(struct megasas_instance *instance)
 950{
 951	return readl(&instance->reg_set->outbound_scratch_pad_0);
 952}
 953
 954/**
 955 * megasas_clear_intr_gen2 -      Check & clear interrupt
 956 * @instance:	Adapter soft state
 957 */
 958static int
 959megasas_clear_intr_gen2(struct megasas_instance *instance)
 960{
 961	u32 status;
 962	u32 mfiStatus = 0;
 963	struct megasas_register_set __iomem *regs;
 964	regs = instance->reg_set;
 965
 966	/*
 967	 * Check if it is our interrupt
 968	 */
 969	status = readl(&regs->outbound_intr_status);
 970
 971	if (status & MFI_INTR_FLAG_REPLY_MESSAGE) {
 972		mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 973	}
 974	if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) {
 975		mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 976	}
 977
 978	/*
 979	 * Clear the interrupt by writing back the same value
 980	 */
 981	if (mfiStatus)
 982		writel(status, &regs->outbound_doorbell_clear);
 983
 984	/* Dummy readl to force pci flush */
 985	readl(&regs->outbound_intr_status);
 986
 987	return mfiStatus;
 988}
 989
 990/**
 991 * megasas_fire_cmd_gen2 -     Sends command to the FW
 992 * @instance:		Adapter soft state
 993 * @frame_phys_addr:	Physical address of cmd
 994 * @frame_count:	Number of frames for the command
 995 * @regs:		MFI register set
 996 */
 997static inline void
 998megasas_fire_cmd_gen2(struct megasas_instance *instance,
 999			dma_addr_t frame_phys_addr,
1000			u32 frame_count,
1001			struct megasas_register_set __iomem *regs)
1002{
1003	unsigned long flags;
1004
1005	spin_lock_irqsave(&instance->hba_lock, flags);
1006	writel((frame_phys_addr | (frame_count<<1))|1,
1007			&(regs)->inbound_queue_port);
1008	spin_unlock_irqrestore(&instance->hba_lock, flags);
1009}
1010
1011/**
1012 * megasas_adp_reset_gen2 -	For controller reset
1013 * @instance:	Adapter soft state
1014 * @reg_set:	MFI register set
1015 */
1016static int
1017megasas_adp_reset_gen2(struct megasas_instance *instance,
1018			struct megasas_register_set __iomem *reg_set)
1019{
1020	u32 retry = 0 ;
1021	u32 HostDiag;
1022	u32 __iomem *seq_offset = &reg_set->seq_offset;
1023	u32 __iomem *hostdiag_offset = &reg_set->host_diag;
1024
1025	if (instance->instancet == &megasas_instance_template_skinny) {
1026		seq_offset = &reg_set->fusion_seq_offset;
1027		hostdiag_offset = &reg_set->fusion_host_diag;
1028	}
1029
1030	writel(0, seq_offset);
1031	writel(4, seq_offset);
1032	writel(0xb, seq_offset);
1033	writel(2, seq_offset);
1034	writel(7, seq_offset);
1035	writel(0xd, seq_offset);
1036
1037	msleep(1000);
1038
1039	HostDiag = (u32)readl(hostdiag_offset);
1040
1041	while (!(HostDiag & DIAG_WRITE_ENABLE)) {
1042		msleep(100);
1043		HostDiag = (u32)readl(hostdiag_offset);
1044		dev_notice(&instance->pdev->dev, "RESETGEN2: retry=%x, hostdiag=%x\n",
1045					retry, HostDiag);
1046
1047		if (retry++ >= 100)
1048			return 1;
1049
1050	}
1051
1052	dev_notice(&instance->pdev->dev, "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag);
1053
1054	writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset);
1055
1056	ssleep(10);
1057
1058	HostDiag = (u32)readl(hostdiag_offset);
1059	while (HostDiag & DIAG_RESET_ADAPTER) {
1060		msleep(100);
1061		HostDiag = (u32)readl(hostdiag_offset);
1062		dev_notice(&instance->pdev->dev, "RESET_GEN2: retry=%x, hostdiag=%x\n",
1063				retry, HostDiag);
1064
1065		if (retry++ >= 1000)
1066			return 1;
1067
1068	}
1069	return 0;
1070}
1071
1072/**
1073 * megasas_check_reset_gen2 -	For controller reset check
1074 * @instance:	Adapter soft state
1075 * @regs:	MFI register set
1076 */
1077static int
1078megasas_check_reset_gen2(struct megasas_instance *instance,
1079		struct megasas_register_set __iomem *regs)
1080{
1081	if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
1082		return 1;
1083
1084	return 0;
1085}
1086
1087static struct megasas_instance_template megasas_instance_template_gen2 = {
1088
1089	.fire_cmd = megasas_fire_cmd_gen2,
1090	.enable_intr = megasas_enable_intr_gen2,
1091	.disable_intr = megasas_disable_intr_gen2,
1092	.clear_intr = megasas_clear_intr_gen2,
1093	.read_fw_status_reg = megasas_read_fw_status_reg_gen2,
1094	.adp_reset = megasas_adp_reset_gen2,
1095	.check_reset = megasas_check_reset_gen2,
1096	.service_isr = megasas_isr,
1097	.tasklet = megasas_complete_cmd_dpc,
1098	.init_adapter = megasas_init_adapter_mfi,
1099	.build_and_issue_cmd = megasas_build_and_issue_cmd,
1100	.issue_dcmd = megasas_issue_dcmd,
1101};
1102
1103/*
1104 * This is the end of set of functions & definitions
1105 * specific to gen2 (deviceid : 0x78, 0x79) controllers
1106 */
1107
1108/*
1109 * Template added for TB (Fusion)
1110 */
1111extern struct megasas_instance_template megasas_instance_template_fusion;
1112
1113/**
1114 * megasas_issue_polled -	Issues a polling command
1115 * @instance:			Adapter soft state
1116 * @cmd:			Command packet to be issued
1117 *
1118 * For polling, MFI requires the cmd_status to be set to MFI_STAT_INVALID_STATUS before posting.
1119 */
1120int
1121megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
1122{
1123	struct megasas_header *frame_hdr = &cmd->frame->hdr;
1124
1125	frame_hdr->cmd_status = MFI_STAT_INVALID_STATUS;
1126	frame_hdr->flags |= cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE);
1127
1128	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1129		dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1130			__func__, __LINE__);
1131		return DCMD_INIT;
1132	}
1133
1134	instance->instancet->issue_dcmd(instance, cmd);
1135
1136	return wait_and_poll(instance, cmd, instance->requestorId ?
1137			MEGASAS_ROUTINE_WAIT_TIME_VF : MFI_IO_TIMEOUT_SECS);
1138}
1139
1140/**
1141 * megasas_issue_blocked_cmd -	Synchronous wrapper around regular FW cmds
1142 * @instance:			Adapter soft state
1143 * @cmd:			Command to be issued
1144 * @timeout:			Timeout in seconds
1145 *
1146 * This function waits on an event for the command to be returned from ISR.
1147 * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
1148 * Used to issue ioctl commands.
1149 */
1150int
1151megasas_issue_blocked_cmd(struct megasas_instance *instance,
1152			  struct megasas_cmd *cmd, int timeout)
1153{
1154	int ret = 0;
1155	cmd->cmd_status_drv = DCMD_INIT;
1156
1157	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1158		dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1159			__func__, __LINE__);
1160		return DCMD_INIT;
1161	}
1162
1163	instance->instancet->issue_dcmd(instance, cmd);
1164
1165	if (timeout) {
1166		ret = wait_event_timeout(instance->int_cmd_wait_q,
1167		cmd->cmd_status_drv != DCMD_INIT, timeout * HZ);
1168		if (!ret) {
1169			dev_err(&instance->pdev->dev,
1170				"DCMD(opcode: 0x%x) is timed out, func:%s\n",
1171				cmd->frame->dcmd.opcode, __func__);
1172			return DCMD_TIMEOUT;
1173		}
1174	} else
1175		wait_event(instance->int_cmd_wait_q,
1176				cmd->cmd_status_drv != DCMD_INIT);
1177
1178	return cmd->cmd_status_drv;
1179}
1180
1181/**
1182 * megasas_issue_blocked_abort_cmd -	Aborts previously issued cmd
1183 * @instance:				Adapter soft state
1184 * @cmd_to_abort:			Previously issued cmd to be aborted
1185 * @timeout:				Timeout in seconds
1186 *
1187 * MFI firmware can abort previously issued AEN comamnd (automatic event
1188 * notification). The megasas_issue_blocked_abort_cmd() issues such abort
1189 * cmd and waits for return status.
1190 * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
1191 */
1192static int
1193megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
1194				struct megasas_cmd *cmd_to_abort, int timeout)
1195{
1196	struct megasas_cmd *cmd;
1197	struct megasas_abort_frame *abort_fr;
1198	int ret = 0;
1199	u32 opcode;
1200
1201	cmd = megasas_get_cmd(instance);
1202
1203	if (!cmd)
1204		return -1;
1205
1206	abort_fr = &cmd->frame->abort;
1207
1208	/*
1209	 * Prepare and issue the abort frame
1210	 */
1211	abort_fr->cmd = MFI_CMD_ABORT;
1212	abort_fr->cmd_status = MFI_STAT_INVALID_STATUS;
1213	abort_fr->flags = cpu_to_le16(0);
1214	abort_fr->abort_context = cpu_to_le32(cmd_to_abort->index);
1215	abort_fr->abort_mfi_phys_addr_lo =
1216		cpu_to_le32(lower_32_bits(cmd_to_abort->frame_phys_addr));
1217	abort_fr->abort_mfi_phys_addr_hi =
1218		cpu_to_le32(upper_32_bits(cmd_to_abort->frame_phys_addr));
1219
1220	cmd->sync_cmd = 1;
1221	cmd->cmd_status_drv = DCMD_INIT;
1222
1223	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1224		dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1225			__func__, __LINE__);
1226		return DCMD_INIT;
1227	}
1228
1229	instance->instancet->issue_dcmd(instance, cmd);
1230
1231	if (timeout) {
1232		ret = wait_event_timeout(instance->abort_cmd_wait_q,
1233		cmd->cmd_status_drv != DCMD_INIT, timeout * HZ);
1234		if (!ret) {
1235			opcode = cmd_to_abort->frame->dcmd.opcode;
1236			dev_err(&instance->pdev->dev,
1237				"Abort(to be aborted DCMD opcode: 0x%x) is timed out func:%s\n",
1238				opcode,  __func__);
1239			return DCMD_TIMEOUT;
1240		}
1241	} else
1242		wait_event(instance->abort_cmd_wait_q,
1243		cmd->cmd_status_drv != DCMD_INIT);
1244
1245	cmd->sync_cmd = 0;
1246
1247	megasas_return_cmd(instance, cmd);
1248	return cmd->cmd_status_drv;
1249}
1250
1251/**
1252 * megasas_make_sgl32 -	Prepares 32-bit SGL
1253 * @instance:		Adapter soft state
1254 * @scp:		SCSI command from the mid-layer
1255 * @mfi_sgl:		SGL to be filled in
1256 *
1257 * If successful, this function returns the number of SG elements. Otherwise,
1258 * it returnes -1.
1259 */
1260static int
1261megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
1262		   union megasas_sgl *mfi_sgl)
1263{
1264	int i;
1265	int sge_count;
1266	struct scatterlist *os_sgl;
1267
1268	sge_count = scsi_dma_map(scp);
1269	BUG_ON(sge_count < 0);
1270
1271	if (sge_count) {
1272		scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1273			mfi_sgl->sge32[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1274			mfi_sgl->sge32[i].phys_addr = cpu_to_le32(sg_dma_address(os_sgl));
1275		}
1276	}
1277	return sge_count;
1278}
1279
1280/**
1281 * megasas_make_sgl64 -	Prepares 64-bit SGL
1282 * @instance:		Adapter soft state
1283 * @scp:		SCSI command from the mid-layer
1284 * @mfi_sgl:		SGL to be filled in
1285 *
1286 * If successful, this function returns the number of SG elements. Otherwise,
1287 * it returnes -1.
1288 */
1289static int
1290megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
1291		   union megasas_sgl *mfi_sgl)
1292{
1293	int i;
1294	int sge_count;
1295	struct scatterlist *os_sgl;
1296
1297	sge_count = scsi_dma_map(scp);
1298	BUG_ON(sge_count < 0);
1299
1300	if (sge_count) {
1301		scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1302			mfi_sgl->sge64[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1303			mfi_sgl->sge64[i].phys_addr = cpu_to_le64(sg_dma_address(os_sgl));
1304		}
1305	}
1306	return sge_count;
1307}
1308
1309/**
1310 * megasas_make_sgl_skinny - Prepares IEEE SGL
1311 * @instance:           Adapter soft state
1312 * @scp:                SCSI command from the mid-layer
1313 * @mfi_sgl:            SGL to be filled in
1314 *
1315 * If successful, this function returns the number of SG elements. Otherwise,
1316 * it returnes -1.
1317 */
1318static int
1319megasas_make_sgl_skinny(struct megasas_instance *instance,
1320		struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl)
1321{
1322	int i;
1323	int sge_count;
1324	struct scatterlist *os_sgl;
1325
1326	sge_count = scsi_dma_map(scp);
1327
1328	if (sge_count) {
1329		scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1330			mfi_sgl->sge_skinny[i].length =
1331				cpu_to_le32(sg_dma_len(os_sgl));
1332			mfi_sgl->sge_skinny[i].phys_addr =
1333				cpu_to_le64(sg_dma_address(os_sgl));
1334			mfi_sgl->sge_skinny[i].flag = cpu_to_le32(0);
1335		}
1336	}
1337	return sge_count;
1338}
1339
1340 /**
1341 * megasas_get_frame_count - Computes the number of frames
1342 * @frame_type		: type of frame- io or pthru frame
1343 * @sge_count		: number of sg elements
1344 *
1345 * Returns the number of frames required for numnber of sge's (sge_count)
1346 */
1347
1348static u32 megasas_get_frame_count(struct megasas_instance *instance,
1349			u8 sge_count, u8 frame_type)
1350{
1351	int num_cnt;
1352	int sge_bytes;
1353	u32 sge_sz;
1354	u32 frame_count = 0;
1355
1356	sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1357	    sizeof(struct megasas_sge32);
1358
1359	if (instance->flag_ieee) {
1360		sge_sz = sizeof(struct megasas_sge_skinny);
1361	}
1362
1363	/*
1364	 * Main frame can contain 2 SGEs for 64-bit SGLs and
1365	 * 3 SGEs for 32-bit SGLs for ldio &
1366	 * 1 SGEs for 64-bit SGLs and
1367	 * 2 SGEs for 32-bit SGLs for pthru frame
1368	 */
1369	if (unlikely(frame_type == PTHRU_FRAME)) {
1370		if (instance->flag_ieee == 1) {
1371			num_cnt = sge_count - 1;
1372		} else if (IS_DMA64)
1373			num_cnt = sge_count - 1;
1374		else
1375			num_cnt = sge_count - 2;
1376	} else {
1377		if (instance->flag_ieee == 1) {
1378			num_cnt = sge_count - 1;
1379		} else if (IS_DMA64)
1380			num_cnt = sge_count - 2;
1381		else
1382			num_cnt = sge_count - 3;
1383	}
1384
1385	if (num_cnt > 0) {
1386		sge_bytes = sge_sz * num_cnt;
1387
1388		frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
1389		    ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
1390	}
1391	/* Main frame */
1392	frame_count += 1;
1393
1394	if (frame_count > 7)
1395		frame_count = 8;
1396	return frame_count;
1397}
1398
1399/**
1400 * megasas_build_dcdb -	Prepares a direct cdb (DCDB) command
1401 * @instance:		Adapter soft state
1402 * @scp:		SCSI command
1403 * @cmd:		Command to be prepared in
1404 *
1405 * This function prepares CDB commands. These are typcially pass-through
1406 * commands to the devices.
1407 */
1408static int
1409megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
1410		   struct megasas_cmd *cmd)
1411{
1412	u32 is_logical;
1413	u32 device_id;
1414	u16 flags = 0;
1415	struct megasas_pthru_frame *pthru;
1416
1417	is_logical = MEGASAS_IS_LOGICAL(scp->device);
1418	device_id = MEGASAS_DEV_INDEX(scp);
1419	pthru = (struct megasas_pthru_frame *)cmd->frame;
1420
1421	if (scp->sc_data_direction == DMA_TO_DEVICE)
1422		flags = MFI_FRAME_DIR_WRITE;
1423	else if (scp->sc_data_direction == DMA_FROM_DEVICE)
1424		flags = MFI_FRAME_DIR_READ;
1425	else if (scp->sc_data_direction == DMA_NONE)
1426		flags = MFI_FRAME_DIR_NONE;
1427
1428	if (instance->flag_ieee == 1) {
1429		flags |= MFI_FRAME_IEEE;
1430	}
1431
1432	/*
1433	 * Prepare the DCDB frame
1434	 */
1435	pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
1436	pthru->cmd_status = 0x0;
1437	pthru->scsi_status = 0x0;
1438	pthru->target_id = device_id;
1439	pthru->lun = scp->device->lun;
1440	pthru->cdb_len = scp->cmd_len;
1441	pthru->timeout = 0;
1442	pthru->pad_0 = 0;
1443	pthru->flags = cpu_to_le16(flags);
1444	pthru->data_xfer_len = cpu_to_le32(scsi_bufflen(scp));
1445
1446	memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
1447
1448	/*
1449	 * If the command is for the tape device, set the
1450	 * pthru timeout to the os layer timeout value.
1451	 */
1452	if (scp->device->type == TYPE_TAPE) {
1453		if (scsi_cmd_to_rq(scp)->timeout / HZ > 0xFFFF)
1454			pthru->timeout = cpu_to_le16(0xFFFF);
1455		else
1456			pthru->timeout = cpu_to_le16(scsi_cmd_to_rq(scp)->timeout / HZ);
1457	}
1458
1459	/*
1460	 * Construct SGL
1461	 */
1462	if (instance->flag_ieee == 1) {
1463		pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1464		pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
1465						      &pthru->sgl);
1466	} else if (IS_DMA64) {
1467		pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1468		pthru->sge_count = megasas_make_sgl64(instance, scp,
1469						      &pthru->sgl);
1470	} else
1471		pthru->sge_count = megasas_make_sgl32(instance, scp,
1472						      &pthru->sgl);
1473
1474	if (pthru->sge_count > instance->max_num_sge) {
1475		dev_err(&instance->pdev->dev, "DCDB too many SGE NUM=%x\n",
1476			pthru->sge_count);
1477		return 0;
1478	}
1479
1480	/*
1481	 * Sense info specific
1482	 */
1483	pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
1484	pthru->sense_buf_phys_addr_hi =
1485		cpu_to_le32(upper_32_bits(cmd->sense_phys_addr));
1486	pthru->sense_buf_phys_addr_lo =
1487		cpu_to_le32(lower_32_bits(cmd->sense_phys_addr));
1488
1489	/*
1490	 * Compute the total number of frames this command consumes. FW uses
1491	 * this number to pull sufficient number of frames from host memory.
1492	 */
1493	cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
1494							PTHRU_FRAME);
1495
1496	return cmd->frame_count;
1497}
1498
1499/**
1500 * megasas_build_ldio -	Prepares IOs to logical devices
1501 * @instance:		Adapter soft state
1502 * @scp:		SCSI command
1503 * @cmd:		Command to be prepared
1504 *
1505 * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
1506 */
1507static int
1508megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
1509		   struct megasas_cmd *cmd)
1510{
1511	u32 device_id;
1512	u8 sc = scp->cmnd[0];
1513	u16 flags = 0;
1514	struct megasas_io_frame *ldio;
1515
1516	device_id = MEGASAS_DEV_INDEX(scp);
1517	ldio = (struct megasas_io_frame *)cmd->frame;
1518
1519	if (scp->sc_data_direction == DMA_TO_DEVICE)
1520		flags = MFI_FRAME_DIR_WRITE;
1521	else if (scp->sc_data_direction == DMA_FROM_DEVICE)
1522		flags = MFI_FRAME_DIR_READ;
1523
1524	if (instance->flag_ieee == 1) {
1525		flags |= MFI_FRAME_IEEE;
1526	}
1527
1528	/*
1529	 * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
1530	 */
1531	ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
1532	ldio->cmd_status = 0x0;
1533	ldio->scsi_status = 0x0;
1534	ldio->target_id = device_id;
1535	ldio->timeout = 0;
1536	ldio->reserved_0 = 0;
1537	ldio->pad_0 = 0;
1538	ldio->flags = cpu_to_le16(flags);
1539	ldio->start_lba_hi = 0;
1540	ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
1541
1542	/*
1543	 * 6-byte READ(0x08) or WRITE(0x0A) cdb
1544	 */
1545	if (scp->cmd_len == 6) {
1546		ldio->lba_count = cpu_to_le32((u32) scp->cmnd[4]);
1547		ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[1] << 16) |
1548						 ((u32) scp->cmnd[2] << 8) |
1549						 (u32) scp->cmnd[3]);
1550
1551		ldio->start_lba_lo &= cpu_to_le32(0x1FFFFF);
1552	}
1553
1554	/*
1555	 * 10-byte READ(0x28) or WRITE(0x2A) cdb
1556	 */
1557	else if (scp->cmd_len == 10) {
1558		ldio->lba_count = cpu_to_le32((u32) scp->cmnd[8] |
1559					      ((u32) scp->cmnd[7] << 8));
1560		ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1561						 ((u32) scp->cmnd[3] << 16) |
1562						 ((u32) scp->cmnd[4] << 8) |
1563						 (u32) scp->cmnd[5]);
1564	}
1565
1566	/*
1567	 * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1568	 */
1569	else if (scp->cmd_len == 12) {
1570		ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1571					      ((u32) scp->cmnd[7] << 16) |
1572					      ((u32) scp->cmnd[8] << 8) |
1573					      (u32) scp->cmnd[9]);
1574
1575		ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1576						 ((u32) scp->cmnd[3] << 16) |
1577						 ((u32) scp->cmnd[4] << 8) |
1578						 (u32) scp->cmnd[5]);
1579	}
1580
1581	/*
1582	 * 16-byte READ(0x88) or WRITE(0x8A) cdb
1583	 */
1584	else if (scp->cmd_len == 16) {
1585		ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[10] << 24) |
1586					      ((u32) scp->cmnd[11] << 16) |
1587					      ((u32) scp->cmnd[12] << 8) |
1588					      (u32) scp->cmnd[13]);
1589
1590		ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1591						 ((u32) scp->cmnd[7] << 16) |
1592						 ((u32) scp->cmnd[8] << 8) |
1593						 (u32) scp->cmnd[9]);
1594
1595		ldio->start_lba_hi = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1596						 ((u32) scp->cmnd[3] << 16) |
1597						 ((u32) scp->cmnd[4] << 8) |
1598						 (u32) scp->cmnd[5]);
1599
1600	}
1601
1602	/*
1603	 * Construct SGL
1604	 */
1605	if (instance->flag_ieee) {
1606		ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1607		ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
1608					      &ldio->sgl);
1609	} else if (IS_DMA64) {
1610		ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1611		ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
1612	} else
1613		ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
1614
1615	if (ldio->sge_count > instance->max_num_sge) {
1616		dev_err(&instance->pdev->dev, "build_ld_io: sge_count = %x\n",
1617			ldio->sge_count);
1618		return 0;
1619	}
1620
1621	/*
1622	 * Sense info specific
1623	 */
1624	ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
1625	ldio->sense_buf_phys_addr_hi = 0;
1626	ldio->sense_buf_phys_addr_lo = cpu_to_le32(cmd->sense_phys_addr);
1627
1628	/*
1629	 * Compute the total number of frames this command consumes. FW uses
1630	 * this number to pull sufficient number of frames from host memory.
1631	 */
1632	cmd->frame_count = megasas_get_frame_count(instance,
1633			ldio->sge_count, IO_FRAME);
1634
1635	return cmd->frame_count;
1636}
1637
1638/**
1639 * megasas_cmd_type -		Checks if the cmd is for logical drive/sysPD
1640 *				and whether it's RW or non RW
1641 * @cmd:			SCSI command
1642 *
1643 */
1644inline int megasas_cmd_type(struct scsi_cmnd *cmd)
1645{
1646	int ret;
1647
1648	switch (cmd->cmnd[0]) {
1649	case READ_10:
1650	case WRITE_10:
1651	case READ_12:
1652	case WRITE_12:
1653	case READ_6:
1654	case WRITE_6:
1655	case READ_16:
1656	case WRITE_16:
1657		ret = (MEGASAS_IS_LOGICAL(cmd->device)) ?
1658			READ_WRITE_LDIO : READ_WRITE_SYSPDIO;
1659		break;
1660	default:
1661		ret = (MEGASAS_IS_LOGICAL(cmd->device)) ?
1662			NON_READ_WRITE_LDIO : NON_READ_WRITE_SYSPDIO;
1663	}
1664	return ret;
1665}
1666
1667 /**
1668 * megasas_dump_pending_frames -	Dumps the frame address of all pending cmds
1669 *					in FW
1670 * @instance:				Adapter soft state
1671 */
1672static inline void
1673megasas_dump_pending_frames(struct megasas_instance *instance)
1674{
1675	struct megasas_cmd *cmd;
1676	int i,n;
1677	union megasas_sgl *mfi_sgl;
1678	struct megasas_io_frame *ldio;
1679	struct megasas_pthru_frame *pthru;
1680	u32 sgcount;
1681	u16 max_cmd = instance->max_fw_cmds;
1682
1683	dev_err(&instance->pdev->dev, "[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
1684	dev_err(&instance->pdev->dev, "[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
1685	if (IS_DMA64)
1686		dev_err(&instance->pdev->dev, "[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
1687	else
1688		dev_err(&instance->pdev->dev, "[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
1689
1690	dev_err(&instance->pdev->dev, "[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
1691	for (i = 0; i < max_cmd; i++) {
1692		cmd = instance->cmd_list[i];
1693		if (!cmd->scmd)
1694			continue;
1695		dev_err(&instance->pdev->dev, "[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
1696		if (megasas_cmd_type(cmd->scmd) == READ_WRITE_LDIO) {
1697			ldio = (struct megasas_io_frame *)cmd->frame;
1698			mfi_sgl = &ldio->sgl;
1699			sgcount = ldio->sge_count;
1700			dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x,"
1701			" lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1702			instance->host->host_no, cmd->frame_count, ldio->cmd, ldio->target_id,
1703			le32_to_cpu(ldio->start_lba_lo), le32_to_cpu(ldio->start_lba_hi),
1704			le32_to_cpu(ldio->sense_buf_phys_addr_lo), sgcount);
1705		} else {
1706			pthru = (struct megasas_pthru_frame *) cmd->frame;
1707			mfi_sgl = &pthru->sgl;
1708			sgcount = pthru->sge_count;
1709			dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, "
1710			"lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1711			instance->host->host_no, cmd->frame_count, pthru->cmd, pthru->target_id,
1712			pthru->lun, pthru->cdb_len, le32_to_cpu(pthru->data_xfer_len),
1713			le32_to_cpu(pthru->sense_buf_phys_addr_lo), sgcount);
1714		}
1715		if (megasas_dbg_lvl & MEGASAS_DBG_LVL) {
1716			for (n = 0; n < sgcount; n++) {
1717				if (IS_DMA64)
1718					dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%llx\n",
1719						le32_to_cpu(mfi_sgl->sge64[n].length),
1720						le64_to_cpu(mfi_sgl->sge64[n].phys_addr));
1721				else
1722					dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%x\n",
1723						le32_to_cpu(mfi_sgl->sge32[n].length),
1724						le32_to_cpu(mfi_sgl->sge32[n].phys_addr));
1725			}
1726		}
1727	} /*for max_cmd*/
1728	dev_err(&instance->pdev->dev, "[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
1729	for (i = 0; i < max_cmd; i++) {
1730
1731		cmd = instance->cmd_list[i];
1732
1733		if (cmd->sync_cmd == 1)
1734			dev_err(&instance->pdev->dev, "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
1735	}
1736	dev_err(&instance->pdev->dev, "[%d]: Dumping Done\n\n",instance->host->host_no);
1737}
1738
1739u32
1740megasas_build_and_issue_cmd(struct megasas_instance *instance,
1741			    struct scsi_cmnd *scmd)
1742{
1743	struct megasas_cmd *cmd;
1744	u32 frame_count;
1745
1746	cmd = megasas_get_cmd(instance);
1747	if (!cmd)
1748		return SCSI_MLQUEUE_HOST_BUSY;
1749
1750	/*
1751	 * Logical drive command
1752	 */
1753	if (megasas_cmd_type(scmd) == READ_WRITE_LDIO)
1754		frame_count = megasas_build_ldio(instance, scmd, cmd);
1755	else
1756		frame_count = megasas_build_dcdb(instance, scmd, cmd);
1757
1758	if (!frame_count)
1759		goto out_return_cmd;
1760
1761	cmd->scmd = scmd;
1762	megasas_priv(scmd)->cmd_priv = cmd;
1763
1764	/*
1765	 * Issue the command to the FW
1766	 */
1767	atomic_inc(&instance->fw_outstanding);
1768
1769	instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
1770				cmd->frame_count-1, instance->reg_set);
1771
1772	return 0;
1773out_return_cmd:
1774	megasas_return_cmd(instance, cmd);
1775	return SCSI_MLQUEUE_HOST_BUSY;
1776}
1777
1778
1779/**
1780 * megasas_queue_command -	Queue entry point
1781 * @shost:			adapter SCSI host
1782 * @scmd:			SCSI command to be queued
1783 */
1784static int
1785megasas_queue_command(struct Scsi_Host *shost, struct scsi_cmnd *scmd)
1786{
1787	struct megasas_instance *instance;
1788	struct MR_PRIV_DEVICE *mr_device_priv_data;
1789	u32 ld_tgt_id;
1790
1791	instance = (struct megasas_instance *)
1792	    scmd->device->host->hostdata;
1793
1794	if (instance->unload == 1) {
1795		scmd->result = DID_NO_CONNECT << 16;
1796		scsi_done(scmd);
1797		return 0;
1798	}
1799
1800	if (instance->issuepend_done == 0)
1801		return SCSI_MLQUEUE_HOST_BUSY;
1802
1803
1804	/* Check for an mpio path and adjust behavior */
1805	if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) {
1806		if (megasas_check_mpio_paths(instance, scmd) ==
1807		    (DID_REQUEUE << 16)) {
1808			return SCSI_MLQUEUE_HOST_BUSY;
1809		} else {
1810			scmd->result = DID_NO_CONNECT << 16;
1811			scsi_done(scmd);
1812			return 0;
1813		}
1814	}
1815
1816	mr_device_priv_data = scmd->device->hostdata;
1817	if (!mr_device_priv_data ||
1818	    (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)) {
1819		scmd->result = DID_NO_CONNECT << 16;
1820		scsi_done(scmd);
1821		return 0;
1822	}
1823
1824	if (MEGASAS_IS_LOGICAL(scmd->device)) {
1825		ld_tgt_id = MEGASAS_TARGET_ID(scmd->device);
1826		if (instance->ld_tgtid_status[ld_tgt_id] == LD_TARGET_ID_DELETED) {
1827			scmd->result = DID_NO_CONNECT << 16;
1828			scsi_done(scmd);
1829			return 0;
1830		}
1831	}
1832
1833	if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
1834		return SCSI_MLQUEUE_HOST_BUSY;
1835
1836	if (mr_device_priv_data->tm_busy)
1837		return SCSI_MLQUEUE_DEVICE_BUSY;
1838
1839
1840	scmd->result = 0;
1841
1842	if (MEGASAS_IS_LOGICAL(scmd->device) &&
1843	    (scmd->device->id >= instance->fw_supported_vd_count ||
1844		scmd->device->lun)) {
1845		scmd->result = DID_BAD_TARGET << 16;
1846		goto out_done;
1847	}
1848
1849	if ((scmd->cmnd[0] == SYNCHRONIZE_CACHE) &&
1850	    MEGASAS_IS_LOGICAL(scmd->device) &&
1851	    (!instance->fw_sync_cache_support)) {
1852		scmd->result = DID_OK << 16;
1853		goto out_done;
1854	}
1855
1856	return instance->instancet->build_and_issue_cmd(instance, scmd);
1857
1858 out_done:
1859	scsi_done(scmd);
1860	return 0;
1861}
1862
1863static struct megasas_instance *megasas_lookup_instance(u16 host_no)
1864{
1865	int i;
1866
1867	for (i = 0; i < megasas_mgmt_info.max_index; i++) {
1868
1869		if ((megasas_mgmt_info.instance[i]) &&
1870		    (megasas_mgmt_info.instance[i]->host->host_no == host_no))
1871			return megasas_mgmt_info.instance[i];
1872	}
1873
1874	return NULL;
1875}
1876
1877/*
1878* megasas_set_dynamic_target_properties -
1879* Device property set by driver may not be static and it is required to be
1880* updated after OCR
1881*
1882* set tm_capable.
1883* set dma alignment (only for eedp protection enable vd).
1884*
1885* @sdev: OS provided scsi device
1886*
1887* Returns void
1888*/
1889void megasas_set_dynamic_target_properties(struct scsi_device *sdev,
1890		struct queue_limits *lim, bool is_target_prop)
1891{
1892	u16 pd_index = 0, ld;
1893	u32 device_id;
1894	struct megasas_instance *instance;
1895	struct fusion_context *fusion;
1896	struct MR_PRIV_DEVICE *mr_device_priv_data;
1897	struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
1898	struct MR_LD_RAID *raid;
1899	struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
1900
1901	instance = megasas_lookup_instance(sdev->host->host_no);
1902	fusion = instance->ctrl_context;
1903	mr_device_priv_data = sdev->hostdata;
1904
1905	if (!fusion || !mr_device_priv_data)
1906		return;
1907
1908	if (MEGASAS_IS_LOGICAL(sdev)) {
1909		device_id = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL)
1910					+ sdev->id;
1911		local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
1912		ld = MR_TargetIdToLdGet(device_id, local_map_ptr);
1913		if (ld >= instance->fw_supported_vd_count)
1914			return;
1915		raid = MR_LdRaidGet(ld, local_map_ptr);
1916
1917		if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER) {
1918			if (lim)
1919				lim->dma_alignment = 0x7;
1920		}
1921
1922		mr_device_priv_data->is_tm_capable =
1923			raid->capability.tmCapable;
1924
1925		if (!raid->flags.isEPD)
1926			sdev->no_write_same = 1;
1927
1928	} else if (instance->use_seqnum_jbod_fp) {
1929		pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1930			sdev->id;
1931		pd_sync = (void *)fusion->pd_seq_sync
1932				[(instance->pd_seq_map_id - 1) & 1];
1933		mr_device_priv_data->is_tm_capable =
1934			pd_sync->seq[pd_index].capability.tmCapable;
1935	}
1936
1937	if (is_target_prop && instance->tgt_prop->reset_tmo) {
1938		/*
1939		 * If FW provides a target reset timeout value, driver will use
1940		 * it. If not set, fallback to default values.
1941		 */
1942		mr_device_priv_data->target_reset_tmo =
1943			min_t(u8, instance->max_reset_tmo,
1944			      instance->tgt_prop->reset_tmo);
1945		mr_device_priv_data->task_abort_tmo = instance->task_abort_tmo;
1946	} else {
1947		mr_device_priv_data->target_reset_tmo =
1948						MEGASAS_DEFAULT_TM_TIMEOUT;
1949		mr_device_priv_data->task_abort_tmo =
1950						MEGASAS_DEFAULT_TM_TIMEOUT;
1951	}
1952}
1953
1954/*
1955 * megasas_set_nvme_device_properties -
1956 * set nomerges=2
1957 * set virtual page boundary = 4K (current mr_nvme_pg_size is 4K).
1958 * set maximum io transfer = MDTS of NVME device provided by MR firmware.
1959 *
1960 * MR firmware provides value in KB. Caller of this function converts
1961 * kb into bytes.
1962 *
1963 * e.a MDTS=5 means 2^5 * nvme page size. (In case of 4K page size,
1964 * MR firmware provides value 128 as (32 * 4K) = 128K.
1965 *
1966 * @sdev:				scsi device
1967 * @max_io_size:				maximum io transfer size
1968 *
1969 */
1970static inline void
1971megasas_set_nvme_device_properties(struct scsi_device *sdev,
1972		struct queue_limits *lim, u32 max_io_size)
1973{
1974	struct megasas_instance *instance;
1975	u32 mr_nvme_pg_size;
1976
1977	instance = (struct megasas_instance *)sdev->host->hostdata;
1978	mr_nvme_pg_size = max_t(u32, instance->nvme_page_size,
1979				MR_DEFAULT_NVME_PAGE_SIZE);
1980
1981	lim->max_hw_sectors = max_io_size / 512;
1982	lim->virt_boundary_mask = mr_nvme_pg_size - 1;
1983}
1984
1985/*
1986 * megasas_set_fw_assisted_qd -
1987 * set device queue depth to can_queue
1988 * set device queue depth to fw assisted qd
1989 *
1990 * @sdev:				scsi device
1991 * @is_target_prop			true, if fw provided target properties.
1992 */
1993static void megasas_set_fw_assisted_qd(struct scsi_device *sdev,
1994						 bool is_target_prop)
1995{
1996	u8 interface_type;
1997	u32 device_qd = MEGASAS_DEFAULT_CMD_PER_LUN;
1998	u32 tgt_device_qd;
1999	struct megasas_instance *instance;
2000	struct MR_PRIV_DEVICE *mr_device_priv_data;
2001
2002	instance = megasas_lookup_instance(sdev->host->host_no);
2003	mr_device_priv_data = sdev->hostdata;
2004	interface_type  = mr_device_priv_data->interface_type;
2005
2006	switch (interface_type) {
2007	case SAS_PD:
2008		device_qd = MEGASAS_SAS_QD;
2009		break;
2010	case SATA_PD:
2011		device_qd = MEGASAS_SATA_QD;
2012		break;
2013	case NVME_PD:
2014		device_qd = MEGASAS_NVME_QD;
2015		break;
2016	}
2017
2018	if (is_target_prop) {
2019		tgt_device_qd = le32_to_cpu(instance->tgt_prop->device_qdepth);
2020		if (tgt_device_qd)
2021			device_qd = min(instance->host->can_queue,
2022					(int)tgt_device_qd);
2023	}
2024
2025	if (instance->enable_sdev_max_qd && interface_type != UNKNOWN_DRIVE)
2026		device_qd = instance->host->can_queue;
2027
2028	scsi_change_queue_depth(sdev, device_qd);
2029}
2030
2031/*
2032 * megasas_set_static_target_properties -
2033 * Device property set by driver are static and it is not required to be
2034 * updated after OCR.
2035 *
2036 * set io timeout
2037 * set device queue depth
2038 * set nvme device properties. see - megasas_set_nvme_device_properties
2039 *
2040 * @sdev:				scsi device
2041 * @is_target_prop			true, if fw provided target properties.
2042 */
2043static void megasas_set_static_target_properties(struct scsi_device *sdev,
2044		struct queue_limits *lim, bool is_target_prop)
2045{
2046	u32 max_io_size_kb = MR_DEFAULT_NVME_MDTS_KB;
2047	struct megasas_instance *instance;
2048
2049	instance = megasas_lookup_instance(sdev->host->host_no);
2050
2051	/*
2052	 * The RAID firmware may require extended timeouts.
2053	 */
2054	blk_queue_rq_timeout(sdev->request_queue, scmd_timeout * HZ);
2055
2056	/* max_io_size_kb will be set to non zero for
2057	 * nvme based vd and syspd.
2058	 */
2059	if (is_target_prop)
2060		max_io_size_kb = le32_to_cpu(instance->tgt_prop->max_io_size_kb);
2061
2062	if (instance->nvme_page_size && max_io_size_kb)
2063		megasas_set_nvme_device_properties(sdev, lim,
2064				max_io_size_kb << 10);
2065
2066	megasas_set_fw_assisted_qd(sdev, is_target_prop);
2067}
2068
2069
2070static int megasas_sdev_configure(struct scsi_device *sdev,
2071				  struct queue_limits *lim)
2072{
2073	u16 pd_index = 0;
2074	struct megasas_instance *instance;
2075	int ret_target_prop = DCMD_FAILED;
2076	bool is_target_prop = false;
2077
2078	instance = megasas_lookup_instance(sdev->host->host_no);
2079	if (instance->pd_list_not_supported) {
2080		if (!MEGASAS_IS_LOGICAL(sdev) && sdev->type == TYPE_DISK) {
2081			pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
2082				sdev->id;
2083			if (instance->pd_list[pd_index].driveState !=
2084				MR_PD_STATE_SYSTEM)
2085				return -ENXIO;
2086		}
2087	}
2088
2089	mutex_lock(&instance->reset_mutex);
2090	/* Send DCMD to Firmware and cache the information */
2091	if ((instance->pd_info) && !MEGASAS_IS_LOGICAL(sdev))
2092		megasas_get_pd_info(instance, sdev);
2093
2094	/* Some ventura firmware may not have instance->nvme_page_size set.
2095	 * Do not send MR_DCMD_DRV_GET_TARGET_PROP
2096	 */
2097	if ((instance->tgt_prop) && (instance->nvme_page_size))
2098		ret_target_prop = megasas_get_target_prop(instance, sdev);
2099
2100	is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false;
2101	megasas_set_static_target_properties(sdev, lim, is_target_prop);
2102
2103	/* This sdev property may change post OCR */
2104	megasas_set_dynamic_target_properties(sdev, lim, is_target_prop);
2105
2106	if (!MEGASAS_IS_LOGICAL(sdev))
2107		sdev->no_vpd_size = 1;
2108
2109	mutex_unlock(&instance->reset_mutex);
2110
2111	return 0;
2112}
2113
2114static int megasas_sdev_init(struct scsi_device *sdev)
2115{
2116	u16 pd_index = 0, ld_tgt_id;
2117	struct megasas_instance *instance ;
2118	struct MR_PRIV_DEVICE *mr_device_priv_data;
2119
2120	instance = megasas_lookup_instance(sdev->host->host_no);
2121	if (!MEGASAS_IS_LOGICAL(sdev)) {
2122		/*
2123		 * Open the OS scan to the SYSTEM PD
2124		 */
2125		pd_index =
2126			(sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
2127			sdev->id;
2128		if ((instance->pd_list_not_supported ||
2129			instance->pd_list[pd_index].driveState ==
2130			MR_PD_STATE_SYSTEM)) {
2131			goto scan_target;
2132		}
2133		return -ENXIO;
2134	} else if (!MEGASAS_IS_LUN_VALID(sdev)) {
2135		sdev_printk(KERN_INFO, sdev, "%s: invalid LUN\n", __func__);
2136		return -ENXIO;
2137	}
2138
2139scan_target:
2140	mr_device_priv_data = kzalloc(sizeof(*mr_device_priv_data),
2141					GFP_KERNEL);
2142	if (!mr_device_priv_data)
2143		return -ENOMEM;
2144
2145	if (MEGASAS_IS_LOGICAL(sdev)) {
2146		ld_tgt_id = MEGASAS_TARGET_ID(sdev);
2147		instance->ld_tgtid_status[ld_tgt_id] = LD_TARGET_ID_ACTIVE;
2148		if (megasas_dbg_lvl & LD_PD_DEBUG)
2149			sdev_printk(KERN_INFO, sdev, "LD target ID %d created.\n", ld_tgt_id);
2150	}
2151
2152	sdev->hostdata = mr_device_priv_data;
2153
2154	atomic_set(&mr_device_priv_data->r1_ldio_hint,
2155		   instance->r1_ldio_hint_default);
2156	return 0;
2157}
2158
2159static void megasas_sdev_destroy(struct scsi_device *sdev)
2160{
2161	u16 ld_tgt_id;
2162	struct megasas_instance *instance;
2163
2164	instance = megasas_lookup_instance(sdev->host->host_no);
2165
2166	if (MEGASAS_IS_LOGICAL(sdev)) {
2167		if (!MEGASAS_IS_LUN_VALID(sdev)) {
2168			sdev_printk(KERN_INFO, sdev, "%s: invalid LUN\n", __func__);
2169			return;
2170		}
2171		ld_tgt_id = MEGASAS_TARGET_ID(sdev);
2172		instance->ld_tgtid_status[ld_tgt_id] = LD_TARGET_ID_DELETED;
2173		if (megasas_dbg_lvl & LD_PD_DEBUG)
2174			sdev_printk(KERN_INFO, sdev,
2175				    "LD target ID %d removed from OS stack\n", ld_tgt_id);
2176	}
2177
2178	kfree(sdev->hostdata);
2179	sdev->hostdata = NULL;
2180}
2181
2182/*
2183* megasas_complete_outstanding_ioctls - Complete outstanding ioctls after a
2184*                                       kill adapter
2185* @instance:				Adapter soft state
2186*
2187*/
2188static void megasas_complete_outstanding_ioctls(struct megasas_instance *instance)
2189{
2190	int i;
2191	struct megasas_cmd *cmd_mfi;
2192	struct megasas_cmd_fusion *cmd_fusion;
2193	struct fusion_context *fusion = instance->ctrl_context;
2194
2195	/* Find all outstanding ioctls */
2196	if (fusion) {
2197		for (i = 0; i < instance->max_fw_cmds; i++) {
2198			cmd_fusion = fusion->cmd_list[i];
2199			if (cmd_fusion->sync_cmd_idx != (u32)ULONG_MAX) {
2200				cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
2201				if (cmd_mfi->sync_cmd &&
2202				    (cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT)) {
2203					cmd_mfi->frame->hdr.cmd_status =
2204							MFI_STAT_WRONG_STATE;
2205					megasas_complete_cmd(instance,
2206							     cmd_mfi, DID_OK);
2207				}
2208			}
2209		}
2210	} else {
2211		for (i = 0; i < instance->max_fw_cmds; i++) {
2212			cmd_mfi = instance->cmd_list[i];
2213			if (cmd_mfi->sync_cmd && cmd_mfi->frame->hdr.cmd !=
2214				MFI_CMD_ABORT)
2215				megasas_complete_cmd(instance, cmd_mfi, DID_OK);
2216		}
2217	}
2218}
2219
2220
2221void megaraid_sas_kill_hba(struct megasas_instance *instance)
2222{
2223	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2224		dev_warn(&instance->pdev->dev,
2225			 "Adapter already dead, skipping kill HBA\n");
2226		return;
2227	}
2228
2229	/* Set critical error to block I/O & ioctls in case caller didn't */
2230	atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR);
2231	/* Wait 1 second to ensure IO or ioctls in build have posted */
2232	msleep(1000);
2233	if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2234		(instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
2235		(instance->adapter_type != MFI_SERIES)) {
2236		if (!instance->requestorId) {
2237			writel(MFI_STOP_ADP, &instance->reg_set->doorbell);
2238			/* Flush */
2239			readl(&instance->reg_set->doorbell);
2240		}
2241		if (instance->requestorId && instance->peerIsPresent)
2242			memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
2243	} else {
2244		writel(MFI_STOP_ADP,
2245			&instance->reg_set->inbound_doorbell);
2246	}
2247	/* Complete outstanding ioctls when adapter is killed */
2248	megasas_complete_outstanding_ioctls(instance);
2249}
2250
2251 /**
2252  * megasas_check_and_restore_queue_depth - Check if queue depth needs to be
2253  *					restored to max value
2254  * @instance:			Adapter soft state
2255  *
2256  */
2257void
2258megasas_check_and_restore_queue_depth(struct megasas_instance *instance)
2259{
2260	unsigned long flags;
2261
2262	if (instance->flag & MEGASAS_FW_BUSY
2263	    && time_after(jiffies, instance->last_time + 5 * HZ)
2264	    && atomic_read(&instance->fw_outstanding) <
2265	    instance->throttlequeuedepth + 1) {
2266
2267		spin_lock_irqsave(instance->host->host_lock, flags);
2268		instance->flag &= ~MEGASAS_FW_BUSY;
2269
2270		instance->host->can_queue = instance->cur_can_queue;
2271		spin_unlock_irqrestore(instance->host->host_lock, flags);
2272	}
2273}
2274
2275/**
2276 * megasas_complete_cmd_dpc	 -	Returns FW's controller structure
2277 * @instance_addr:			Address of adapter soft state
2278 *
2279 * Tasklet to complete cmds
2280 */
2281static void megasas_complete_cmd_dpc(unsigned long instance_addr)
2282{
2283	u32 producer;
2284	u32 consumer;
2285	u32 context;
2286	struct megasas_cmd *cmd;
2287	struct megasas_instance *instance =
2288				(struct megasas_instance *)instance_addr;
2289	unsigned long flags;
2290
2291	/* If we have already declared adapter dead, donot complete cmds */
2292	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
2293		return;
2294
2295	spin_lock_irqsave(&instance->completion_lock, flags);
2296
2297	producer = le32_to_cpu(*instance->producer);
2298	consumer = le32_to_cpu(*instance->consumer);
2299
2300	while (consumer != producer) {
2301		context = le32_to_cpu(instance->reply_queue[consumer]);
2302		if (context >= instance->max_fw_cmds) {
2303			dev_err(&instance->pdev->dev, "Unexpected context value %x\n",
2304				context);
2305			BUG();
2306		}
2307
2308		cmd = instance->cmd_list[context];
2309
2310		megasas_complete_cmd(instance, cmd, DID_OK);
2311
2312		consumer++;
2313		if (consumer == (instance->max_fw_cmds + 1)) {
2314			consumer = 0;
2315		}
2316	}
2317
2318	*instance->consumer = cpu_to_le32(producer);
2319
2320	spin_unlock_irqrestore(&instance->completion_lock, flags);
2321
2322	/*
2323	 * Check if we can restore can_queue
2324	 */
2325	megasas_check_and_restore_queue_depth(instance);
2326}
2327
2328static void megasas_sriov_heartbeat_handler(struct timer_list *t);
2329
2330/**
2331 * megasas_start_timer - Initializes sriov heartbeat timer object
2332 * @instance:		Adapter soft state
2333 *
2334 */
2335void megasas_start_timer(struct megasas_instance *instance)
2336{
2337	struct timer_list *timer = &instance->sriov_heartbeat_timer;
2338
2339	timer_setup(timer, megasas_sriov_heartbeat_handler, 0);
2340	timer->expires = jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF;
2341	add_timer(timer);
2342}
2343
2344static void
2345megasas_internal_reset_defer_cmds(struct megasas_instance *instance);
2346
2347static void
2348process_fw_state_change_wq(struct work_struct *work);
2349
2350static void megasas_do_ocr(struct megasas_instance *instance)
2351{
2352	if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
2353	(instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
2354	(instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
2355		*instance->consumer = cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
2356	}
2357	instance->instancet->disable_intr(instance);
2358	atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
2359	instance->issuepend_done = 0;
2360
2361	atomic_set(&instance->fw_outstanding, 0);
2362	megasas_internal_reset_defer_cmds(instance);
2363	process_fw_state_change_wq(&instance->work_init);
2364}
2365
2366static int megasas_get_ld_vf_affiliation_111(struct megasas_instance *instance,
2367					    int initial)
2368{
2369	struct megasas_cmd *cmd;
2370	struct megasas_dcmd_frame *dcmd;
2371	struct MR_LD_VF_AFFILIATION_111 *new_affiliation_111 = NULL;
2372	dma_addr_t new_affiliation_111_h;
2373	int ld, retval = 0;
2374	u8 thisVf;
2375
2376	cmd = megasas_get_cmd(instance);
2377
2378	if (!cmd) {
2379		dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation_111:"
2380		       "Failed to get cmd for scsi%d\n",
2381			instance->host->host_no);
2382		return -ENOMEM;
2383	}
2384
2385	dcmd = &cmd->frame->dcmd;
2386
2387	if (!instance->vf_affiliation_111) {
2388		dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF "
2389		       "affiliation for scsi%d\n", instance->host->host_no);
2390		megasas_return_cmd(instance, cmd);
2391		return -ENOMEM;
2392	}
2393
2394	if (initial)
2395			memset(instance->vf_affiliation_111, 0,
2396			       sizeof(struct MR_LD_VF_AFFILIATION_111));
2397	else {
2398		new_affiliation_111 =
2399			dma_alloc_coherent(&instance->pdev->dev,
2400					   sizeof(struct MR_LD_VF_AFFILIATION_111),
2401					   &new_affiliation_111_h, GFP_KERNEL);
2402		if (!new_affiliation_111) {
2403			dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate "
2404			       "memory for new affiliation for scsi%d\n",
2405			       instance->host->host_no);
2406			megasas_return_cmd(instance, cmd);
2407			return -ENOMEM;
2408		}
2409	}
2410
2411	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2412
2413	dcmd->cmd = MFI_CMD_DCMD;
2414	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2415	dcmd->sge_count = 1;
2416	dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2417	dcmd->timeout = 0;
2418	dcmd->pad_0 = 0;
2419	dcmd->data_xfer_len =
2420		cpu_to_le32(sizeof(struct MR_LD_VF_AFFILIATION_111));
2421	dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS_111);
2422
2423	if (initial)
2424		dcmd->sgl.sge32[0].phys_addr =
2425			cpu_to_le32(instance->vf_affiliation_111_h);
2426	else
2427		dcmd->sgl.sge32[0].phys_addr =
2428			cpu_to_le32(new_affiliation_111_h);
2429
2430	dcmd->sgl.sge32[0].length = cpu_to_le32(
2431		sizeof(struct MR_LD_VF_AFFILIATION_111));
2432
2433	dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for "
2434	       "scsi%d\n", instance->host->host_no);
2435
2436	if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) {
2437		dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD"
2438		       " failed with status 0x%x for scsi%d\n",
2439		       dcmd->cmd_status, instance->host->host_no);
2440		retval = 1; /* Do a scan if we couldn't get affiliation */
2441		goto out;
2442	}
2443
2444	if (!initial) {
2445		thisVf = new_affiliation_111->thisVf;
2446		for (ld = 0 ; ld < new_affiliation_111->vdCount; ld++)
2447			if (instance->vf_affiliation_111->map[ld].policy[thisVf] !=
2448			    new_affiliation_111->map[ld].policy[thisVf]) {
2449				dev_warn(&instance->pdev->dev, "SR-IOV: "
2450				       "Got new LD/VF affiliation for scsi%d\n",
2451				       instance->host->host_no);
2452				memcpy(instance->vf_affiliation_111,
2453				       new_affiliation_111,
2454				       sizeof(struct MR_LD_VF_AFFILIATION_111));
2455				retval = 1;
2456				goto out;
2457			}
2458	}
2459out:
2460	if (new_affiliation_111) {
2461		dma_free_coherent(&instance->pdev->dev,
2462				    sizeof(struct MR_LD_VF_AFFILIATION_111),
2463				    new_affiliation_111,
2464				    new_affiliation_111_h);
2465	}
2466
2467	megasas_return_cmd(instance, cmd);
2468
2469	return retval;
2470}
2471
2472static int megasas_get_ld_vf_affiliation_12(struct megasas_instance *instance,
2473					    int initial)
2474{
2475	struct megasas_cmd *cmd;
2476	struct megasas_dcmd_frame *dcmd;
2477	struct MR_LD_VF_AFFILIATION *new_affiliation = NULL;
2478	struct MR_LD_VF_MAP *newmap = NULL, *savedmap = NULL;
2479	dma_addr_t new_affiliation_h;
2480	int i, j, retval = 0, found = 0, doscan = 0;
2481	u8 thisVf;
2482
2483	cmd = megasas_get_cmd(instance);
2484
2485	if (!cmd) {
2486		dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation12: "
2487		       "Failed to get cmd for scsi%d\n",
2488		       instance->host->host_no);
2489		return -ENOMEM;
2490	}
2491
2492	dcmd = &cmd->frame->dcmd;
2493
2494	if (!instance->vf_affiliation) {
2495		dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF "
2496		       "affiliation for scsi%d\n", instance->host->host_no);
2497		megasas_return_cmd(instance, cmd);
2498		return -ENOMEM;
2499	}
2500
2501	if (initial)
2502		memset(instance->vf_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) *
2503		       sizeof(struct MR_LD_VF_AFFILIATION));
2504	else {
2505		new_affiliation =
2506			dma_alloc_coherent(&instance->pdev->dev,
2507					   (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION),
2508					   &new_affiliation_h, GFP_KERNEL);
2509		if (!new_affiliation) {
2510			dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate "
2511			       "memory for new affiliation for scsi%d\n",
2512			       instance->host->host_no);
2513			megasas_return_cmd(instance, cmd);
2514			return -ENOMEM;
2515		}
2516	}
2517
2518	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2519
2520	dcmd->cmd = MFI_CMD_DCMD;
2521	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2522	dcmd->sge_count = 1;
2523	dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2524	dcmd->timeout = 0;
2525	dcmd->pad_0 = 0;
2526	dcmd->data_xfer_len = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2527		sizeof(struct MR_LD_VF_AFFILIATION));
2528	dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS);
2529
2530	if (initial)
2531		dcmd->sgl.sge32[0].phys_addr =
2532			cpu_to_le32(instance->vf_affiliation_h);
2533	else
2534		dcmd->sgl.sge32[0].phys_addr =
2535			cpu_to_le32(new_affiliation_h);
2536
2537	dcmd->sgl.sge32[0].length = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2538		sizeof(struct MR_LD_VF_AFFILIATION));
2539
2540	dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for "
2541	       "scsi%d\n", instance->host->host_no);
2542
2543
2544	if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) {
2545		dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD"
2546		       " failed with status 0x%x for scsi%d\n",
2547		       dcmd->cmd_status, instance->host->host_no);
2548		retval = 1; /* Do a scan if we couldn't get affiliation */
2549		goto out;
2550	}
2551
2552	if (!initial) {
2553		if (!new_affiliation->ldCount) {
2554			dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF "
2555			       "affiliation for passive path for scsi%d\n",
2556			       instance->host->host_no);
2557			retval = 1;
2558			goto out;
2559		}
2560		newmap = new_affiliation->map;
2561		savedmap = instance->vf_affiliation->map;
2562		thisVf = new_affiliation->thisVf;
2563		for (i = 0 ; i < new_affiliation->ldCount; i++) {
2564			found = 0;
2565			for (j = 0; j < instance->vf_affiliation->ldCount;
2566			     j++) {
2567				if (newmap->ref.targetId ==
2568				    savedmap->ref.targetId) {
2569					found = 1;
2570					if (newmap->policy[thisVf] !=
2571					    savedmap->policy[thisVf]) {
2572						doscan = 1;
2573						goto out;
2574					}
2575				}
2576				savedmap = (struct MR_LD_VF_MAP *)
2577					((unsigned char *)savedmap +
2578					 savedmap->size);
2579			}
2580			if (!found && newmap->policy[thisVf] !=
2581			    MR_LD_ACCESS_HIDDEN) {
2582				doscan = 1;
2583				goto out;
2584			}
2585			newmap = (struct MR_LD_VF_MAP *)
2586				((unsigned char *)newmap + newmap->size);
2587		}
2588
2589		newmap = new_affiliation->map;
2590		savedmap = instance->vf_affiliation->map;
2591
2592		for (i = 0 ; i < instance->vf_affiliation->ldCount; i++) {
2593			found = 0;
2594			for (j = 0 ; j < new_affiliation->ldCount; j++) {
2595				if (savedmap->ref.targetId ==
2596				    newmap->ref.targetId) {
2597					found = 1;
2598					if (savedmap->policy[thisVf] !=
2599					    newmap->policy[thisVf]) {
2600						doscan = 1;
2601						goto out;
2602					}
2603				}
2604				newmap = (struct MR_LD_VF_MAP *)
2605					((unsigned char *)newmap +
2606					 newmap->size);
2607			}
2608			if (!found && savedmap->policy[thisVf] !=
2609			    MR_LD_ACCESS_HIDDEN) {
2610				doscan = 1;
2611				goto out;
2612			}
2613			savedmap = (struct MR_LD_VF_MAP *)
2614				((unsigned char *)savedmap +
2615				 savedmap->size);
2616		}
2617	}
2618out:
2619	if (doscan) {
2620		dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF "
2621		       "affiliation for scsi%d\n", instance->host->host_no);
2622		memcpy(instance->vf_affiliation, new_affiliation,
2623		       new_affiliation->size);
2624		retval = 1;
2625	}
2626
2627	if (new_affiliation)
2628		dma_free_coherent(&instance->pdev->dev,
2629				    (MAX_LOGICAL_DRIVES + 1) *
2630				    sizeof(struct MR_LD_VF_AFFILIATION),
2631				    new_affiliation, new_affiliation_h);
2632	megasas_return_cmd(instance, cmd);
2633
2634	return retval;
2635}
2636
2637/* This function will get the current SR-IOV LD/VF affiliation */
2638static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
2639	int initial)
2640{
2641	int retval;
2642
2643	if (instance->PlasmaFW111)
2644		retval = megasas_get_ld_vf_affiliation_111(instance, initial);
2645	else
2646		retval = megasas_get_ld_vf_affiliation_12(instance, initial);
2647	return retval;
2648}
2649
2650/* This function will tell FW to start the SR-IOV heartbeat */
2651int megasas_sriov_start_heartbeat(struct megasas_instance *instance,
2652					 int initial)
2653{
2654	struct megasas_cmd *cmd;
2655	struct megasas_dcmd_frame *dcmd;
2656	int retval = 0;
2657
2658	cmd = megasas_get_cmd(instance);
2659
2660	if (!cmd) {
2661		dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_sriov_start_heartbeat: "
2662		       "Failed to get cmd for scsi%d\n",
2663		       instance->host->host_no);
2664		return -ENOMEM;
2665	}
2666
2667	dcmd = &cmd->frame->dcmd;
2668
2669	if (initial) {
2670		instance->hb_host_mem =
2671			dma_alloc_coherent(&instance->pdev->dev,
2672					   sizeof(struct MR_CTRL_HB_HOST_MEM),
2673					   &instance->hb_host_mem_h,
2674					   GFP_KERNEL);
2675		if (!instance->hb_host_mem) {
2676			dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate"
2677			       " memory for heartbeat host memory for scsi%d\n",
2678			       instance->host->host_no);
2679			retval = -ENOMEM;
2680			goto out;
2681		}
2682	}
2683
2684	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2685
2686	dcmd->mbox.s[0] = cpu_to_le16(sizeof(struct MR_CTRL_HB_HOST_MEM));
2687	dcmd->cmd = MFI_CMD_DCMD;
2688	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2689	dcmd->sge_count = 1;
2690	dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2691	dcmd->timeout = 0;
2692	dcmd->pad_0 = 0;
2693	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_CTRL_HB_HOST_MEM));
2694	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SHARED_HOST_MEM_ALLOC);
2695
2696	megasas_set_dma_settings(instance, dcmd, instance->hb_host_mem_h,
2697				 sizeof(struct MR_CTRL_HB_HOST_MEM));
2698
2699	dev_warn(&instance->pdev->dev, "SR-IOV: Starting heartbeat for scsi%d\n",
2700	       instance->host->host_no);
2701
2702	if ((instance->adapter_type != MFI_SERIES) &&
2703	    !instance->mask_interrupts)
2704		retval = megasas_issue_blocked_cmd(instance, cmd,
2705			MEGASAS_ROUTINE_WAIT_TIME_VF);
2706	else
2707		retval = megasas_issue_polled(instance, cmd);
2708
2709	if (retval) {
2710		dev_warn(&instance->pdev->dev, "SR-IOV: MR_DCMD_CTRL_SHARED_HOST"
2711			"_MEM_ALLOC DCMD %s for scsi%d\n",
2712			(dcmd->cmd_status == MFI_STAT_INVALID_STATUS) ?
2713			"timed out" : "failed", instance->host->host_no);
2714		retval = 1;
2715	}
2716
2717out:
2718	megasas_return_cmd(instance, cmd);
2719
2720	return retval;
2721}
2722
2723/* Handler for SR-IOV heartbeat */
2724static void megasas_sriov_heartbeat_handler(struct timer_list *t)
2725{
2726	struct megasas_instance *instance =
2727		timer_container_of(instance, t, sriov_heartbeat_timer);
2728
2729	if (instance->hb_host_mem->HB.fwCounter !=
2730	    instance->hb_host_mem->HB.driverCounter) {
2731		instance->hb_host_mem->HB.driverCounter =
2732			instance->hb_host_mem->HB.fwCounter;
2733		mod_timer(&instance->sriov_heartbeat_timer,
2734			  jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
2735	} else {
2736		dev_warn(&instance->pdev->dev, "SR-IOV: Heartbeat never "
2737		       "completed for scsi%d\n", instance->host->host_no);
2738		schedule_work(&instance->work_init);
2739	}
2740}
2741
2742/**
2743 * megasas_wait_for_outstanding -	Wait for all outstanding cmds
2744 * @instance:				Adapter soft state
2745 *
2746 * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to
2747 * complete all its outstanding commands. Returns error if one or more IOs
2748 * are pending after this time period. It also marks the controller dead.
2749 */
2750static int megasas_wait_for_outstanding(struct megasas_instance *instance)
2751{
2752	int i, sl, outstanding;
2753	u32 reset_index;
2754	u32 wait_time = MEGASAS_RESET_WAIT_TIME;
2755	unsigned long flags;
2756	struct list_head clist_local;
2757	struct megasas_cmd *reset_cmd;
2758	u32 fw_state;
2759
2760	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2761		dev_info(&instance->pdev->dev, "%s:%d HBA is killed.\n",
2762		__func__, __LINE__);
2763		return FAILED;
2764	}
2765
2766	if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
2767
2768		INIT_LIST_HEAD(&clist_local);
2769		spin_lock_irqsave(&instance->hba_lock, flags);
2770		list_splice_init(&instance->internal_reset_pending_q,
2771				&clist_local);
2772		spin_unlock_irqrestore(&instance->hba_lock, flags);
2773
2774		dev_notice(&instance->pdev->dev, "HBA reset wait ...\n");
2775		for (i = 0; i < wait_time; i++) {
2776			msleep(1000);
2777			if (atomic_read(&instance->adprecovery) == MEGASAS_HBA_OPERATIONAL)
2778				break;
2779		}
2780
2781		if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
2782			dev_notice(&instance->pdev->dev, "reset: Stopping HBA.\n");
2783			atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR);
2784			return FAILED;
2785		}
2786
2787		reset_index = 0;
2788		while (!list_empty(&clist_local)) {
2789			reset_cmd = list_entry((&clist_local)->next,
2790						struct megasas_cmd, list);
2791			list_del_init(&reset_cmd->list);
2792			if (reset_cmd->scmd) {
2793				reset_cmd->scmd->result = DID_REQUEUE << 16;
2794				dev_notice(&instance->pdev->dev, "%d:%p reset [%02x]\n",
2795					reset_index, reset_cmd,
2796					reset_cmd->scmd->cmnd[0]);
2797
2798				scsi_done(reset_cmd->scmd);
2799				megasas_return_cmd(instance, reset_cmd);
2800			} else if (reset_cmd->sync_cmd) {
2801				dev_notice(&instance->pdev->dev, "%p synch cmds"
2802						"reset queue\n",
2803						reset_cmd);
2804
2805				reset_cmd->cmd_status_drv = DCMD_INIT;
2806				instance->instancet->fire_cmd(instance,
2807						reset_cmd->frame_phys_addr,
2808						0, instance->reg_set);
2809			} else {
2810				dev_notice(&instance->pdev->dev, "%p unexpected"
2811					"cmds lst\n",
2812					reset_cmd);
2813			}
2814			reset_index++;
2815		}
2816
2817		return SUCCESS;
2818	}
2819
2820	for (i = 0; i < resetwaittime; i++) {
2821		outstanding = atomic_read(&instance->fw_outstanding);
2822
2823		if (!outstanding)
2824			break;
2825
2826		if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
2827			dev_notice(&instance->pdev->dev, "[%2d]waiting for %d "
2828			       "commands to complete\n",i,outstanding);
2829			/*
2830			 * Call cmd completion routine. Cmd to be
2831			 * be completed directly without depending on isr.
2832			 */
2833			megasas_complete_cmd_dpc((unsigned long)instance);
2834		}
2835
2836		msleep(1000);
2837	}
2838
2839	i = 0;
2840	outstanding = atomic_read(&instance->fw_outstanding);
2841	fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK;
2842
2843	if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL)))
2844		goto no_outstanding;
2845
2846	if (instance->disableOnlineCtrlReset)
2847		goto kill_hba_and_failed;
2848	do {
2849		if ((fw_state == MFI_STATE_FAULT) || atomic_read(&instance->fw_outstanding)) {
2850			dev_info(&instance->pdev->dev,
2851				"%s:%d waiting_for_outstanding: before issue OCR. FW state = 0x%x, outstanding 0x%x\n",
2852				__func__, __LINE__, fw_state, atomic_read(&instance->fw_outstanding));
2853			if (i == 3)
2854				goto kill_hba_and_failed;
2855			megasas_do_ocr(instance);
2856
2857			if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2858				dev_info(&instance->pdev->dev, "%s:%d OCR failed and HBA is killed.\n",
2859				__func__, __LINE__);
2860				return FAILED;
2861			}
2862			dev_info(&instance->pdev->dev, "%s:%d waiting_for_outstanding: after issue OCR.\n",
2863				__func__, __LINE__);
2864
2865			for (sl = 0; sl < 10; sl++)
2866				msleep(500);
2867
2868			outstanding = atomic_read(&instance->fw_outstanding);
2869
2870			fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK;
2871			if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL)))
2872				goto no_outstanding;
2873		}
2874		i++;
2875	} while (i <= 3);
2876
2877no_outstanding:
2878
2879	dev_info(&instance->pdev->dev, "%s:%d no more pending commands remain after reset handling.\n",
2880		__func__, __LINE__);
2881	return SUCCESS;
2882
2883kill_hba_and_failed:
2884
2885	/* Reset not supported, kill adapter */
2886	dev_info(&instance->pdev->dev, "%s:%d killing adapter scsi%d"
2887		" disableOnlineCtrlReset %d fw_outstanding %d \n",
2888		__func__, __LINE__, instance->host->host_no, instance->disableOnlineCtrlReset,
2889		atomic_read(&instance->fw_outstanding));
2890	megasas_dump_pending_frames(instance);
2891	megaraid_sas_kill_hba(instance);
2892
2893	return FAILED;
2894}
2895
2896/**
2897 * megasas_generic_reset -	Generic reset routine
2898 * @scmd:			Mid-layer SCSI command
2899 *
2900 * This routine implements a generic reset handler for device, bus and host
2901 * reset requests. Device, bus and host specific reset handlers can use this
2902 * function after they do their specific tasks.
2903 */
2904static int megasas_generic_reset(struct scsi_cmnd *scmd)
2905{
2906	int ret_val;
2907	struct megasas_instance *instance;
2908
2909	instance = (struct megasas_instance *)scmd->device->host->hostdata;
2910
2911	scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n",
2912		 scmd->cmnd[0], scmd->retries);
2913
2914	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2915		dev_err(&instance->pdev->dev, "cannot recover from previous reset failures\n");
2916		return FAILED;
2917	}
2918
2919	ret_val = megasas_wait_for_outstanding(instance);
2920	if (ret_val == SUCCESS)
2921		dev_notice(&instance->pdev->dev, "reset successful\n");
2922	else
2923		dev_err(&instance->pdev->dev, "failed to do reset\n");
2924
2925	return ret_val;
2926}
2927
2928/**
2929 * megasas_reset_timer - quiesce the adapter if required
2930 * @scmd:		scsi cmnd
2931 *
2932 * Sets the FW busy flag and reduces the host->can_queue if the
2933 * cmd has not been completed within the timeout period.
2934 */
2935static enum scsi_timeout_action megasas_reset_timer(struct scsi_cmnd *scmd)
2936{
2937	struct megasas_instance *instance;
2938	unsigned long flags;
2939
2940	if (time_after(jiffies, scmd->jiffies_at_alloc +
2941				(scmd_timeout * 2) * HZ)) {
2942		return SCSI_EH_NOT_HANDLED;
2943	}
2944
2945	instance = (struct megasas_instance *)scmd->device->host->hostdata;
2946	if (!(instance->flag & MEGASAS_FW_BUSY)) {
2947		/* FW is busy, throttle IO */
2948		spin_lock_irqsave(instance->host->host_lock, flags);
2949
2950		instance->host->can_queue = instance->throttlequeuedepth;
2951		instance->last_time = jiffies;
2952		instance->flag |= MEGASAS_FW_BUSY;
2953
2954		spin_unlock_irqrestore(instance->host->host_lock, flags);
2955	}
2956	return SCSI_EH_RESET_TIMER;
2957}
2958
2959/**
2960 * megasas_dump -	This function will print hexdump of provided buffer.
2961 * @buf:		Buffer to be dumped
2962 * @sz:		Size in bytes
2963 * @format:		Different formats of dumping e.g. format=n will
2964 *			cause only 'n' 32 bit words to be dumped in a single
2965 *			line.
2966 */
2967inline void
2968megasas_dump(void *buf, int sz, int format)
2969{
2970	int i;
2971	__le32 *buf_loc = (__le32 *)buf;
2972
2973	for (i = 0; i < (sz / sizeof(__le32)); i++) {
2974		if ((i % format) == 0) {
2975			if (i != 0)
2976				printk(KERN_CONT "\n");
2977			printk(KERN_CONT "%08x: ", (i * 4));
2978		}
2979		printk(KERN_CONT "%08x ", le32_to_cpu(buf_loc[i]));
2980	}
2981	printk(KERN_CONT "\n");
2982}
2983
2984/**
2985 * megasas_dump_reg_set -	This function will print hexdump of register set
2986 * @reg_set:	Register set to be dumped
2987 */
2988inline void
2989megasas_dump_reg_set(void __iomem *reg_set)
2990{
2991	unsigned int i, sz = 256;
2992	u32 __iomem *reg = (u32 __iomem *)reg_set;
2993
2994	for (i = 0; i < (sz / sizeof(u32)); i++)
2995		printk("%08x: %08x\n", (i * 4), readl(&reg[i]));
2996}
2997
2998/**
2999 * megasas_dump_fusion_io -	This function will print key details
3000 *				of SCSI IO
3001 * @scmd:			SCSI command pointer of SCSI IO
3002 */
3003void
3004megasas_dump_fusion_io(struct scsi_cmnd *scmd)
3005{
3006	struct megasas_cmd_fusion *cmd = megasas_priv(scmd)->cmd_priv;
3007	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
3008	struct megasas_instance *instance;
3009
3010	instance = (struct megasas_instance *)scmd->device->host->hostdata;
3011
3012	scmd_printk(KERN_INFO, scmd,
3013		    "scmd: (0x%p)  retries: 0x%x  allowed: 0x%x\n",
3014		    scmd, scmd->retries, scmd->allowed);
3015	scsi_print_command(scmd);
3016
3017	if (cmd) {
3018		req_desc = (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)cmd->request_desc;
3019		scmd_printk(KERN_INFO, scmd, "Request descriptor details:\n");
3020		scmd_printk(KERN_INFO, scmd,
3021			    "RequestFlags:0x%x  MSIxIndex:0x%x  SMID:0x%x  LMID:0x%x  DevHandle:0x%x\n",
3022			    req_desc->SCSIIO.RequestFlags,
3023			    req_desc->SCSIIO.MSIxIndex, req_desc->SCSIIO.SMID,
3024			    req_desc->SCSIIO.LMID, req_desc->SCSIIO.DevHandle);
3025
3026		printk(KERN_INFO "IO request frame:\n");
3027		megasas_dump(cmd->io_request,
3028			     MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE, 8);
3029		printk(KERN_INFO "Chain frame:\n");
3030		megasas_dump(cmd->sg_frame,
3031			     instance->max_chain_frame_sz, 8);
3032	}
3033
3034}
3035
3036/*
3037 * megasas_dump_sys_regs - This function will dump system registers through
3038 *			    sysfs.
3039 * @reg_set:		    Pointer to System register set.
3040 * @buf:		    Buffer to which output is to be written.
3041 * @return:		    Number of bytes written to buffer.
3042 */
3043static inline ssize_t
3044megasas_dump_sys_regs(void __iomem *reg_set, char *buf)
3045{
3046	unsigned int i, sz = 256;
3047	int bytes_wrote = 0;
3048	char *loc = (char *)buf;
3049	u32 __iomem *reg = (u32 __iomem *)reg_set;
3050
3051	for (i = 0; i < sz / sizeof(u32); i++) {
3052		bytes_wrote += scnprintf(loc + bytes_wrote,
3053					 PAGE_SIZE - bytes_wrote,
3054					 "%08x: %08x\n", (i * 4),
3055					 readl(&reg[i]));
3056	}
3057	return bytes_wrote;
3058}
3059
3060/**
3061 * megasas_reset_bus_host -	Bus & host reset handler entry point
3062 * @scmd:			Mid-layer SCSI command
3063 */
3064static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
3065{
3066	int ret;
3067	struct megasas_instance *instance;
3068
3069	instance = (struct megasas_instance *)scmd->device->host->hostdata;
3070
3071	scmd_printk(KERN_INFO, scmd,
3072		"OCR is requested due to IO timeout!!\n");
3073
3074	scmd_printk(KERN_INFO, scmd,
3075		"SCSI host state: %d  SCSI host busy: %d  FW outstanding: %d\n",
3076		scmd->device->host->shost_state,
3077		scsi_host_busy(scmd->device->host),
3078		atomic_read(&instance->fw_outstanding));
3079	/*
3080	 * First wait for all commands to complete
3081	 */
3082	if (instance->adapter_type == MFI_SERIES) {
3083		ret = megasas_generic_reset(scmd);
3084	} else {
3085		megasas_dump_fusion_io(scmd);
3086		ret = megasas_reset_fusion(scmd->device->host,
3087				SCSIIO_TIMEOUT_OCR);
3088	}
3089
3090	return ret;
3091}
3092
3093/**
3094 * megasas_task_abort - Issues task abort request to firmware
3095 *			(supported only for fusion adapters)
3096 * @scmd:		SCSI command pointer
3097 */
3098static int megasas_task_abort(struct scsi_cmnd *scmd)
3099{
3100	int ret;
3101	struct megasas_instance *instance;
3102
3103	instance = (struct megasas_instance *)scmd->device->host->hostdata;
3104
3105	if (instance->adapter_type != MFI_SERIES)
3106		ret = megasas_task_abort_fusion(scmd);
3107	else {
3108		sdev_printk(KERN_NOTICE, scmd->device, "TASK ABORT not supported\n");
3109		ret = FAILED;
3110	}
3111
3112	return ret;
3113}
3114
3115/**
3116 * megasas_reset_target:  Issues target reset request to firmware
3117 *                        (supported only for fusion adapters)
3118 * @scmd:                 SCSI command pointer
3119 */
3120static int megasas_reset_target(struct scsi_cmnd *scmd)
3121{
3122	int ret;
3123	struct megasas_instance *instance;
3124
3125	instance = (struct megasas_instance *)scmd->device->host->hostdata;
3126
3127	if (instance->adapter_type != MFI_SERIES)
3128		ret = megasas_reset_target_fusion(scmd);
3129	else {
3130		sdev_printk(KERN_NOTICE, scmd->device, "TARGET RESET not supported\n");
3131		ret = FAILED;
3132	}
3133
3134	return ret;
3135}
3136
3137/**
3138 * megasas_bios_param - Returns disk geometry for a disk
3139 * @sdev:		device handle
3140 * @unused:		gendisk
3141 * @capacity:		drive capacity
3142 * @geom:		geometry parameters
3143 */
3144static int
3145megasas_bios_param(struct scsi_device *sdev, struct gendisk *unused,
3146		 sector_t capacity, int geom[])
3147{
3148	int heads;
3149	int sectors;
3150	sector_t cylinders;
3151	unsigned long tmp;
3152
3153	/* Default heads (64) & sectors (32) */
3154	heads = 64;
3155	sectors = 32;
3156
3157	tmp = heads * sectors;
3158	cylinders = capacity;
3159
3160	sector_div(cylinders, tmp);
3161
3162	/*
3163	 * Handle extended translation size for logical drives > 1Gb
3164	 */
3165
3166	if (capacity >= 0x200000) {
3167		heads = 255;
3168		sectors = 63;
3169		tmp = heads*sectors;
3170		cylinders = capacity;
3171		sector_div(cylinders, tmp);
3172	}
3173
3174	geom[0] = heads;
3175	geom[1] = sectors;
3176	geom[2] = cylinders;
3177
3178	return 0;
3179}
3180
3181static void megasas_map_queues(struct Scsi_Host *shost)
3182{
3183	struct megasas_instance *instance;
3184	int qoff = 0, offset;
3185	struct blk_mq_queue_map *map;
3186
3187	instance = (struct megasas_instance *)shost->hostdata;
3188
3189	if (shost->nr_hw_queues == 1)
3190		return;
3191
3192	offset = instance->low_latency_index_start;
3193
3194	/* Setup Default hctx */
3195	map = &shost->tag_set.map[HCTX_TYPE_DEFAULT];
3196	map->nr_queues = instance->msix_vectors - offset;
3197	map->queue_offset = 0;
3198	blk_mq_map_hw_queues(map, &instance->pdev->dev, offset);
3199	qoff += map->nr_queues;
3200	offset += map->nr_queues;
3201
3202	/* we never use READ queue, so can't cheat blk-mq */
3203	shost->tag_set.map[HCTX_TYPE_READ].nr_queues = 0;
3204
3205	/* Setup Poll hctx */
3206	map = &shost->tag_set.map[HCTX_TYPE_POLL];
3207	map->nr_queues = instance->iopoll_q_count;
3208	if (map->nr_queues) {
3209		/*
3210		 * The poll queue(s) doesn't have an IRQ (and hence IRQ
3211		 * affinity), so use the regular blk-mq cpu mapping
3212		 */
3213		map->queue_offset = qoff;
3214		blk_mq_map_queues(map);
3215	}
3216}
3217
3218static void megasas_aen_polling(struct work_struct *work);
3219
3220/**
3221 * megasas_service_aen -	Processes an event notification
3222 * @instance:			Adapter soft state
3223 * @cmd:			AEN command completed by the ISR
3224 *
3225 * For AEN, driver sends a command down to FW that is held by the FW till an
3226 * event occurs. When an event of interest occurs, FW completes the command
3227 * that it was previously holding.
3228 *
3229 * This routines sends SIGIO signal to processes that have registered with the
3230 * driver for AEN.
3231 */
3232static void
3233megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
3234{
3235	unsigned long flags;
3236
3237	/*
3238	 * Don't signal app if it is just an aborted previously registered aen
3239	 */
3240	if ((!cmd->abort_aen) && (instance->unload == 0)) {
3241		spin_lock_irqsave(&poll_aen_lock, flags);
3242		megasas_poll_wait_aen = 1;
3243		spin_unlock_irqrestore(&poll_aen_lock, flags);
3244		wake_up(&megasas_poll_wait);
3245		kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
3246	}
3247	else
3248		cmd->abort_aen = 0;
3249
3250	instance->aen_cmd = NULL;
3251
3252	megasas_return_cmd(instance, cmd);
3253
3254	if ((instance->unload == 0) &&
3255		((instance->issuepend_done == 1))) {
3256		struct megasas_aen_event *ev;
3257
3258		ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
3259		if (!ev) {
3260			dev_err(&instance->pdev->dev, "megasas_service_aen: out of memory\n");
3261		} else {
3262			ev->instance = instance;
3263			instance->ev = ev;
3264			INIT_DELAYED_WORK(&ev->hotplug_work,
3265					  megasas_aen_polling);
3266			schedule_delayed_work(&ev->hotplug_work, 0);
3267		}
3268	}
3269}
3270
3271static ssize_t
3272fw_crash_buffer_store(struct device *cdev,
3273	struct device_attribute *attr, const char *buf, size_t count)
3274{
3275	struct Scsi_Host *shost = class_to_shost(cdev);
3276	struct megasas_instance *instance =
3277		(struct megasas_instance *) shost->hostdata;
3278	int val = 0;
3279
3280	if (kstrtoint(buf, 0, &val) != 0)
3281		return -EINVAL;
3282
3283	mutex_lock(&instance->crashdump_lock);
3284	instance->fw_crash_buffer_offset = val;
3285	mutex_unlock(&instance->crashdump_lock);
3286	return strlen(buf);
3287}
3288
3289static ssize_t
3290fw_crash_buffer_show(struct device *cdev,
3291	struct device_attribute *attr, char *buf)
3292{
3293	struct Scsi_Host *shost = class_to_shost(cdev);
3294	struct megasas_instance *instance =
3295		(struct megasas_instance *) shost->hostdata;
3296	u32 size;
3297	unsigned long dmachunk = CRASH_DMA_BUF_SIZE;
3298	unsigned long chunk_left_bytes;
3299	unsigned long src_addr;
3300	u32 buff_offset;
3301
3302	mutex_lock(&instance->crashdump_lock);
3303	buff_offset = instance->fw_crash_buffer_offset;
3304	if (!instance->crash_dump_buf ||
3305		!((instance->fw_crash_state == AVAILABLE) ||
3306		(instance->fw_crash_state == COPYING))) {
3307		dev_err(&instance->pdev->dev,
3308			"Firmware crash dump is not available\n");
3309		mutex_unlock(&instance->crashdump_lock);
3310		return -EINVAL;
3311	}
3312
3313	if (buff_offset > (instance->fw_crash_buffer_size * dmachunk)) {
3314		dev_err(&instance->pdev->dev,
3315			"Firmware crash dump offset is out of range\n");
3316		mutex_unlock(&instance->crashdump_lock);
3317		return 0;
3318	}
3319
3320	size = (instance->fw_crash_buffer_size * dmachunk) - buff_offset;
3321	chunk_left_bytes = dmachunk - (buff_offset % dmachunk);
3322	size = (size > chunk_left_bytes) ? chunk_left_bytes : size;
3323	size = (size >= PAGE_SIZE) ? (PAGE_SIZE - 1) : size;
3324
3325	src_addr = (unsigned long)instance->crash_buf[buff_offset / dmachunk] +
3326		(buff_offset % dmachunk);
3327	memcpy(buf, (void *)src_addr, size);
3328	mutex_unlock(&instance->crashdump_lock);
3329
3330	return size;
3331}
3332
3333static ssize_t
3334fw_crash_buffer_size_show(struct device *cdev,
3335	struct device_attribute *attr, char *buf)
3336{
3337	struct Scsi_Host *shost = class_to_shost(cdev);
3338	struct megasas_instance *instance =
3339		(struct megasas_instance *) shost->hostdata;
3340
3341	return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)
3342		((instance->fw_crash_buffer_size) * 1024 * 1024)/PAGE_SIZE);
3343}
3344
3345static ssize_t
3346fw_crash_state_store(struct device *cdev,
3347	struct device_attribute *attr, const char *buf, size_t count)
3348{
3349	struct Scsi_Host *shost = class_to_shost(cdev);
3350	struct megasas_instance *instance =
3351		(struct megasas_instance *) shost->hostdata;
3352	int val = 0;
3353
3354	if (kstrtoint(buf, 0, &val) != 0)
3355		return -EINVAL;
3356
3357	if ((val <= AVAILABLE || val > COPY_ERROR)) {
3358		dev_err(&instance->pdev->dev, "application updates invalid "
3359			"firmware crash state\n");
3360		return -EINVAL;
3361	}
3362
3363	instance->fw_crash_state = val;
3364
3365	if ((val == COPIED) || (val == COPY_ERROR)) {
3366		mutex_lock(&instance->crashdump_lock);
3367		megasas_free_host_crash_buffer(instance);
3368		mutex_unlock(&instance->crashdump_lock);
3369		if (val == COPY_ERROR)
3370			dev_info(&instance->pdev->dev, "application failed to "
3371				"copy Firmware crash dump\n");
3372		else
3373			dev_info(&instance->pdev->dev, "Firmware crash dump "
3374				"copied successfully\n");
3375	}
3376	return strlen(buf);
3377}
3378
3379static ssize_t
3380fw_crash_state_show(struct device *cdev,
3381	struct device_attribute *attr, char *buf)
3382{
3383	struct Scsi_Host *shost = class_to_shost(cdev);
3384	struct megasas_instance *instance =
3385		(struct megasas_instance *) shost->hostdata;
3386
3387	return snprintf(buf, PAGE_SIZE, "%d\n", instance->fw_crash_state);
3388}
3389
3390static ssize_t
3391page_size_show(struct device *cdev,
3392	struct device_attribute *attr, char *buf)
3393{
3394	return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)PAGE_SIZE - 1);
3395}
3396
3397static ssize_t
3398ldio_outstanding_show(struct device *cdev, struct device_attribute *attr,
3399	char *buf)
3400{
3401	struct Scsi_Host *shost = class_to_shost(cdev);
3402	struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3403
3404	return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->ldio_outstanding));
3405}
3406
3407static ssize_t
3408fw_cmds_outstanding_show(struct device *cdev,
3409				 struct device_attribute *attr, char *buf)
3410{
3411	struct Scsi_Host *shost = class_to_shost(cdev);
3412	struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3413
3414	return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->fw_outstanding));
3415}
3416
3417static ssize_t
3418enable_sdev_max_qd_show(struct device *cdev,
3419	struct device_attribute *attr, char *buf)
3420{
3421	struct Scsi_Host *shost = class_to_shost(cdev);
3422	struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3423
3424	return snprintf(buf, PAGE_SIZE, "%d\n", instance->enable_sdev_max_qd);
3425}
3426
3427static ssize_t
3428enable_sdev_max_qd_store(struct device *cdev,
3429	struct device_attribute *attr, const char *buf, size_t count)
3430{
3431	struct Scsi_Host *shost = class_to_shost(cdev);
3432	struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3433	u32 val = 0;
3434	bool is_target_prop;
3435	int ret_target_prop = DCMD_FAILED;
3436	struct scsi_device *sdev;
3437
3438	if (kstrtou32(buf, 0, &val) != 0) {
3439		pr_err("megasas: could not set enable_sdev_max_qd\n");
3440		return -EINVAL;
3441	}
3442
3443	mutex_lock(&instance->reset_mutex);
3444	if (val)
3445		instance->enable_sdev_max_qd = true;
3446	else
3447		instance->enable_sdev_max_qd = false;
3448
3449	shost_for_each_device(sdev, shost) {
3450		ret_target_prop = megasas_get_target_prop(instance, sdev);
3451		is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false;
3452		megasas_set_fw_assisted_qd(sdev, is_target_prop);
3453	}
3454	mutex_unlock(&instance->reset_mutex);
3455
3456	return strlen(buf);
3457}
3458
3459static ssize_t
3460dump_system_regs_show(struct device *cdev,
3461			       struct device_attribute *attr, char *buf)
3462{
3463	struct Scsi_Host *shost = class_to_shost(cdev);
3464	struct megasas_instance *instance =
3465			(struct megasas_instance *)shost->hostdata;
3466
3467	return megasas_dump_sys_regs(instance->reg_set, buf);
3468}
3469
3470static ssize_t
3471raid_map_id_show(struct device *cdev, struct device_attribute *attr,
3472			  char *buf)
3473{
3474	struct Scsi_Host *shost = class_to_shost(cdev);
3475	struct megasas_instance *instance =
3476			(struct megasas_instance *)shost->hostdata;
3477
3478	return snprintf(buf, PAGE_SIZE, "%ld\n",
3479			(unsigned long)instance->map_id);
3480}
3481
3482static DEVICE_ATTR_RW(fw_crash_buffer);
3483static DEVICE_ATTR_RO(fw_crash_buffer_size);
3484static DEVICE_ATTR_RW(fw_crash_state);
3485static DEVICE_ATTR_RO(page_size);
3486static DEVICE_ATTR_RO(ldio_outstanding);
3487static DEVICE_ATTR_RO(fw_cmds_outstanding);
3488static DEVICE_ATTR_RW(enable_sdev_max_qd);
3489static DEVICE_ATTR_RO(dump_system_regs);
3490static DEVICE_ATTR_RO(raid_map_id);
3491
3492static struct attribute *megaraid_host_attrs[] = {
3493	&dev_attr_fw_crash_buffer_size.attr,
3494	&dev_attr_fw_crash_buffer.attr,
3495	&dev_attr_fw_crash_state.attr,
3496	&dev_attr_page_size.attr,
3497	&dev_attr_ldio_outstanding.attr,
3498	&dev_attr_fw_cmds_outstanding.attr,
3499	&dev_attr_enable_sdev_max_qd.attr,
3500	&dev_attr_dump_system_regs.attr,
3501	&dev_attr_raid_map_id.attr,
3502	NULL,
3503};
3504
3505ATTRIBUTE_GROUPS(megaraid_host);
3506
3507/*
3508 * Scsi host template for megaraid_sas driver
3509 */
3510static const struct scsi_host_template megasas_template = {
3511
3512	.module = THIS_MODULE,
3513	.name = "Avago SAS based MegaRAID driver",
3514	.proc_name = "megaraid_sas",
3515	.sdev_configure = megasas_sdev_configure,
3516	.sdev_init = megasas_sdev_init,
3517	.sdev_destroy = megasas_sdev_destroy,
3518	.queuecommand = megasas_queue_command,
3519	.eh_target_reset_handler = megasas_reset_target,
3520	.eh_abort_handler = megasas_task_abort,
3521	.eh_host_reset_handler = megasas_reset_bus_host,
3522	.eh_timed_out = megasas_reset_timer,
3523	.shost_groups = megaraid_host_groups,
3524	.bios_param = megasas_bios_param,
3525	.map_queues = megasas_map_queues,
3526	.mq_poll = megasas_blk_mq_poll,
3527	.change_queue_depth = scsi_change_queue_depth,
3528	.max_segment_size = 0xffffffff,
3529	.cmd_size = sizeof(struct megasas_cmd_priv),
3530};
3531
3532/**
3533 * megasas_complete_int_cmd -	Completes an internal command
3534 * @instance:			Adapter soft state
3535 * @cmd:			Command to be completed
3536 *
3537 * The megasas_issue_blocked_cmd() function waits for a command to complete
3538 * after it issues a command. This function wakes up that waiting routine by
3539 * calling wake_up() on the wait queue.
3540 */
3541static void
3542megasas_complete_int_cmd(struct megasas_instance *instance,
3543			 struct megasas_cmd *cmd)
3544{
3545	if (cmd->cmd_status_drv == DCMD_INIT)
3546		cmd->cmd_status_drv =
3547		(cmd->frame->io.cmd_status == MFI_STAT_OK) ?
3548		DCMD_SUCCESS : DCMD_FAILED;
3549
3550	wake_up(&instance->int_cmd_wait_q);
3551}
3552
3553/**
3554 * megasas_complete_abort -	Completes aborting a command
3555 * @instance:			Adapter soft state
3556 * @cmd:			Cmd that was issued to abort another cmd
3557 *
3558 * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
3559 * after it issues an abort on a previously issued command. This function
3560 * wakes up all functions waiting on the same wait queue.
3561 */
3562static void
3563megasas_complete_abort(struct megasas_instance *instance,
3564		       struct megasas_cmd *cmd)
3565{
3566	if (cmd->sync_cmd) {
3567		cmd->sync_cmd = 0;
3568		cmd->cmd_status_drv = DCMD_SUCCESS;
3569		wake_up(&instance->abort_cmd_wait_q);
3570	}
3571}
3572
3573static void
3574megasas_set_ld_removed_by_fw(struct megasas_instance *instance)
3575{
3576	uint i;
3577
3578	for (i = 0; (i < MEGASAS_MAX_LD_IDS); i++) {
3579		if (instance->ld_ids_prev[i] != 0xff &&
3580		    instance->ld_ids_from_raidmap[i] == 0xff) {
3581			if (megasas_dbg_lvl & LD_PD_DEBUG)
3582				dev_info(&instance->pdev->dev,
3583					 "LD target ID %d removed from RAID map\n", i);
3584			instance->ld_tgtid_status[i] = LD_TARGET_ID_DELETED;
3585		}
3586	}
3587}
3588
3589/**
3590 * megasas_complete_cmd -	Completes a command
3591 * @instance:			Adapter soft state
3592 * @cmd:			Command to be completed
3593 * @alt_status:			If non-zero, use this value as status to
3594 *				SCSI mid-layer instead of the value returned
3595 *				by the FW. This should be used if caller wants
3596 *				an alternate status (as in the case of aborted
3597 *				commands)
3598 */
3599void
3600megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
3601		     u8 alt_status)
3602{
3603	int exception = 0;
3604	struct megasas_header *hdr = &cmd->frame->hdr;
3605	unsigned long flags;
3606	struct fusion_context *fusion = instance->ctrl_context;
3607	u32 opcode, status;
3608
3609	/* flag for the retry reset */
3610	cmd->retry_for_fw_reset = 0;
3611
3612	if (cmd->scmd)
3613		megasas_priv(cmd->scmd)->cmd_priv = NULL;
3614
3615	switch (hdr->cmd) {
3616	case MFI_CMD_INVALID:
3617		/* Some older 1068 controller FW may keep a pended
3618		   MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
3619		   when booting the kdump kernel.  Ignore this command to
3620		   prevent a kernel panic on shutdown of the kdump kernel. */
3621		dev_warn(&instance->pdev->dev, "MFI_CMD_INVALID command "
3622		       "completed\n");
3623		dev_warn(&instance->pdev->dev, "If you have a controller "
3624		       "other than PERC5, please upgrade your firmware\n");
3625		break;
3626	case MFI_CMD_PD_SCSI_IO:
3627	case MFI_CMD_LD_SCSI_IO:
3628
3629		/*
3630		 * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
3631		 * issued either through an IO path or an IOCTL path. If it
3632		 * was via IOCTL, we will send it to internal completion.
3633		 */
3634		if (cmd->sync_cmd) {
3635			cmd->sync_cmd = 0;
3636			megasas_complete_int_cmd(instance, cmd);
3637			break;
3638		}
3639		fallthrough;
3640
3641	case MFI_CMD_LD_READ:
3642	case MFI_CMD_LD_WRITE:
3643
3644		if (alt_status) {
3645			cmd->scmd->result = alt_status << 16;
3646			exception = 1;
3647		}
3648
3649		if (exception) {
3650
3651			atomic_dec(&instance->fw_outstanding);
3652
3653			scsi_dma_unmap(cmd->scmd);
3654			scsi_done(cmd->scmd);
3655			megasas_return_cmd(instance, cmd);
3656
3657			break;
3658		}
3659
3660		switch (hdr->cmd_status) {
3661
3662		case MFI_STAT_OK:
3663			cmd->scmd->result = DID_OK << 16;
3664			break;
3665
3666		case MFI_STAT_SCSI_IO_FAILED:
3667		case MFI_STAT_LD_INIT_IN_PROGRESS:
3668			if (hdr->scsi_status == 0xf0)
3669				cmd->scmd->result = (DID_ERROR << 16) | SAM_STAT_CHECK_CONDITION;
3670			else
3671				cmd->scmd->result = (DID_ERROR << 16) | hdr->scsi_status;
3672			break;
3673
3674		case MFI_STAT_SCSI_DONE_WITH_ERROR:
3675
3676			cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
3677
3678			if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
3679				memset(cmd->scmd->sense_buffer, 0,
3680				       SCSI_SENSE_BUFFERSIZE);
3681				memcpy(cmd->scmd->sense_buffer, cmd->sense,
3682				       hdr->sense_len);
3683			}
3684
3685			break;
3686
3687		case MFI_STAT_LD_OFFLINE:
3688		case MFI_STAT_DEVICE_NOT_FOUND:
3689			cmd->scmd->result = DID_BAD_TARGET << 16;
3690			break;
3691
3692		default:
3693			dev_printk(KERN_DEBUG, &instance->pdev->dev, "MFI FW status %#x\n",
3694			       hdr->cmd_status);
3695			cmd->scmd->result = DID_ERROR << 16;
3696			break;
3697		}
3698
3699		atomic_dec(&instance->fw_outstanding);
3700
3701		scsi_dma_unmap(cmd->scmd);
3702		scsi_done(cmd->scmd);
3703		megasas_return_cmd(instance, cmd);
3704
3705		break;
3706
3707	case MFI_CMD_SMP:
3708	case MFI_CMD_STP:
3709	case MFI_CMD_NVME:
3710	case MFI_CMD_TOOLBOX:
3711		megasas_complete_int_cmd(instance, cmd);
3712		break;
3713
3714	case MFI_CMD_DCMD:
3715		opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
3716		/* Check for LD map update */
3717		if ((opcode == MR_DCMD_LD_MAP_GET_INFO)
3718			&& (cmd->frame->dcmd.mbox.b[1] == 1)) {
3719			fusion->fast_path_io = 0;
3720			spin_lock_irqsave(instance->host->host_lock, flags);
3721			status = cmd->frame->hdr.cmd_status;
3722			instance->map_update_cmd = NULL;
3723			if (status != MFI_STAT_OK) {
3724				if (status != MFI_STAT_NOT_FOUND)
3725					dev_warn(&instance->pdev->dev, "map syncfailed, status = 0x%x\n",
3726					       cmd->frame->hdr.cmd_status);
3727				else {
3728					megasas_return_cmd(instance, cmd);
3729					spin_unlock_irqrestore(
3730						instance->host->host_lock,
3731						flags);
3732					break;
3733				}
3734			}
3735
3736			megasas_return_cmd(instance, cmd);
3737
3738			/*
3739			 * Set fast path IO to ZERO.
3740			 * Validate Map will set proper value.
3741			 * Meanwhile all IOs will go as LD IO.
3742			 */
3743			if (status == MFI_STAT_OK &&
3744			    (MR_ValidateMapInfo(instance, (instance->map_id + 1)))) {
3745				instance->map_id++;
3746				fusion->fast_path_io = 1;
3747			} else {
3748				fusion->fast_path_io = 0;
3749			}
3750
3751			if (instance->adapter_type >= INVADER_SERIES)
3752				megasas_set_ld_removed_by_fw(instance);
3753
3754			megasas_sync_map_info(instance);
3755			spin_unlock_irqrestore(instance->host->host_lock,
3756					       flags);
3757
3758			break;
3759		}
3760		if (opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
3761		    opcode == MR_DCMD_CTRL_EVENT_GET) {
3762			spin_lock_irqsave(&poll_aen_lock, flags);
3763			megasas_poll_wait_aen = 0;
3764			spin_unlock_irqrestore(&poll_aen_lock, flags);
3765		}
3766
3767		/* FW has an updated PD sequence */
3768		if ((opcode == MR_DCMD_SYSTEM_PD_MAP_GET_INFO) &&
3769			(cmd->frame->dcmd.mbox.b[0] == 1)) {
3770
3771			spin_lock_irqsave(instance->host->host_lock, flags);
3772			status = cmd->frame->hdr.cmd_status;
3773			instance->jbod_seq_cmd = NULL;
3774			megasas_return_cmd(instance, cmd);
3775
3776			if (status == MFI_STAT_OK) {
3777				instance->pd_seq_map_id++;
3778				/* Re-register a pd sync seq num cmd */
3779				if (megasas_sync_pd_seq_num(instance, true))
3780					instance->use_seqnum_jbod_fp = false;
3781			} else
3782				instance->use_seqnum_jbod_fp = false;
3783
3784			spin_unlock_irqrestore(instance->host->host_lock, flags);
3785			break;
3786		}
3787
3788		/*
3789		 * See if got an event notification
3790		 */
3791		if (opcode == MR_DCMD_CTRL_EVENT_WAIT)
3792			megasas_service_aen(instance, cmd);
3793		else
3794			megasas_complete_int_cmd(instance, cmd);
3795
3796		break;
3797
3798	case MFI_CMD_ABORT:
3799		/*
3800		 * Cmd issued to abort another cmd returned
3801		 */
3802		megasas_complete_abort(instance, cmd);
3803		break;
3804
3805	default:
3806		dev_info(&instance->pdev->dev, "Unknown command completed! [0x%X]\n",
3807		       hdr->cmd);
3808		megasas_complete_int_cmd(instance, cmd);
3809		break;
3810	}
3811}
3812
3813/**
3814 * megasas_issue_pending_cmds_again -	issue all pending cmds
3815 *					in FW again because of the fw reset
3816 * @instance:				Adapter soft state
3817 */
3818static inline void
3819megasas_issue_pending_cmds_again(struct megasas_instance *instance)
3820{
3821	struct megasas_cmd *cmd;
3822	struct list_head clist_local;
3823	union megasas_evt_class_locale class_locale;
3824	unsigned long flags;
3825	u32 seq_num;
3826
3827	INIT_LIST_HEAD(&clist_local);
3828	spin_lock_irqsave(&instance->hba_lock, flags);
3829	list_splice_init(&instance->internal_reset_pending_q, &clist_local);
3830	spin_unlock_irqrestore(&instance->hba_lock, flags);
3831
3832	while (!list_empty(&clist_local)) {
3833		cmd = list_entry((&clist_local)->next,
3834					struct megasas_cmd, list);
3835		list_del_init(&cmd->list);
3836
3837		if (cmd->sync_cmd || cmd->scmd) {
3838			dev_notice(&instance->pdev->dev, "command %p, %p:%d"
3839				"detected to be pending while HBA reset\n",
3840					cmd, cmd->scmd, cmd->sync_cmd);
3841
3842			cmd->retry_for_fw_reset++;
3843
3844			if (cmd->retry_for_fw_reset == 3) {
3845				dev_notice(&instance->pdev->dev, "cmd %p, %p:%d"
3846					"was tried multiple times during reset."
3847					"Shutting down the HBA\n",
3848					cmd, cmd->scmd, cmd->sync_cmd);
3849				instance->instancet->disable_intr(instance);
3850				atomic_set(&instance->fw_reset_no_pci_access, 1);
3851				megaraid_sas_kill_hba(instance);
3852				return;
3853			}
3854		}
3855
3856		if (cmd->sync_cmd == 1) {
3857			if (cmd->scmd) {
3858				dev_notice(&instance->pdev->dev, "unexpected"
3859					"cmd attached to internal command!\n");
3860			}
3861			dev_notice(&instance->pdev->dev, "%p synchronous cmd"
3862						"on the internal reset queue,"
3863						"issue it again.\n", cmd);
3864			cmd->cmd_status_drv = DCMD_INIT;
3865			instance->instancet->fire_cmd(instance,
3866							cmd->frame_phys_addr,
3867							0, instance->reg_set);
3868		} else if (cmd->scmd) {
3869			dev_notice(&instance->pdev->dev, "%p scsi cmd [%02x]"
3870			"detected on the internal queue, issue again.\n",
3871			cmd, cmd->scmd->cmnd[0]);
3872
3873			atomic_inc(&instance->fw_outstanding);
3874			instance->instancet->fire_cmd(instance,
3875					cmd->frame_phys_addr,
3876					cmd->frame_count-1, instance->reg_set);
3877		} else {
3878			dev_notice(&instance->pdev->dev, "%p unexpected cmd on the"
3879				"internal reset defer list while re-issue!!\n",
3880				cmd);
3881		}
3882	}
3883
3884	if (instance->aen_cmd) {
3885		dev_notice(&instance->pdev->dev, "aen_cmd in def process\n");
3886		megasas_return_cmd(instance, instance->aen_cmd);
3887
3888		instance->aen_cmd = NULL;
3889	}
3890
3891	/*
3892	 * Initiate AEN (Asynchronous Event Notification)
3893	 */
3894	seq_num = instance->last_seq_num;
3895	class_locale.members.reserved = 0;
3896	class_locale.members.locale = MR_EVT_LOCALE_ALL;
3897	class_locale.members.class = MR_EVT_CLASS_DEBUG;
3898
3899	megasas_register_aen(instance, seq_num, class_locale.word);
3900}
3901
3902/*
3903 * Move the internal reset pending commands to a deferred queue.
3904 *
3905 * We move the commands pending at internal reset time to a
3906 * pending queue. This queue would be flushed after successful
3907 * completion of the internal reset sequence. if the internal reset
3908 * did not complete in time, the kernel reset handler would flush
3909 * these commands.
3910 */
3911static void
3912megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
3913{
3914	struct megasas_cmd *cmd;
3915	int i;
3916	u16 max_cmd = instance->max_fw_cmds;
3917	u32 defer_index;
3918	unsigned long flags;
3919
3920	defer_index = 0;
3921	spin_lock_irqsave(&instance->mfi_pool_lock, flags);
3922	for (i = 0; i < max_cmd; i++) {
3923		cmd = instance->cmd_list[i];
3924		if (cmd->sync_cmd == 1 || cmd->scmd) {
3925			dev_notice(&instance->pdev->dev, "moving cmd[%d]:%p:%d:%p"
3926					"on the defer queue as internal\n",
3927				defer_index, cmd, cmd->sync_cmd, cmd->scmd);
3928
3929			if (!list_empty(&cmd->list)) {
3930				dev_notice(&instance->pdev->dev, "ERROR while"
3931					" moving this cmd:%p, %d %p, it was"
3932					"discovered on some list?\n",
3933					cmd, cmd->sync_cmd, cmd->scmd);
3934
3935				list_del_init(&cmd->list);
3936			}
3937			defer_index++;
3938			list_add_tail(&cmd->list,
3939				&instance->internal_reset_pending_q);
3940		}
3941	}
3942	spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
3943}
3944
3945
3946static void
3947process_fw_state_change_wq(struct work_struct *work)
3948{
3949	struct megasas_instance *instance =
3950		container_of(work, struct megasas_instance, work_init);
3951	u32 wait;
3952	unsigned long flags;
3953
3954	if (atomic_read(&instance->adprecovery) != MEGASAS_ADPRESET_SM_INFAULT) {
3955		dev_notice(&instance->pdev->dev, "error, recovery st %x\n",
3956			   atomic_read(&instance->adprecovery));
3957		return ;
3958	}
3959
3960	if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) {
3961		dev_notice(&instance->pdev->dev, "FW detected to be in fault"
3962					"state, restarting it...\n");
3963
3964		instance->instancet->disable_intr(instance);
3965		atomic_set(&instance->fw_outstanding, 0);
3966
3967		atomic_set(&instance->fw_reset_no_pci_access, 1);
3968		instance->instancet->adp_reset(instance, instance->reg_set);
3969		atomic_set(&instance->fw_reset_no_pci_access, 0);
3970
3971		dev_notice(&instance->pdev->dev, "FW restarted successfully,"
3972					"initiating next stage...\n");
3973
3974		dev_notice(&instance->pdev->dev, "HBA recovery state machine,"
3975					"state 2 starting...\n");
3976
3977		/* waiting for about 20 second before start the second init */
3978		for (wait = 0; wait < 30; wait++) {
3979			msleep(1000);
3980		}
3981
3982		if (megasas_transition_to_ready(instance, 1)) {
3983			dev_notice(&instance->pdev->dev, "adapter not ready\n");
3984
3985			atomic_set(&instance->fw_reset_no_pci_access, 1);
3986			megaraid_sas_kill_hba(instance);
3987			return ;
3988		}
3989
3990		if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
3991			(instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
3992			(instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
3993			) {
3994			*instance->consumer = *instance->producer;
3995		} else {
3996			*instance->consumer = 0;
3997			*instance->producer = 0;
3998		}
3999
4000		megasas_issue_init_mfi(instance);
4001
4002		spin_lock_irqsave(&instance->hba_lock, flags);
4003		atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
4004		spin_unlock_irqrestore(&instance->hba_lock, flags);
4005		instance->instancet->enable_intr(instance);
4006
4007		megasas_issue_pending_cmds_again(instance);
4008		instance->issuepend_done = 1;
4009	}
4010}
4011
4012/**
4013 * megasas_deplete_reply_queue -	Processes all completed commands
4014 * @instance:				Adapter soft state
4015 * @alt_status:				Alternate status to be returned to
4016 *					SCSI mid-layer instead of the status
4017 *					returned by the FW
4018 * Note: this must be called with hba lock held
4019 */
4020static int
4021megasas_deplete_reply_queue(struct megasas_instance *instance,
4022					u8 alt_status)
4023{
4024	u32 mfiStatus;
4025	u32 fw_state;
4026
4027	if (instance->instancet->check_reset(instance, instance->reg_set) == 1)
4028		return IRQ_HANDLED;
4029
4030	mfiStatus = instance->instancet->clear_intr(instance);
4031	if (mfiStatus == 0) {
4032		/* Hardware may not set outbound_intr_status in MSI-X mode */
4033		if (!instance->msix_vectors)
4034			return IRQ_NONE;
4035	}
4036
4037	instance->mfiStatus = mfiStatus;
4038
4039	if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
4040		fw_state = instance->instancet->read_fw_status_reg(
4041				instance) & MFI_STATE_MASK;
4042
4043		if (fw_state != MFI_STATE_FAULT) {
4044			dev_notice(&instance->pdev->dev, "fw state:%x\n",
4045						fw_state);
4046		}
4047
4048		if ((fw_state == MFI_STATE_FAULT) &&
4049				(instance->disableOnlineCtrlReset == 0)) {
4050			dev_notice(&instance->pdev->dev, "wait adp restart\n");
4051
4052			if ((instance->pdev->device ==
4053					PCI_DEVICE_ID_LSI_SAS1064R) ||
4054				(instance->pdev->device ==
4055					PCI_DEVICE_ID_DELL_PERC5) ||
4056				(instance->pdev->device ==
4057					PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
4058
4059				*instance->consumer =
4060					cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
4061			}
4062
4063
4064			instance->instancet->disable_intr(instance);
4065			atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
4066			instance->issuepend_done = 0;
4067
4068			atomic_set(&instance->fw_outstanding, 0);
4069			megasas_internal_reset_defer_cmds(instance);
4070
4071			dev_notice(&instance->pdev->dev, "fwState=%x, stage:%d\n",
4072					fw_state, atomic_read(&instance->adprecovery));
4073
4074			schedule_work(&instance->work_init);
4075			return IRQ_HANDLED;
4076
4077		} else {
4078			dev_notice(&instance->pdev->dev, "fwstate:%x, dis_OCR=%x\n",
4079				fw_state, instance->disableOnlineCtrlReset);
4080		}
4081	}
4082
4083	tasklet_schedule(&instance->isr_tasklet);
4084	return IRQ_HANDLED;
4085}
4086
4087/**
4088 * megasas_isr - isr entry point
4089 * @irq:	IRQ number
4090 * @devp:	IRQ context address
4091 */
4092static irqreturn_t megasas_isr(int irq, void *devp)
4093{
4094	struct megasas_irq_context *irq_context = devp;
4095	struct megasas_instance *instance = irq_context->instance;
4096	unsigned long flags;
4097	irqreturn_t rc;
4098
4099	if (atomic_read(&instance->fw_reset_no_pci_access))
4100		return IRQ_HANDLED;
4101
4102	spin_lock_irqsave(&instance->hba_lock, flags);
4103	rc = megasas_deplete_reply_queue(instance, DID_OK);
4104	spin_unlock_irqrestore(&instance->hba_lock, flags);
4105
4106	return rc;
4107}
4108
4109/**
4110 * megasas_transition_to_ready -	Move the FW to READY state
4111 * @instance:				Adapter soft state
4112 * @ocr:				Adapter reset state
4113 *
4114 * During the initialization, FW passes can potentially be in any one of
4115 * several possible states. If the FW in operational, waiting-for-handshake
4116 * states, driver must take steps to bring it to ready state. Otherwise, it
4117 * has to wait for the ready state.
4118 */
4119int
4120megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
4121{
4122	int i;
4123	u8 max_wait;
4124	u32 fw_state;
4125	u32 abs_state, curr_abs_state;
4126
4127	abs_state = instance->instancet->read_fw_status_reg(instance);
4128	fw_state = abs_state & MFI_STATE_MASK;
4129
4130	if (fw_state != MFI_STATE_READY)
4131		dev_info(&instance->pdev->dev, "Waiting for FW to come to ready"
4132		       " state\n");
4133
4134	while (fw_state != MFI_STATE_READY) {
4135
4136		switch (fw_state) {
4137
4138		case MFI_STATE_FAULT:
4139			dev_printk(KERN_ERR, &instance->pdev->dev,
4140				   "FW in FAULT state, Fault code:0x%x subcode:0x%x func:%s\n",
4141				   abs_state & MFI_STATE_FAULT_CODE,
4142				   abs_state & MFI_STATE_FAULT_SUBCODE, __func__);
4143			if (ocr) {
4144				max_wait = MEGASAS_RESET_WAIT_TIME;
4145				break;
4146			} else {
4147				dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4148				megasas_dump_reg_set(instance->reg_set);
4149				return -ENODEV;
4150			}
4151
4152		case MFI_STATE_WAIT_HANDSHAKE:
4153			/*
4154			 * Set the CLR bit in inbound doorbell
4155			 */
4156			if ((instance->pdev->device ==
4157				PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4158				(instance->pdev->device ==
4159				 PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
4160				(instance->adapter_type != MFI_SERIES))
4161				writel(
4162				  MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
4163				  &instance->reg_set->doorbell);
4164			else
4165				writel(
4166				    MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
4167					&instance->reg_set->inbound_doorbell);
4168
4169			max_wait = MEGASAS_RESET_WAIT_TIME;
4170			break;
4171
4172		case MFI_STATE_BOOT_MESSAGE_PENDING:
4173			if ((instance->pdev->device ==
4174			     PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4175				(instance->pdev->device ==
4176				 PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
4177				(instance->adapter_type != MFI_SERIES))
4178				writel(MFI_INIT_HOTPLUG,
4179				       &instance->reg_set->doorbell);
4180			else
4181				writel(MFI_INIT_HOTPLUG,
4182					&instance->reg_set->inbound_doorbell);
4183
4184			max_wait = MEGASAS_RESET_WAIT_TIME;
4185			break;
4186
4187		case MFI_STATE_OPERATIONAL:
4188			/*
4189			 * Bring it to READY state; assuming max wait 10 secs
4190			 */
4191			instance->instancet->disable_intr(instance);
4192			if ((instance->pdev->device ==
4193				PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4194				(instance->pdev->device ==
4195				PCI_DEVICE_ID_LSI_SAS0071SKINNY)  ||
4196				(instance->adapter_type != MFI_SERIES)) {
4197				writel(MFI_RESET_FLAGS,
4198					&instance->reg_set->doorbell);
4199
4200				if (instance->adapter_type != MFI_SERIES) {
4201					for (i = 0; i < (10 * 1000); i += 20) {
4202						if (megasas_readl(
4203							    instance,
4204							    &instance->
4205							    reg_set->
4206							    doorbell) & 1)
4207							msleep(20);
4208						else
4209							break;
4210					}
4211				}
4212			} else
4213				writel(MFI_RESET_FLAGS,
4214					&instance->reg_set->inbound_doorbell);
4215
4216			max_wait = MEGASAS_RESET_WAIT_TIME;
4217			break;
4218
4219		case MFI_STATE_UNDEFINED:
4220			/*
4221			 * This state should not last for more than 2 seconds
4222			 */
4223			max_wait = MEGASAS_RESET_WAIT_TIME;
4224			break;
4225
4226		case MFI_STATE_BB_INIT:
4227			max_wait = MEGASAS_RESET_WAIT_TIME;
4228			break;
4229
4230		case MFI_STATE_FW_INIT:
4231			max_wait = MEGASAS_RESET_WAIT_TIME;
4232			break;
4233
4234		case MFI_STATE_FW_INIT_2:
4235			max_wait = MEGASAS_RESET_WAIT_TIME;
4236			break;
4237
4238		case MFI_STATE_DEVICE_SCAN:
4239			max_wait = MEGASAS_RESET_WAIT_TIME;
4240			break;
4241
4242		case MFI_STATE_FLUSH_CACHE:
4243			max_wait = MEGASAS_RESET_WAIT_TIME;
4244			break;
4245
4246		default:
4247			dev_printk(KERN_DEBUG, &instance->pdev->dev, "Unknown state 0x%x\n",
4248			       fw_state);
4249			dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4250			megasas_dump_reg_set(instance->reg_set);
4251			return -ENODEV;
4252		}
4253
4254		/*
4255		 * The cur_state should not last for more than max_wait secs
4256		 */
4257		for (i = 0; i < max_wait * 50; i++) {
4258			curr_abs_state = instance->instancet->
4259				read_fw_status_reg(instance);
4260
4261			if (abs_state == curr_abs_state) {
4262				msleep(20);
4263			} else
4264				break;
4265		}
4266
4267		/*
4268		 * Return error if fw_state hasn't changed after max_wait
4269		 */
4270		if (curr_abs_state == abs_state) {
4271			dev_printk(KERN_DEBUG, &instance->pdev->dev, "FW state [%d] hasn't changed "
4272			       "in %d secs\n", fw_state, max_wait);
4273			dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4274			megasas_dump_reg_set(instance->reg_set);
4275			return -ENODEV;
4276		}
4277
4278		abs_state = curr_abs_state;
4279		fw_state = curr_abs_state & MFI_STATE_MASK;
4280	}
4281	dev_info(&instance->pdev->dev, "FW now in Ready state\n");
4282
4283	return 0;
4284}
4285
4286/**
4287 * megasas_teardown_frame_pool -	Destroy the cmd frame DMA pool
4288 * @instance:				Adapter soft state
4289 */
4290static void megasas_teardown_frame_pool(struct megasas_instance *instance)
4291{
4292	int i;
4293	u16 max_cmd = instance->max_mfi_cmds;
4294	struct megasas_cmd *cmd;
4295
4296	if (!instance->frame_dma_pool)
4297		return;
4298
4299	/*
4300	 * Return all frames to pool
4301	 */
4302	for (i = 0; i < max_cmd; i++) {
4303
4304		cmd = instance->cmd_list[i];
4305
4306		if (cmd->frame)
4307			dma_pool_free(instance->frame_dma_pool, cmd->frame,
4308				      cmd->frame_phys_addr);
4309
4310		if (cmd->sense)
4311			dma_pool_free(instance->sense_dma_pool, cmd->sense,
4312				      cmd->sense_phys_addr);
4313	}
4314
4315	/*
4316	 * Now destroy the pool itself
4317	 */
4318	dma_pool_destroy(instance->frame_dma_pool);
4319	dma_pool_destroy(instance->sense_dma_pool);
4320
4321	instance->frame_dma_pool = NULL;
4322	instance->sense_dma_pool = NULL;
4323}
4324
4325/**
4326 * megasas_create_frame_pool -	Creates DMA pool for cmd frames
4327 * @instance:			Adapter soft state
4328 *
4329 * Each command packet has an embedded DMA memory buffer that is used for
4330 * filling MFI frame and the SG list that immediately follows the frame. This
4331 * function creates those DMA memory buffers for each command packet by using
4332 * PCI pool facility.
4333 */
4334static int megasas_create_frame_pool(struct megasas_instance *instance)
4335{
4336	int i;
4337	u16 max_cmd;
4338	u32 frame_count;
4339	struct megasas_cmd *cmd;
4340
4341	max_cmd = instance->max_mfi_cmds;
4342
4343	/*
4344	 * For MFI controllers.
4345	 * max_num_sge = 60
4346	 * max_sge_sz  = 16 byte (sizeof megasas_sge_skinny)
4347	 * Total 960 byte (15 MFI frame of 64 byte)
4348	 *
4349	 * Fusion adapter require only 3 extra frame.
4350	 * max_num_sge = 16 (defined as MAX_IOCTL_SGE)
4351	 * max_sge_sz  = 12 byte (sizeof  megasas_sge64)
4352	 * Total 192 byte (3 MFI frame of 64 byte)
4353	 */
4354	frame_count = (instance->adapter_type == MFI_SERIES) ?
4355			(15 + 1) : (3 + 1);
4356	instance->mfi_frame_size = MEGAMFI_FRAME_SIZE * frame_count;
4357	/*
4358	 * Use DMA pool facility provided by PCI layer
4359	 */
4360	instance->frame_dma_pool = dma_pool_create("megasas frame pool",
4361					&instance->pdev->dev,
4362					instance->mfi_frame_size, 256, 0);
4363
4364	if (!instance->frame_dma_pool) {
4365		dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup frame pool\n");
4366		return -ENOMEM;
4367	}
4368
4369	instance->sense_dma_pool = dma_pool_create("megasas sense pool",
4370						   &instance->pdev->dev, 128,
4371						   4, 0);
4372
4373	if (!instance->sense_dma_pool) {
4374		dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup sense pool\n");
4375
4376		dma_pool_destroy(instance->frame_dma_pool);
4377		instance->frame_dma_pool = NULL;
4378
4379		return -ENOMEM;
4380	}
4381
4382	/*
4383	 * Allocate and attach a frame to each of the commands in cmd_list.
4384	 * By making cmd->index as the context instead of the &cmd, we can
4385	 * always use 32bit context regardless of the architecture
4386	 */
4387	for (i = 0; i < max_cmd; i++) {
4388
4389		cmd = instance->cmd_list[i];
4390
4391		cmd->frame = dma_pool_zalloc(instance->frame_dma_pool,
4392					    GFP_KERNEL, &cmd->frame_phys_addr);
4393
4394		cmd->sense = dma_pool_alloc(instance->sense_dma_pool,
4395					    GFP_KERNEL, &cmd->sense_phys_addr);
4396
4397		/*
4398		 * megasas_teardown_frame_pool() takes care of freeing
4399		 * whatever has been allocated
4400		 */
4401		if (!cmd->frame || !cmd->sense) {
4402			dev_printk(KERN_DEBUG, &instance->pdev->dev, "dma_pool_alloc failed\n");
4403			megasas_teardown_frame_pool(instance);
4404			return -ENOMEM;
4405		}
4406
4407		cmd->frame->io.context = cpu_to_le32(cmd->index);
4408		cmd->frame->io.pad_0 = 0;
4409		if ((instance->adapter_type == MFI_SERIES) && reset_devices)
4410			cmd->frame->hdr.cmd = MFI_CMD_INVALID;
4411	}
4412
4413	return 0;
4414}
4415
4416/**
4417 * megasas_free_cmds -	Free all the cmds in the free cmd pool
4418 * @instance:		Adapter soft state
4419 */
4420void megasas_free_cmds(struct megasas_instance *instance)
4421{
4422	int i;
4423
4424	/* First free the MFI frame pool */
4425	megasas_teardown_frame_pool(instance);
4426
4427	/* Free all the commands in the cmd_list */
4428	for (i = 0; i < instance->max_mfi_cmds; i++)
4429
4430		kfree(instance->cmd_list[i]);
4431
4432	/* Free the cmd_list buffer itself */
4433	kfree(instance->cmd_list);
4434	instance->cmd_list = NULL;
4435
4436	INIT_LIST_HEAD(&instance->cmd_pool);
4437}
4438
4439/**
4440 * megasas_alloc_cmds -	Allocates the command packets
4441 * @instance:		Adapter soft state
4442 *
4443 * Each command that is issued to the FW, whether IO commands from the OS or
4444 * internal commands like IOCTLs, are wrapped in local data structure called
4445 * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
4446 * the FW.
4447 *
4448 * Each frame has a 32-bit field called context (tag). This context is used
4449 * to get back the megasas_cmd from the frame when a frame gets completed in
4450 * the ISR. Typically the address of the megasas_cmd itself would be used as
4451 * the context. But we wanted to keep the differences between 32 and 64 bit
4452 * systems to the mininum. We always use 32 bit integers for the context. In
4453 * this driver, the 32 bit values are the indices into an array cmd_list.
4454 * This array is used only to look up the megasas_cmd given the context. The
4455 * free commands themselves are maintained in a linked list called cmd_pool.
4456 */
4457int megasas_alloc_cmds(struct megasas_instance *instance)
4458{
4459	int i;
4460	int j;
4461	u16 max_cmd;
4462	struct megasas_cmd *cmd;
4463
4464	max_cmd = instance->max_mfi_cmds;
4465
4466	/*
4467	 * instance->cmd_list is an array of struct megasas_cmd pointers.
4468	 * Allocate the dynamic array first and then allocate individual
4469	 * commands.
4470	 */
4471	instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
4472
4473	if (!instance->cmd_list) {
4474		dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
4475		return -ENOMEM;
4476	}
4477
4478	for (i = 0; i < max_cmd; i++) {
4479		instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
4480						GFP_KERNEL);
4481
4482		if (!instance->cmd_list[i]) {
4483
4484			for (j = 0; j < i; j++)
4485				kfree(instance->cmd_list[j]);
4486
4487			kfree(instance->cmd_list);
4488			instance->cmd_list = NULL;
4489
4490			return -ENOMEM;
4491		}
4492	}
4493
4494	for (i = 0; i < max_cmd; i++) {
4495		cmd = instance->cmd_list[i];
4496		memset(cmd, 0, sizeof(struct megasas_cmd));
4497		cmd->index = i;
4498		cmd->scmd = NULL;
4499		cmd->instance = instance;
4500
4501		list_add_tail(&cmd->list, &instance->cmd_pool);
4502	}
4503
4504	/*
4505	 * Create a frame pool and assign one frame to each cmd
4506	 */
4507	if (megasas_create_frame_pool(instance)) {
4508		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
4509		megasas_free_cmds(instance);
4510		return -ENOMEM;
4511	}
4512
4513	return 0;
4514}
4515
4516/*
4517 * dcmd_timeout_ocr_possible -	Check if OCR is possible based on Driver/FW state.
4518 * @instance:				Adapter soft state
4519 *
4520 * Return 0 for only Fusion adapter, if driver load/unload is not in progress
4521 * or FW is not under OCR.
4522 */
4523inline int
4524dcmd_timeout_ocr_possible(struct megasas_instance *instance) {
4525
4526	if (instance->adapter_type == MFI_SERIES)
4527		return KILL_ADAPTER;
4528	else if (instance->unload ||
4529			test_bit(MEGASAS_FUSION_OCR_NOT_POSSIBLE,
4530				 &instance->reset_flags))
4531		return IGNORE_TIMEOUT;
4532	else
4533		return INITIATE_OCR;
4534}
4535
4536static void
4537megasas_get_pd_info(struct megasas_instance *instance, struct scsi_device *sdev)
4538{
4539	int ret;
4540	struct megasas_cmd *cmd;
4541	struct megasas_dcmd_frame *dcmd;
4542
4543	struct MR_PRIV_DEVICE *mr_device_priv_data;
4544	u16 device_id = 0;
4545
4546	device_id = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id;
4547	cmd = megasas_get_cmd(instance);
4548
4549	if (!cmd) {
4550		dev_err(&instance->pdev->dev, "Failed to get cmd %s\n", __func__);
4551		return;
4552	}
4553
4554	dcmd = &cmd->frame->dcmd;
4555
4556	memset(instance->pd_info, 0, sizeof(*instance->pd_info));
4557	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4558
4559	dcmd->mbox.s[0] = cpu_to_le16(device_id);
4560	dcmd->cmd = MFI_CMD_DCMD;
4561	dcmd->cmd_status = 0xFF;
4562	dcmd->sge_count = 1;
4563	dcmd->flags = MFI_FRAME_DIR_READ;
4564	dcmd->timeout = 0;
4565	dcmd->pad_0 = 0;
4566	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_PD_INFO));
4567	dcmd->opcode = cpu_to_le32(MR_DCMD_PD_GET_INFO);
4568
4569	megasas_set_dma_settings(instance, dcmd, instance->pd_info_h,
4570				 sizeof(struct MR_PD_INFO));
4571
4572	if ((instance->adapter_type != MFI_SERIES) &&
4573	    !instance->mask_interrupts)
4574		ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4575	else
4576		ret = megasas_issue_polled(instance, cmd);
4577
4578	switch (ret) {
4579	case DCMD_SUCCESS:
4580		mr_device_priv_data = sdev->hostdata;
4581		le16_to_cpus((u16 *)&instance->pd_info->state.ddf.pdType);
4582		mr_device_priv_data->interface_type =
4583				instance->pd_info->state.ddf.pdType.intf;
4584		break;
4585
4586	case DCMD_TIMEOUT:
4587
4588		switch (dcmd_timeout_ocr_possible(instance)) {
4589		case INITIATE_OCR:
4590			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4591			mutex_unlock(&instance->reset_mutex);
4592			megasas_reset_fusion(instance->host,
4593				MFI_IO_TIMEOUT_OCR);
4594			mutex_lock(&instance->reset_mutex);
4595			break;
4596		case KILL_ADAPTER:
4597			megaraid_sas_kill_hba(instance);
4598			break;
4599		case IGNORE_TIMEOUT:
4600			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4601				__func__, __LINE__);
4602			break;
4603		}
4604
4605		break;
4606	}
4607
4608	if (ret != DCMD_TIMEOUT)
4609		megasas_return_cmd(instance, cmd);
4610
4611	return;
4612}
4613/*
4614 * megasas_get_pd_list_info -	Returns FW's pd_list structure
4615 * @instance:				Adapter soft state
4616 * @pd_list:				pd_list structure
4617 *
4618 * Issues an internal command (DCMD) to get the FW's controller PD
4619 * list structure.  This information is mainly used to find out SYSTEM
4620 * supported by the FW.
4621 */
4622static int
4623megasas_get_pd_list(struct megasas_instance *instance)
4624{
4625	int ret = 0, pd_index = 0;
4626	struct megasas_cmd *cmd;
4627	struct megasas_dcmd_frame *dcmd;
4628	struct MR_PD_LIST *ci;
4629	struct MR_PD_ADDRESS *pd_addr;
4630
4631	if (instance->pd_list_not_supported) {
4632		dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4633		"not supported by firmware\n");
4634		return ret;
4635	}
4636
4637	ci = instance->pd_list_buf;
4638
4639	cmd = megasas_get_cmd(instance);
4640
4641	if (!cmd) {
4642		dev_printk(KERN_DEBUG, &instance->pdev->dev, "(get_pd_list): Failed to get cmd\n");
4643		return -ENOMEM;
4644	}
4645
4646	dcmd = &cmd->frame->dcmd;
4647
4648	memset(ci, 0, sizeof(*ci));
4649	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4650
4651	dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
4652	dcmd->mbox.b[1] = 0;
4653	dcmd->cmd = MFI_CMD_DCMD;
4654	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4655	dcmd->sge_count = 1;
4656	dcmd->flags = MFI_FRAME_DIR_READ;
4657	dcmd->timeout = 0;
4658	dcmd->pad_0 = 0;
4659	dcmd->data_xfer_len = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
4660	dcmd->opcode = cpu_to_le32(MR_DCMD_PD_LIST_QUERY);
4661
4662	megasas_set_dma_settings(instance, dcmd, instance->pd_list_buf_h,
4663				 (MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST)));
4664
4665	if ((instance->adapter_type != MFI_SERIES) &&
4666	    !instance->mask_interrupts)
4667		ret = megasas_issue_blocked_cmd(instance, cmd,
4668			MFI_IO_TIMEOUT_SECS);
4669	else
4670		ret = megasas_issue_polled(instance, cmd);
4671
4672	switch (ret) {
4673	case DCMD_FAILED:
4674		dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4675			"failed/not supported by firmware\n");
4676
4677		if (instance->adapter_type != MFI_SERIES)
4678			megaraid_sas_kill_hba(instance);
4679		else
4680			instance->pd_list_not_supported = 1;
4681		break;
4682	case DCMD_TIMEOUT:
4683
4684		switch (dcmd_timeout_ocr_possible(instance)) {
4685		case INITIATE_OCR:
4686			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4687			/*
4688			 * DCMD failed from AEN path.
4689			 * AEN path already hold reset_mutex to avoid PCI access
4690			 * while OCR is in progress.
4691			 */
4692			mutex_unlock(&instance->reset_mutex);
4693			megasas_reset_fusion(instance->host,
4694						MFI_IO_TIMEOUT_OCR);
4695			mutex_lock(&instance->reset_mutex);
4696			break;
4697		case KILL_ADAPTER:
4698			megaraid_sas_kill_hba(instance);
4699			break;
4700		case IGNORE_TIMEOUT:
4701			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d \n",
4702				__func__, __LINE__);
4703			break;
4704		}
4705
4706		break;
4707
4708	case DCMD_SUCCESS:
4709		pd_addr = ci->addr;
4710		if (megasas_dbg_lvl & LD_PD_DEBUG)
4711			dev_info(&instance->pdev->dev, "%s, sysPD count: 0x%x\n",
4712				 __func__, le32_to_cpu(ci->count));
4713
4714		if ((le32_to_cpu(ci->count) >
4715			(MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL)))
4716			break;
4717
4718		memset(instance->local_pd_list, 0,
4719				MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
4720
4721		for (pd_index = 0; pd_index < le32_to_cpu(ci->count); pd_index++) {
4722			instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].tid	=
4723					le16_to_cpu(pd_addr->deviceId);
4724			instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveType	=
4725					pd_addr->scsiDevType;
4726			instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveState	=
4727					MR_PD_STATE_SYSTEM;
4728			if (megasas_dbg_lvl & LD_PD_DEBUG)
4729				dev_info(&instance->pdev->dev,
4730					 "PD%d: targetID: 0x%03x deviceType:0x%x\n",
4731					 pd_index, le16_to_cpu(pd_addr->deviceId),
4732					 pd_addr->scsiDevType);
4733			pd_addr++;
4734		}
4735
4736		memcpy(instance->pd_list, instance->local_pd_list,
4737			sizeof(instance->pd_list));
4738		break;
4739
4740	}
4741
4742	if (ret != DCMD_TIMEOUT)
4743		megasas_return_cmd(instance, cmd);
4744
4745	return ret;
4746}
4747
4748/*
4749 * megasas_get_ld_list_info -	Returns FW's ld_list structure
4750 * @instance:				Adapter soft state
4751 * @ld_list:				ld_list structure
4752 *
4753 * Issues an internal command (DCMD) to get the FW's controller PD
4754 * list structure.  This information is mainly used to find out SYSTEM
4755 * supported by the FW.
4756 */
4757static int
4758megasas_get_ld_list(struct megasas_instance *instance)
4759{
4760	int ret = 0, ld_index = 0, ids = 0;
4761	struct megasas_cmd *cmd;
4762	struct megasas_dcmd_frame *dcmd;
4763	struct MR_LD_LIST *ci;
4764	dma_addr_t ci_h = 0;
4765	u32 ld_count;
4766
4767	ci = instance->ld_list_buf;
4768	ci_h = instance->ld_list_buf_h;
4769
4770	cmd = megasas_get_cmd(instance);
4771
4772	if (!cmd) {
4773		dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_list: Failed to get cmd\n");
4774		return -ENOMEM;
4775	}
4776
4777	dcmd = &cmd->frame->dcmd;
4778
4779	memset(ci, 0, sizeof(*ci));
4780	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4781
4782	if (instance->supportmax256vd)
4783		dcmd->mbox.b[0] = 1;
4784	dcmd->cmd = MFI_CMD_DCMD;
4785	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4786	dcmd->sge_count = 1;
4787	dcmd->flags = MFI_FRAME_DIR_READ;
4788	dcmd->timeout = 0;
4789	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_LIST));
4790	dcmd->opcode = cpu_to_le32(MR_DCMD_LD_GET_LIST);
4791	dcmd->pad_0  = 0;
4792
4793	megasas_set_dma_settings(instance, dcmd, ci_h,
4794				 sizeof(struct MR_LD_LIST));
4795
4796	if ((instance->adapter_type != MFI_SERIES) &&
4797	    !instance->mask_interrupts)
4798		ret = megasas_issue_blocked_cmd(instance, cmd,
4799			MFI_IO_TIMEOUT_SECS);
4800	else
4801		ret = megasas_issue_polled(instance, cmd);
4802
4803	ld_count = le32_to_cpu(ci->ldCount);
4804
4805	switch (ret) {
4806	case DCMD_FAILED:
4807		megaraid_sas_kill_hba(instance);
4808		break;
4809	case DCMD_TIMEOUT:
4810
4811		switch (dcmd_timeout_ocr_possible(instance)) {
4812		case INITIATE_OCR:
4813			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4814			/*
4815			 * DCMD failed from AEN path.
4816			 * AEN path already hold reset_mutex to avoid PCI access
4817			 * while OCR is in progress.
4818			 */
4819			mutex_unlock(&instance->reset_mutex);
4820			megasas_reset_fusion(instance->host,
4821						MFI_IO_TIMEOUT_OCR);
4822			mutex_lock(&instance->reset_mutex);
4823			break;
4824		case KILL_ADAPTER:
4825			megaraid_sas_kill_hba(instance);
4826			break;
4827		case IGNORE_TIMEOUT:
4828			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4829				__func__, __LINE__);
4830			break;
4831		}
4832
4833		break;
4834
4835	case DCMD_SUCCESS:
4836		if (megasas_dbg_lvl & LD_PD_DEBUG)
4837			dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4838				 __func__, ld_count);
4839
4840		if (ld_count > instance->fw_supported_vd_count)
4841			break;
4842
4843		memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
4844
4845		for (ld_index = 0; ld_index < ld_count; ld_index++) {
4846			if (ci->ldList[ld_index].state != 0) {
4847				ids = ci->ldList[ld_index].ref.targetId;
4848				instance->ld_ids[ids] = ci->ldList[ld_index].ref.targetId;
4849				if (megasas_dbg_lvl & LD_PD_DEBUG)
4850					dev_info(&instance->pdev->dev,
4851						 "LD%d: targetID: 0x%03x\n",
4852						 ld_index, ids);
4853			}
4854		}
4855
4856		break;
4857	}
4858
4859	if (ret != DCMD_TIMEOUT)
4860		megasas_return_cmd(instance, cmd);
4861
4862	return ret;
4863}
4864
4865/**
4866 * megasas_ld_list_query -	Returns FW's ld_list structure
4867 * @instance:				Adapter soft state
4868 * @query_type:				ld_list structure type
4869 *
4870 * Issues an internal command (DCMD) to get the FW's controller PD
4871 * list structure.  This information is mainly used to find out SYSTEM
4872 * supported by the FW.
4873 */
4874static int
4875megasas_ld_list_query(struct megasas_instance *instance, u8 query_type)
4876{
4877	int ret = 0, ld_index = 0, ids = 0;
4878	struct megasas_cmd *cmd;
4879	struct megasas_dcmd_frame *dcmd;
4880	struct MR_LD_TARGETID_LIST *ci;
4881	dma_addr_t ci_h = 0;
4882	u32 tgtid_count;
4883
4884	ci = instance->ld_targetid_list_buf;
4885	ci_h = instance->ld_targetid_list_buf_h;
4886
4887	cmd = megasas_get_cmd(instance);
4888
4889	if (!cmd) {
4890		dev_warn(&instance->pdev->dev,
4891		         "megasas_ld_list_query: Failed to get cmd\n");
4892		return -ENOMEM;
4893	}
4894
4895	dcmd = &cmd->frame->dcmd;
4896
4897	memset(ci, 0, sizeof(*ci));
4898	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4899
4900	dcmd->mbox.b[0] = query_type;
4901	if (instance->supportmax256vd)
4902		dcmd->mbox.b[2] = 1;
4903
4904	dcmd->cmd = MFI_CMD_DCMD;
4905	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4906	dcmd->sge_count = 1;
4907	dcmd->flags = MFI_FRAME_DIR_READ;
4908	dcmd->timeout = 0;
4909	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
4910	dcmd->opcode = cpu_to_le32(MR_DCMD_LD_LIST_QUERY);
4911	dcmd->pad_0  = 0;
4912
4913	megasas_set_dma_settings(instance, dcmd, ci_h,
4914				 sizeof(struct MR_LD_TARGETID_LIST));
4915
4916	if ((instance->adapter_type != MFI_SERIES) &&
4917	    !instance->mask_interrupts)
4918		ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4919	else
4920		ret = megasas_issue_polled(instance, cmd);
4921
4922	switch (ret) {
4923	case DCMD_FAILED:
4924		dev_info(&instance->pdev->dev,
4925			"DCMD not supported by firmware - %s %d\n",
4926				__func__, __LINE__);
4927		ret = megasas_get_ld_list(instance);
4928		break;
4929	case DCMD_TIMEOUT:
4930		switch (dcmd_timeout_ocr_possible(instance)) {
4931		case INITIATE_OCR:
4932			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4933			/*
4934			 * DCMD failed from AEN path.
4935			 * AEN path already hold reset_mutex to avoid PCI access
4936			 * while OCR is in progress.
4937			 */
4938			mutex_unlock(&instance->reset_mutex);
4939			megasas_reset_fusion(instance->host,
4940						MFI_IO_TIMEOUT_OCR);
4941			mutex_lock(&instance->reset_mutex);
4942			break;
4943		case KILL_ADAPTER:
4944			megaraid_sas_kill_hba(instance);
4945			break;
4946		case IGNORE_TIMEOUT:
4947			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4948				__func__, __LINE__);
4949			break;
4950		}
4951
4952		break;
4953	case DCMD_SUCCESS:
4954		tgtid_count = le32_to_cpu(ci->count);
4955
4956		if (megasas_dbg_lvl & LD_PD_DEBUG)
4957			dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4958				 __func__, tgtid_count);
4959
4960		if ((tgtid_count > (instance->fw_supported_vd_count)))
4961			break;
4962
4963		memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
4964		for (ld_index = 0; ld_index < tgtid_count; ld_index++) {
4965			ids = ci->targetId[ld_index];
4966			instance->ld_ids[ids] = ci->targetId[ld_index];
4967			if (megasas_dbg_lvl & LD_PD_DEBUG)
4968				dev_info(&instance->pdev->dev, "LD%d: targetID: 0x%03x\n",
4969					 ld_index, ci->targetId[ld_index]);
4970		}
4971
4972		break;
4973	}
4974
4975	if (ret != DCMD_TIMEOUT)
4976		megasas_return_cmd(instance, cmd);
4977
4978	return ret;
4979}
4980
4981/**
4982 * megasas_host_device_list_query
4983 * dcmd.opcode            - MR_DCMD_CTRL_DEVICE_LIST_GET
4984 * dcmd.mbox              - reserved
4985 * dcmd.sge IN            - ptr to return MR_HOST_DEVICE_LIST structure
4986 * Desc:    This DCMD will return the combined device list
4987 * Status:  MFI_STAT_OK - List returned successfully
4988 *          MFI_STAT_INVALID_CMD - Firmware support for the feature has been
4989 *                                 disabled
4990 * @instance:			Adapter soft state
4991 * @is_probe:			Driver probe check
4992 * Return:			0 if DCMD succeeded
4993 *				 non-zero if failed
4994 */
4995static int
4996megasas_host_device_list_query(struct megasas_instance *instance,
4997			       bool is_probe)
4998{
4999	int ret, i, target_id;
5000	struct megasas_cmd *cmd;
5001	struct megasas_dcmd_frame *dcmd;
5002	struct MR_HOST_DEVICE_LIST *ci;
5003	u32 count;
5004	dma_addr_t ci_h;
5005
5006	ci = instance->host_device_list_buf;
5007	ci_h = instance->host_device_list_buf_h;
5008
5009	cmd = megasas_get_cmd(instance);
5010
5011	if (!cmd) {
5012		dev_warn(&instance->pdev->dev,
5013			 "%s: failed to get cmd\n",
5014			 __func__);
5015		return -ENOMEM;
5016	}
5017
5018	dcmd = &cmd->frame->dcmd;
5019
5020	memset(ci, 0, sizeof(*ci));
5021	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5022
5023	dcmd->mbox.b[0] = is_probe ? 0 : 1;
5024	dcmd->cmd = MFI_CMD_DCMD;
5025	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5026	dcmd->sge_count = 1;
5027	dcmd->flags = MFI_FRAME_DIR_READ;
5028	dcmd->timeout = 0;
5029	dcmd->pad_0 = 0;
5030	dcmd->data_xfer_len = cpu_to_le32(HOST_DEVICE_LIST_SZ);
5031	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_DEVICE_LIST_GET);
5032
5033	megasas_set_dma_settings(instance, dcmd, ci_h, HOST_DEVICE_LIST_SZ);
5034
5035	if (!instance->mask_interrupts) {
5036		ret = megasas_issue_blocked_cmd(instance, cmd,
5037						MFI_IO_TIMEOUT_SECS);
5038	} else {
5039		ret = megasas_issue_polled(instance, cmd);
5040		cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5041	}
5042
5043	switch (ret) {
5044	case DCMD_SUCCESS:
5045		/* Fill the internal pd_list and ld_ids array based on
5046		 * targetIds returned by FW
5047		 */
5048		count = le32_to_cpu(ci->count);
5049
5050		if (count > (MEGASAS_MAX_PD + MAX_LOGICAL_DRIVES_EXT))
5051			break;
5052
5053		if (megasas_dbg_lvl & LD_PD_DEBUG)
5054			dev_info(&instance->pdev->dev, "%s, Device count: 0x%x\n",
5055				 __func__, count);
5056
5057		memset(instance->local_pd_list, 0,
5058		       MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
5059		memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
5060		for (i = 0; i < count; i++) {
5061			target_id = le16_to_cpu(ci->host_device_list[i].target_id);
5062			if (ci->host_device_list[i].flags.u.bits.is_sys_pd) {
5063				instance->local_pd_list[target_id].tid = target_id;
5064				instance->local_pd_list[target_id].driveType =
5065						ci->host_device_list[i].scsi_type;
5066				instance->local_pd_list[target_id].driveState =
5067						MR_PD_STATE_SYSTEM;
5068				if (megasas_dbg_lvl & LD_PD_DEBUG)
5069					dev_info(&instance->pdev->dev,
5070						 "Device %d: PD targetID: 0x%03x deviceType:0x%x\n",
5071						 i, target_id, ci->host_device_list[i].scsi_type);
5072			} else {
5073				instance->ld_ids[target_id] = target_id;
5074				if (megasas_dbg_lvl & LD_PD_DEBUG)
5075					dev_info(&instance->pdev->dev,
5076						 "Device %d: LD targetID: 0x%03x\n",
5077						 i, target_id);
5078			}
5079		}
5080
5081		memcpy(instance->pd_list, instance->local_pd_list,
5082		       sizeof(instance->pd_list));
5083		break;
5084
5085	case DCMD_TIMEOUT:
5086		switch (dcmd_timeout_ocr_possible(instance)) {
5087		case INITIATE_OCR:
5088			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5089			mutex_unlock(&instance->reset_mutex);
5090			megasas_reset_fusion(instance->host,
5091				MFI_IO_TIMEOUT_OCR);
5092			mutex_lock(&instance->reset_mutex);
5093			break;
5094		case KILL_ADAPTER:
5095			megaraid_sas_kill_hba(instance);
5096			break;
5097		case IGNORE_TIMEOUT:
5098			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5099				 __func__, __LINE__);
5100			break;
5101		}
5102		break;
5103	case DCMD_FAILED:
5104		dev_err(&instance->pdev->dev,
5105			"%s: MR_DCMD_CTRL_DEVICE_LIST_GET failed\n",
5106			__func__);
5107		break;
5108	}
5109
5110	if (ret != DCMD_TIMEOUT)
5111		megasas_return_cmd(instance, cmd);
5112
5113	return ret;
5114}
5115
5116/*
5117 * megasas_update_ext_vd_details : Update details w.r.t Extended VD
5118 * instance			 : Controller's instance
5119*/
5120static void megasas_update_ext_vd_details(struct megasas_instance *instance)
5121{
5122	struct fusion_context *fusion;
5123	u32 ventura_map_sz = 0;
5124
5125	fusion = instance->ctrl_context;
5126	/* For MFI based controllers return dummy success */
5127	if (!fusion)
5128		return;
5129
5130	instance->supportmax256vd =
5131		instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs;
5132	/* Below is additional check to address future FW enhancement */
5133	if (instance->ctrl_info_buf->max_lds > 64)
5134		instance->supportmax256vd = 1;
5135
5136	instance->drv_supported_vd_count = MEGASAS_MAX_LD_CHANNELS
5137					* MEGASAS_MAX_DEV_PER_CHANNEL;
5138	instance->drv_supported_pd_count = MEGASAS_MAX_PD_CHANNELS
5139					* MEGASAS_MAX_DEV_PER_CHANNEL;
5140	if (instance->supportmax256vd) {
5141		instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES_EXT;
5142		instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
5143	} else {
5144		instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
5145		instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
5146	}
5147
5148	dev_info(&instance->pdev->dev,
5149		"FW provided supportMaxExtLDs: %d\tmax_lds: %d\n",
5150		instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs ? 1 : 0,
5151		instance->ctrl_info_buf->max_lds);
5152
5153	if (instance->max_raid_mapsize) {
5154		ventura_map_sz = instance->max_raid_mapsize *
5155						MR_MIN_MAP_SIZE; /* 64k */
5156		fusion->current_map_sz = ventura_map_sz;
5157		fusion->max_map_sz = ventura_map_sz;
5158	} else {
5159		fusion->old_map_sz =
5160			struct_size_t(struct MR_FW_RAID_MAP, ldSpanMap,
5161				      instance->fw_supported_vd_count);
5162		fusion->new_map_sz =  sizeof(struct MR_FW_RAID_MAP_EXT);
5163
5164		fusion->max_map_sz =
5165			max(fusion->old_map_sz, fusion->new_map_sz);
5166
5167		if (instance->supportmax256vd)
5168			fusion->current_map_sz = fusion->new_map_sz;
5169		else
5170			fusion->current_map_sz = fusion->old_map_sz;
5171	}
5172	/* irrespective of FW raid maps, driver raid map is constant */
5173	fusion->drv_map_sz = sizeof(struct MR_DRV_RAID_MAP_ALL);
5174}
5175
5176/*
5177 * dcmd.opcode                - MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES
5178 * dcmd.hdr.length            - number of bytes to read
5179 * dcmd.sge                   - Ptr to MR_SNAPDUMP_PROPERTIES
5180 * Desc:			 Fill in snapdump properties
5181 * Status:			 MFI_STAT_OK- Command successful
5182 */
5183void megasas_get_snapdump_properties(struct megasas_instance *instance)
5184{
5185	int ret = 0;
5186	struct megasas_cmd *cmd;
5187	struct megasas_dcmd_frame *dcmd;
5188	struct MR_SNAPDUMP_PROPERTIES *ci;
5189	dma_addr_t ci_h = 0;
5190
5191	ci = instance->snapdump_prop;
5192	ci_h = instance->snapdump_prop_h;
5193
5194	if (!ci)
5195		return;
5196
5197	cmd = megasas_get_cmd(instance);
5198
5199	if (!cmd) {
5200		dev_dbg(&instance->pdev->dev, "Failed to get a free cmd\n");
5201		return;
5202	}
5203
5204	dcmd = &cmd->frame->dcmd;
5205
5206	memset(ci, 0, sizeof(*ci));
5207	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5208
5209	dcmd->cmd = MFI_CMD_DCMD;
5210	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5211	dcmd->sge_count = 1;
5212	dcmd->flags = MFI_FRAME_DIR_READ;
5213	dcmd->timeout = 0;
5214	dcmd->pad_0 = 0;
5215	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_SNAPDUMP_PROPERTIES));
5216	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES);
5217
5218	megasas_set_dma_settings(instance, dcmd, ci_h,
5219				 sizeof(struct MR_SNAPDUMP_PROPERTIES));
5220
5221	if (!instance->mask_interrupts) {
5222		ret = megasas_issue_blocked_cmd(instance, cmd,
5223						MFI_IO_TIMEOUT_SECS);
5224	} else {
5225		ret = megasas_issue_polled(instance, cmd);
5226		cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5227	}
5228
5229	switch (ret) {
5230	case DCMD_SUCCESS:
5231		instance->snapdump_wait_time =
5232			min_t(u8, ci->trigger_min_num_sec_before_ocr,
5233				MEGASAS_MAX_SNAP_DUMP_WAIT_TIME);
5234		break;
5235
5236	case DCMD_TIMEOUT:
5237		switch (dcmd_timeout_ocr_possible(instance)) {
5238		case INITIATE_OCR:
5239			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5240			mutex_unlock(&instance->reset_mutex);
5241			megasas_reset_fusion(instance->host,
5242				MFI_IO_TIMEOUT_OCR);
5243			mutex_lock(&instance->reset_mutex);
5244			break;
5245		case KILL_ADAPTER:
5246			megaraid_sas_kill_hba(instance);
5247			break;
5248		case IGNORE_TIMEOUT:
5249			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5250				__func__, __LINE__);
5251			break;
5252		}
5253	}
5254
5255	if (ret != DCMD_TIMEOUT)
5256		megasas_return_cmd(instance, cmd);
5257}
5258
5259/**
5260 * megasas_get_ctrl_info -	Returns FW's controller structure
5261 * @instance:				Adapter soft state
5262 *
5263 * Issues an internal command (DCMD) to get the FW's controller structure.
5264 * This information is mainly used to find out the maximum IO transfer per
5265 * command supported by the FW.
5266 */
5267int
5268megasas_get_ctrl_info(struct megasas_instance *instance)
5269{
5270	int ret = 0;
5271	struct megasas_cmd *cmd;
5272	struct megasas_dcmd_frame *dcmd;
5273	struct megasas_ctrl_info *ci;
5274	dma_addr_t ci_h = 0;
5275
5276	ci = instance->ctrl_info_buf;
5277	ci_h = instance->ctrl_info_buf_h;
5278
5279	cmd = megasas_get_cmd(instance);
5280
5281	if (!cmd) {
5282		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a free cmd\n");
5283		return -ENOMEM;
5284	}
5285
5286	dcmd = &cmd->frame->dcmd;
5287
5288	memset(ci, 0, sizeof(*ci));
5289	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5290
5291	dcmd->cmd = MFI_CMD_DCMD;
5292	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5293	dcmd->sge_count = 1;
5294	dcmd->flags = MFI_FRAME_DIR_READ;
5295	dcmd->timeout = 0;
5296	dcmd->pad_0 = 0;
5297	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_ctrl_info));
5298	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_GET_INFO);
5299	dcmd->mbox.b[0] = 1;
5300
5301	megasas_set_dma_settings(instance, dcmd, ci_h,
5302				 sizeof(struct megasas_ctrl_info));
5303
5304	if ((instance->adapter_type != MFI_SERIES) &&
5305	    !instance->mask_interrupts) {
5306		ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5307	} else {
5308		ret = megasas_issue_polled(instance, cmd);
5309		cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5310	}
5311
5312	switch (ret) {
5313	case DCMD_SUCCESS:
5314		/* Save required controller information in
5315		 * CPU endianness format.
5316		 */
5317		le32_to_cpus((u32 *)&ci->properties.OnOffProperties);
5318		le16_to_cpus((u16 *)&ci->properties.on_off_properties2);
5319		le32_to_cpus((u32 *)&ci->adapterOperations2);
5320		le32_to_cpus((u32 *)&ci->adapterOperations3);
5321		le16_to_cpus((u16 *)&ci->adapter_operations4);
5322		le32_to_cpus((u32 *)&ci->adapter_operations5);
5323
5324		/* Update the latest Ext VD info.
5325		 * From Init path, store current firmware details.
5326		 * From OCR path, detect any firmware properties changes.
5327		 * in case of Firmware upgrade without system reboot.
5328		 */
5329		megasas_update_ext_vd_details(instance);
5330		instance->support_seqnum_jbod_fp =
5331			ci->adapterOperations3.useSeqNumJbodFP;
5332		instance->support_morethan256jbod =
5333			ci->adapter_operations4.support_pd_map_target_id;
5334		instance->support_nvme_passthru =
5335			ci->adapter_operations4.support_nvme_passthru;
5336		instance->support_pci_lane_margining =
5337			ci->adapter_operations5.support_pci_lane_margining;
5338		instance->task_abort_tmo = ci->TaskAbortTO;
5339		instance->max_reset_tmo = ci->MaxResetTO;
5340
5341		/*Check whether controller is iMR or MR */
5342		instance->is_imr = (ci->memory_size ? 0 : 1);
5343
5344		instance->snapdump_wait_time =
5345			(ci->properties.on_off_properties2.enable_snap_dump ?
5346			 MEGASAS_DEFAULT_SNAP_DUMP_WAIT_TIME : 0);
5347
5348		instance->enable_fw_dev_list =
5349			ci->properties.on_off_properties2.enable_fw_dev_list;
5350
5351		dev_info(&instance->pdev->dev,
5352			"controller type\t: %s(%dMB)\n",
5353			instance->is_imr ? "iMR" : "MR",
5354			le16_to_cpu(ci->memory_size));
5355
5356		instance->disableOnlineCtrlReset =
5357			ci->properties.OnOffProperties.disableOnlineCtrlReset;
5358		instance->secure_jbod_support =
5359			ci->adapterOperations3.supportSecurityonJBOD;
5360		dev_info(&instance->pdev->dev, "Online Controller Reset(OCR)\t: %s\n",
5361			instance->disableOnlineCtrlReset ? "Disabled" : "Enabled");
5362		dev_info(&instance->pdev->dev, "Secure JBOD support\t: %s\n",
5363			instance->secure_jbod_support ? "Yes" : "No");
5364		dev_info(&instance->pdev->dev, "NVMe passthru support\t: %s\n",
5365			 instance->support_nvme_passthru ? "Yes" : "No");
5366		dev_info(&instance->pdev->dev,
5367			 "FW provided TM TaskAbort/Reset timeout\t: %d secs/%d secs\n",
5368			 instance->task_abort_tmo, instance->max_reset_tmo);
5369		dev_info(&instance->pdev->dev, "JBOD sequence map support\t: %s\n",
5370			 instance->support_seqnum_jbod_fp ? "Yes" : "No");
5371		dev_info(&instance->pdev->dev, "PCI Lane Margining support\t: %s\n",
5372			 instance->support_pci_lane_margining ? "Yes" : "No");
5373
5374		break;
5375
5376	case DCMD_TIMEOUT:
5377		switch (dcmd_timeout_ocr_possible(instance)) {
5378		case INITIATE_OCR:
5379			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5380			mutex_unlock(&instance->reset_mutex);
5381			megasas_reset_fusion(instance->host,
5382				MFI_IO_TIMEOUT_OCR);
5383			mutex_lock(&instance->reset_mutex);
5384			break;
5385		case KILL_ADAPTER:
5386			megaraid_sas_kill_hba(instance);
5387			break;
5388		case IGNORE_TIMEOUT:
5389			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5390				__func__, __LINE__);
5391			break;
5392		}
5393		break;
5394	case DCMD_FAILED:
5395		megaraid_sas_kill_hba(instance);
5396		break;
5397
5398	}
5399
5400	if (ret != DCMD_TIMEOUT)
5401		megasas_return_cmd(instance, cmd);
5402
5403	return ret;
5404}
5405
5406/*
5407 * megasas_set_crash_dump_params -	Sends address of crash dump DMA buffer
5408 *					to firmware
5409 *
5410 * @instance:				Adapter soft state
5411 * @crash_buf_state		-	tell FW to turn ON/OFF crash dump feature
5412					MR_CRASH_BUF_TURN_OFF = 0
5413					MR_CRASH_BUF_TURN_ON = 1
5414 * @return 0 on success non-zero on failure.
5415 * Issues an internal command (DCMD) to set parameters for crash dump feature.
5416 * Driver will send address of crash dump DMA buffer and set mbox to tell FW
5417 * that driver supports crash dump feature. This DCMD will be sent only if
5418 * crash dump feature is supported by the FW.
5419 *
5420 */
5421int megasas_set_crash_dump_params(struct megasas_instance *instance,
5422	u8 crash_buf_state)
5423{
5424	int ret = 0;
5425	struct megasas_cmd *cmd;
5426	struct megasas_dcmd_frame *dcmd;
5427
5428	cmd = megasas_get_cmd(instance);
5429
5430	if (!cmd) {
5431		dev_err(&instance->pdev->dev, "Failed to get a free cmd\n");
5432		return -ENOMEM;
5433	}
5434
5435
5436	dcmd = &cmd->frame->dcmd;
5437
5438	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5439	dcmd->mbox.b[0] = crash_buf_state;
5440	dcmd->cmd = MFI_CMD_DCMD;
5441	dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5442	dcmd->sge_count = 1;
5443	dcmd->flags = MFI_FRAME_DIR_NONE;
5444	dcmd->timeout = 0;
5445	dcmd->pad_0 = 0;
5446	dcmd->data_xfer_len = cpu_to_le32(CRASH_DMA_BUF_SIZE);
5447	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SET_CRASH_DUMP_PARAMS);
5448
5449	megasas_set_dma_settings(instance, dcmd, instance->crash_dump_h,
5450				 CRASH_DMA_BUF_SIZE);
5451
5452	if ((instance->adapter_type != MFI_SERIES) &&
5453	    !instance->mask_interrupts)
5454		ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5455	else
5456		ret = megasas_issue_polled(instance, cmd);
5457
5458	if (ret == DCMD_TIMEOUT) {
5459		switch (dcmd_timeout_ocr_possible(instance)) {
5460		case INITIATE_OCR:
5461			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5462			megasas_reset_fusion(instance->host,
5463					MFI_IO_TIMEOUT_OCR);
5464			break;
5465		case KILL_ADAPTER:
5466			megaraid_sas_kill_hba(instance);
5467			break;
5468		case IGNORE_TIMEOUT:
5469			dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5470				__func__, __LINE__);
5471			break;
5472		}
5473	} else
5474		megasas_return_cmd(instance, cmd);
5475
5476	return ret;
5477}
5478
5479/**
5480 * megasas_issue_init_mfi -	Initializes the FW
5481 * @instance:		Adapter soft state
5482 *
5483 * Issues the INIT MFI cmd
5484 */
5485static int
5486megasas_issue_init_mfi(struct megasas_instance *instance)
5487{
5488	__le32 context;
5489	struct megasas_cmd *cmd;
5490	struct megasas_init_frame *init_frame;
5491	struct megasas_init_queue_info *initq_info;
5492	dma_addr_t init_frame_h;
5493	dma_addr_t initq_info_h;
5494
5495	/*
5496	 * Prepare a init frame. Note the init frame points to queue info
5497	 * structure. Each frame has SGL allocated after first 64 bytes. For
5498	 * this frame - since we don't need any SGL - we use SGL's space as
5499	 * queue info structure
5500	 *
5501	 * We will not get a NULL command below. We just created the pool.
5502	 */
5503	cmd = megasas_get_cmd(instance);
5504
5505	init_frame = (struct megasas_init_frame *)cmd->frame;
5506	initq_info = (struct megasas_init_queue_info *)
5507		((unsigned long)init_frame + 64);
5508
5509	init_frame_h = cmd->frame_phys_addr;
5510	initq_info_h = init_frame_h + 64;
5511
5512	context = init_frame->context;
5513	memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
5514	memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
5515	init_frame->context = context;
5516
5517	initq_info->reply_queue_entries = cpu_to_le32(instance->max_fw_cmds + 1);
5518	initq_info->reply_queue_start_phys_addr_lo = cpu_to_le32(instance->reply_queue_h);
5519
5520	initq_info->producer_index_phys_addr_lo = cpu_to_le32(instance->producer_h);
5521	initq_info->consumer_index_phys_addr_lo = cpu_to_le32(instance->consumer_h);
5522
5523	init_frame->cmd = MFI_CMD_INIT;
5524	init_frame->cmd_status = MFI_STAT_INVALID_STATUS;
5525	init_frame->queue_info_new_phys_addr_lo =
5526		cpu_to_le32(lower_32_bits(initq_info_h));
5527	init_frame->queue_info_new_phys_addr_hi =
5528		cpu_to_le32(upper_32_bits(initq_info_h));
5529
5530	init_frame->data_xfer_len = cpu_to_le32(sizeof(struct megasas_init_queue_info));
5531
5532	/*
5533	 * disable the intr before firing the init frame to FW
5534	 */
5535	instance->instancet->disable_intr(instance);
5536
5537	/*
5538	 * Issue the init frame in polled mode
5539	 */
5540
5541	if (megasas_issue_polled(instance, cmd)) {
5542		dev_err(&instance->pdev->dev, "Failed to init firmware\n");
5543		megasas_return_cmd(instance, cmd);
5544		goto fail_fw_init;
5545	}
5546
5547	megasas_return_cmd(instance, cmd);
5548
5549	return 0;
5550
5551fail_fw_init:
5552	return -EINVAL;
5553}
5554
5555static u32
5556megasas_init_adapter_mfi(struct megasas_instance *instance)
5557{
5558	u32 context_sz;
5559	u32 reply_q_sz;
5560
5561	/*
5562	 * Get various operational parameters from status register
5563	 */
5564	instance->max_fw_cmds = instance->instancet->read_fw_status_reg(instance) & 0x00FFFF;
5565	/*
5566	 * Reduce the max supported cmds by 1. This is to ensure that the
5567	 * reply_q_sz (1 more than the max cmd that driver may send)
5568	 * does not exceed max cmds that the FW can support
5569	 */
5570	instance->max_fw_cmds = instance->max_fw_cmds-1;
5571	instance->max_mfi_cmds = instance->max_fw_cmds;
5572	instance->max_num_sge = (instance->instancet->read_fw_status_reg(instance) & 0xFF0000) >>
5573					0x10;
5574	/*
5575	 * For MFI skinny adapters, MEGASAS_SKINNY_INT_CMDS commands
5576	 * are reserved for IOCTL + driver's internal DCMDs.
5577	 */
5578	if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
5579		(instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
5580		instance->max_scsi_cmds = (instance->max_fw_cmds -
5581			MEGASAS_SKINNY_INT_CMDS);
5582		sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
5583	} else {
5584		instance->max_scsi_cmds = (instance->max_fw_cmds -
5585			MEGASAS_INT_CMDS);
5586		sema_init(&instance->ioctl_sem, (MEGASAS_MFI_IOCTL_CMDS));
5587	}
5588
5589	instance->cur_can_queue = instance->max_scsi_cmds;
5590	/*
5591	 * Create a pool of commands
5592	 */
5593	if (megasas_alloc_cmds(instance))
5594		goto fail_alloc_cmds;
5595
5596	/*
5597	 * Allocate memory for reply queue. Length of reply queue should
5598	 * be _one_ more than the maximum commands handled by the firmware.
5599	 *
5600	 * Note: When FW completes commands, it places corresponding contex
5601	 * values in this circular reply queue. This circular queue is a fairly
5602	 * typical producer-consumer queue. FW is the producer (of completed
5603	 * commands) and the driver is the consumer.
5604	 */
5605	context_sz = sizeof(u32);
5606	reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
5607
5608	instance->reply_queue = dma_alloc_coherent(&instance->pdev->dev,
5609			reply_q_sz, &instance->reply_queue_h, GFP_KERNEL);
5610
5611	if (!instance->reply_queue) {
5612		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Out of DMA mem for reply queue\n");
5613		goto fail_reply_queue;
5614	}
5615
5616	if (megasas_issue_init_mfi(instance))
5617		goto fail_fw_init;
5618
5619	if (megasas_get_ctrl_info(instance)) {
5620		dev_err(&instance->pdev->dev, "(%d): Could get controller info "
5621			"Fail from %s %d\n", instance->unique_id,
5622			__func__, __LINE__);
5623		goto fail_fw_init;
5624	}
5625
5626	instance->fw_support_ieee = 0;
5627	instance->fw_support_ieee =
5628		(instance->instancet->read_fw_status_reg(instance) &
5629		0x04000000);
5630
5631	dev_notice(&instance->pdev->dev, "megasas_init_mfi: fw_support_ieee=%d",
5632			instance->fw_support_ieee);
5633
5634	if (instance->fw_support_ieee)
5635		instance->flag_ieee = 1;
5636
5637	return 0;
5638
5639fail_fw_init:
5640
5641	dma_free_coherent(&instance->pdev->dev, reply_q_sz,
5642			    instance->reply_queue, instance->reply_queue_h);
5643fail_reply_queue:
5644	megasas_free_cmds(instance);
5645
5646fail_alloc_cmds:
5647	return 1;
5648}
5649
5650static
5651void megasas_setup_irq_poll(struct megasas_instance *instance)
5652{
5653	struct megasas_irq_context *irq_ctx;
5654	u32 count, i;
5655
5656	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5657
5658	/* Initialize IRQ poll */
5659	for (i = 0; i < count; i++) {
5660		irq_ctx = &instance->irq_context[i];
5661		irq_ctx->os_irq = pci_irq_vector(instance->pdev, i);
5662		irq_ctx->irq_poll_scheduled = false;
5663		irq_poll_init(&irq_ctx->irqpoll,
5664			      instance->threshold_reply_count,
5665			      megasas_irqpoll);
5666	}
5667}
5668
5669/*
5670 * megasas_setup_irqs_ioapic -		register legacy interrupts.
5671 * @instance:				Adapter soft state
5672 *
5673 * Do not enable interrupt, only setup ISRs.
5674 *
5675 * Return 0 on success.
5676 */
5677static int
5678megasas_setup_irqs_ioapic(struct megasas_instance *instance)
5679{
5680	struct pci_dev *pdev;
5681
5682	pdev = instance->pdev;
5683	instance->irq_context[0].instance = instance;
5684	instance->irq_context[0].MSIxIndex = 0;
5685	snprintf(instance->irq_context->name, MEGASAS_MSIX_NAME_LEN, "%s%u",
5686		"megasas", instance->host->host_no);
5687	if (request_irq(pci_irq_vector(pdev, 0),
5688			instance->instancet->service_isr, IRQF_SHARED,
5689			instance->irq_context->name, &instance->irq_context[0])) {
5690		dev_err(&instance->pdev->dev,
5691				"Failed to register IRQ from %s %d\n",
5692				__func__, __LINE__);
5693		return -1;
5694	}
5695	instance->perf_mode = MR_LATENCY_PERF_MODE;
5696	instance->low_latency_index_start = 0;
5697	return 0;
5698}
5699
5700/**
5701 * megasas_setup_irqs_msix -		register MSI-x interrupts.
5702 * @instance:				Adapter soft state
5703 * @is_probe:				Driver probe check
5704 *
5705 * Do not enable interrupt, only setup ISRs.
5706 *
5707 * Return 0 on success.
5708 */
5709static int
5710megasas_setup_irqs_msix(struct megasas_instance *instance, u8 is_probe)
5711{
5712	int i, j;
5713	struct pci_dev *pdev;
5714
5715	pdev = instance->pdev;
5716
5717	/* Try MSI-x */
5718	for (i = 0; i < instance->msix_vectors; i++) {
5719		instance->irq_context[i].instance = instance;
5720		instance->irq_context[i].MSIxIndex = i;
5721		snprintf(instance->irq_context[i].name, MEGASAS_MSIX_NAME_LEN, "%s%u-msix%u",
5722			"megasas", instance->host->host_no, i);
5723		if (request_irq(pci_irq_vector(pdev, i),
5724			instance->instancet->service_isr, 0, instance->irq_context[i].name,
5725			&instance->irq_context[i])) {
5726			dev_err(&instance->pdev->dev,
5727				"Failed to register IRQ for vector %d.\n", i);
5728			for (j = 0; j < i; j++) {
5729				if (j < instance->low_latency_index_start)
5730					irq_update_affinity_hint(
5731						pci_irq_vector(pdev, j), NULL);
5732				free_irq(pci_irq_vector(pdev, j),
5733					 &instance->irq_context[j]);
5734			}
5735			/* Retry irq register for IO_APIC*/
5736			instance->msix_vectors = 0;
5737			instance->msix_load_balance = false;
5738			if (is_probe) {
5739				pci_free_irq_vectors(instance->pdev);
5740				return megasas_setup_irqs_ioapic(instance);
5741			} else {
5742				return -1;
5743			}
5744		}
5745	}
5746
5747	return 0;
5748}
5749
5750/*
5751 * megasas_destroy_irqs-		unregister interrupts.
5752 * @instance:				Adapter soft state
5753 * return:				void
5754 */
5755static void
5756megasas_destroy_irqs(struct megasas_instance *instance) {
5757
5758	int i;
5759	int count;
5760	struct megasas_irq_context *irq_ctx;
5761
5762	count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5763	if (instance->adapter_type != MFI_SERIES) {
5764		for (i = 0; i < count; i++) {
5765			irq_ctx = &instance->irq_context[i];
5766			irq_poll_disable(&irq_ctx->irqpoll);
5767		}
5768	}
5769
5770	if (instance->msix_vectors)
5771		for (i = 0; i < instance->msix_vectors; i++) {
5772			if (i < instance->low_latency_index_start)
5773				irq_update_affinity_hint(
5774				    pci_irq_vector(instance->pdev, i), NULL);
5775			free_irq(pci_irq_vector(instance->pdev, i),
5776				 &instance->irq_context[i]);
5777		}
5778	else
5779		free_irq(pci_irq_vector(instance->pdev, 0),
5780			 &instance->irq_context[0]);
5781}
5782
5783/**
5784 * megasas_setup_jbod_map -	setup jbod map for FP seq_number.
5785 * @instance:				Adapter soft state
5786 *
5787 * Return 0 on success.
5788 */
5789void
5790megasas_setup_jbod_map(struct megasas_instance *instance)
5791{
5792	int i;
5793	struct fusion_context *fusion = instance->ctrl_context;
5794	size_t pd_seq_map_sz;
5795
5796	pd_seq_map_sz = struct_size_t(struct MR_PD_CFG_SEQ_NUM_SYNC, seq,
5797				      MAX_PHYSICAL_DEVICES);
5798
5799	instance->use_seqnum_jbod_fp =
5800		instance->support_seqnum_jbod_fp;
5801	if (reset_devices || !fusion ||
5802		!instance->support_seqnum_jbod_fp) {
5803		dev_info(&instance->pdev->dev,
5804			"JBOD sequence map is disabled %s %d\n",
5805			__func__, __LINE__);
5806		instance->use_seqnum_jbod_fp = false;
5807		return;
5808	}
5809
5810	if (fusion->pd_seq_sync[0])
5811		goto skip_alloc;
5812
5813	for (i = 0; i < JBOD_MAPS_COUNT; i++) {
5814		fusion->pd_seq_sync[i] = dma_alloc_coherent
5815			(&instance->pdev->dev, pd_seq_map_sz,
5816			&fusion->pd_seq_phys[i], GFP_KERNEL);
5817		if (!fusion->pd_seq_sync[i]) {
5818			dev_err(&instance->pdev->dev,
5819				"Failed to allocate memory from %s %d\n",
5820				__func__, __LINE__);
5821			if (i == 1) {
5822				dma_free_coherent(&instance->pdev->dev,
5823					pd_seq_map_sz, fusion->pd_seq_sync[0],
5824					fusion->pd_seq_phys[0]);
5825				fusion->pd_seq_sync[0] = NULL;
5826			}
5827			instance->use_seqnum_jbod_fp = false;
5828			return;
5829		}
5830	}
5831
5832skip_alloc:
5833	if (!megasas_sync_pd_seq_num(instance, false) &&
5834		!megasas_sync_pd_seq_num(instance, true))
5835		instance->use_seqnum_jbod_fp = true;
5836	else
5837		instance->use_seqnum_jbod_fp = false;
5838}
5839
5840static void megasas_setup_reply_map(struct megasas_instance *instance)
5841{
5842	const struct cpumask *mask;
5843	unsigned int queue, cpu, low_latency_index_start;
5844
5845	low_latency_index_start = instance->low_latency_index_start;
5846
5847	for (queue = low_latency_index_start; queue < instance->msix_vectors; queue++) {
5848		mask = pci_irq_get_affinity(instance->pdev, queue);
5849		if (!mask)
5850			goto fallback;
5851
5852		for_each_cpu(cpu, mask)
5853			instance->reply_map[cpu] = queue;
5854	}
5855	return;
5856
5857fallback:
5858	queue = low_latency_index_start;
5859	for_each_possible_cpu(cpu) {
5860		instance->reply_map[cpu] = queue;
5861		if (queue == (instance->msix_vectors - 1))
5862			queue = low_latency_index_start;
5863		else
5864			queue++;
5865	}
5866}
5867
5868/**
5869 * megasas_get_device_list -	Get the PD and LD device list from FW.
5870 * @instance:			Adapter soft state
5871 * @return:			Success or failure
5872 *
5873 * Issue DCMDs to Firmware to get the PD and LD list.
5874 * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
5875 * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
5876 */
5877static
5878int megasas_get_device_list(struct megasas_instance *instance)
5879{
5880	if (instance->enable_fw_dev_list) {
5881		if (megasas_host_device_list_query(instance, true))
5882			return FAILED;
5883	} else {
5884		if (megasas_get_pd_list(instance) < 0) {
5885			dev_err(&instance->pdev->dev, "failed to get PD list\n");
5886			return FAILED;
5887		}
5888
5889		if (megasas_ld_list_query(instance,
5890					  MR_LD_QUERY_TYPE_EXPOSED_TO_HOST)) {
5891			dev_err(&instance->pdev->dev, "failed to get LD list\n");
5892			return FAILED;
5893		}
5894	}
5895
5896	return SUCCESS;
5897}
5898
5899/**
5900 * megasas_set_high_iops_queue_affinity_and_hint -	Set affinity and hint
5901 *							for high IOPS queues
5902 * @instance:						Adapter soft state
5903 * return:						void
5904 */
5905static inline void
5906megasas_set_high_iops_queue_affinity_and_hint(struct megasas_instance *instance)
5907{
5908	int i;
5909	unsigned int irq;
5910	const struct cpumask *mask;
5911
5912	if (instance->perf_mode == MR_BALANCED_PERF_MODE) {
5913		int nid = dev_to_node(&instance->pdev->dev);
5914
5915		if (nid == NUMA_NO_NODE)
5916			nid = 0;
5917		mask = cpumask_of_node(nid);
5918
5919		for (i = 0; i < instance->low_latency_index_start; i++) {
5920			irq = pci_irq_vector(instance->pdev, i);
5921			irq_set_affinity_and_hint(irq, mask);
5922		}
5923	}
5924}
5925
5926static int
5927__megasas_alloc_irq_vectors(struct megasas_instance *instance)
5928{
5929	int i, irq_flags;
5930	struct irq_affinity desc = { .pre_vectors = instance->low_latency_index_start };
5931	struct irq_affinity *descp = &desc;
5932
5933	irq_flags = PCI_IRQ_MSIX;
5934
5935	if (instance->smp_affinity_enable)
5936		irq_flags |= PCI_IRQ_AFFINITY | PCI_IRQ_ALL_TYPES;
5937	else
5938		descp = NULL;
5939
5940	/* Do not allocate msix vectors for poll_queues.
5941	 * msix_vectors is always within a range of FW supported reply queue.
5942	 */
5943	i = pci_alloc_irq_vectors_affinity(instance->pdev,
5944		instance->low_latency_index_start,
5945		instance->msix_vectors - instance->iopoll_q_count, irq_flags, descp);
5946
5947	return i;
5948}
5949
5950/**
5951 * megasas_alloc_irq_vectors -	Allocate IRQ vectors/enable MSI-x vectors
5952 * @instance:			Adapter soft state
5953 * return:			void
5954 */
5955static void
5956megasas_alloc_irq_vectors(struct megasas_instance *instance)
5957{
5958	int i;
5959	unsigned int num_msix_req;
5960
5961	instance->iopoll_q_count = 0;
5962	if ((instance->adapter_type != MFI_SERIES) &&
5963		poll_queues) {
5964
5965		instance->perf_mode = MR_LATENCY_PERF_MODE;
5966		instance->low_latency_index_start = 1;
5967
5968		/* reserve for default and non-mananged pre-vector. */
5969		if (instance->msix_vectors > (poll_queues + 2))
5970			instance->iopoll_q_count = poll_queues;
5971		else
5972			instance->iopoll_q_count = 0;
5973
5974		num_msix_req = blk_mq_num_online_queues(0) +
5975			instance->low_latency_index_start;
5976		instance->msix_vectors = min(num_msix_req,
5977				instance->msix_vectors);
5978
5979	}
5980
5981	i = __megasas_alloc_irq_vectors(instance);
5982
5983	if (((instance->perf_mode == MR_BALANCED_PERF_MODE)
5984		|| instance->iopoll_q_count) &&
5985	    (i != (instance->msix_vectors - instance->iopoll_q_count))) {
5986		if (instance->msix_vectors)
5987			pci_free_irq_vectors(instance->pdev);
5988		/* Disable Balanced IOPS mode and try realloc vectors */
5989		instance->perf_mode = MR_LATENCY_PERF_MODE;
5990		instance->low_latency_index_start = 1;
5991		num_msix_req = blk_mq_num_online_queues(0) +
5992			instance->low_latency_index_start;
5993
5994		instance->msix_vectors = min(num_msix_req,
5995				instance->msix_vectors);
5996
5997		instance->iopoll_q_count = 0;
5998		i = __megasas_alloc_irq_vectors(instance);
5999
6000	}
6001
6002	dev_info(&instance->pdev->dev,
6003		"requested/available msix %d/%d poll_queue %d\n",
6004			instance->msix_vectors - instance->iopoll_q_count,
6005			i, instance->iopoll_q_count);
6006
6007	if (i > 0)
6008		instance->msix_vectors = i;
6009	else
6010		instance->msix_vectors = 0;
6011
6012	if (instance->smp_affinity_enable)
6013		megasas_set_high_iops_queue_affinity_and_hint(instance);
6014}
6015
6016/**
6017 * megasas_init_fw -	Initializes the FW
6018 * @instance:		Adapter soft state
6019 *
6020 * This is the main function for initializing firmware
6021 */
6022
6023static int megasas_init_fw(struct megasas_instance *instance)
6024{
6025	u32 max_sectors_1;
6026	u32 max_sectors_2, tmp_sectors, msix_enable;
6027	u32 scratch_pad_1, scratch_pad_2, scratch_pad_3, status_reg;
6028	resource_size_t base_addr;
6029	void *base_addr_phys;
6030	struct megasas_ctrl_info *ctrl_info = NULL;
6031	unsigned long bar_list;
6032	int i, j, loop;
6033	struct IOV_111 *iovPtr;
6034	struct fusion_context *fusion;
6035	bool intr_coalescing;
6036	unsigned int num_msix_req;
6037	u16 lnksta, speed;
6038
6039	fusion = instance->ctrl_context;
6040
6041	/* Find first memory bar */
6042	bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
6043	instance->bar = find_first_bit(&bar_list, BITS_PER_LONG);
6044	if (pci_request_selected_regions(instance->pdev, 1<<instance->bar,
6045					 "megasas: LSI")) {
6046		dev_printk(KERN_DEBUG, &instance->pdev->dev, "IO memory region busy!\n");
6047		return -EBUSY;
6048	}
6049
6050	base_addr = pci_resource_start(instance->pdev, instance->bar);
6051	instance->reg_set = ioremap(base_addr, 8192);
6052
6053	if (!instance->reg_set) {
6054		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to map IO mem\n");
6055		goto fail_ioremap;
6056	}
6057
6058	base_addr_phys = &base_addr;
6059	dev_printk(KERN_DEBUG, &instance->pdev->dev,
6060		   "BAR:0x%lx  BAR's base_addr(phys):%pa  mapped virt_addr:0x%p\n",
6061		   instance->bar, base_addr_phys, instance->reg_set);
6062
6063	if (instance->adapter_type != MFI_SERIES)
6064		instance->instancet = &megasas_instance_template_fusion;
6065	else {
6066		switch (instance->pdev->device) {
6067		case PCI_DEVICE_ID_LSI_SAS1078R:
6068		case PCI_DEVICE_ID_LSI_SAS1078DE:
6069			instance->instancet = &megasas_instance_template_ppc;
6070			break;
6071		case PCI_DEVICE_ID_LSI_SAS1078GEN2:
6072		case PCI_DEVICE_ID_LSI_SAS0079GEN2:
6073			instance->instancet = &megasas_instance_template_gen2;
6074			break;
6075		case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
6076		case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
6077			instance->instancet = &megasas_instance_template_skinny;
6078			break;
6079		case PCI_DEVICE_ID_LSI_SAS1064R:
6080		case PCI_DEVICE_ID_DELL_PERC5:
6081		default:
6082			instance->instancet = &megasas_instance_template_xscale;
6083			instance->pd_list_not_supported = 1;
6084			break;
6085		}
6086	}
6087
6088	if (megasas_transition_to_ready(instance, 0)) {
6089		dev_info(&instance->pdev->dev,
6090			 "Failed to transition controller to ready from %s!\n",
6091			 __func__);
6092		if (instance->adapter_type != MFI_SERIES) {
6093			status_reg = instance->instancet->read_fw_status_reg(
6094					instance);
6095			if (status_reg & MFI_RESET_ADAPTER) {
6096				if (megasas_adp_reset_wait_for_ready
6097					(instance, true, 0) == FAILED)
6098					goto fail_ready_state;
6099			} else {
6100				goto fail_ready_state;
6101			}
6102		} else {
6103			atomic_set(&instance->fw_reset_no_pci_access, 1);
6104			instance->instancet->adp_reset
6105				(instance, instance->reg_set);
6106			atomic_set(&instance->fw_reset_no_pci_access, 0);
6107
6108			/*waiting for about 30 second before retry*/
6109			ssleep(30);
6110
6111			if (megasas_transition_to_ready(instance, 0))
6112				goto fail_ready_state;
6113		}
6114
6115		dev_info(&instance->pdev->dev,
6116			 "FW restarted successfully from %s!\n",
6117			 __func__);
6118	}
6119
6120	megasas_init_ctrl_params(instance);
6121
6122	if (megasas_set_dma_mask(instance))
6123		goto fail_ready_state;
6124
6125	if (megasas_alloc_ctrl_mem(instance))
6126		goto fail_alloc_dma_buf;
6127
6128	if (megasas_alloc_ctrl_dma_buffers(instance))
6129		goto fail_alloc_dma_buf;
6130
6131	fusion = instance->ctrl_context;
6132
6133	if (instance->adapter_type >= VENTURA_SERIES) {
6134		scratch_pad_2 =
6135			megasas_readl(instance,
6136				      &instance->reg_set->outbound_scratch_pad_2);
6137		instance->max_raid_mapsize = ((scratch_pad_2 >>
6138			MR_MAX_RAID_MAP_SIZE_OFFSET_SHIFT) &
6139			MR_MAX_RAID_MAP_SIZE_MASK);
6140	}
6141
6142	instance->enable_sdev_max_qd = enable_sdev_max_qd;
6143
6144	switch (instance->adapter_type) {
6145	case VENTURA_SERIES:
6146		fusion->pcie_bw_limitation = true;
6147		break;
6148	case AERO_SERIES:
6149		fusion->r56_div_offload = true;
6150		break;
6151	default:
6152		break;
6153	}
6154
6155	/* Check if MSI-X is supported while in ready state */
6156	msix_enable = (instance->instancet->read_fw_status_reg(instance) &
6157		       0x4000000) >> 0x1a;
6158	if (msix_enable && !msix_disable) {
6159
6160		scratch_pad_1 = megasas_readl
6161			(instance, &instance->reg_set->outbound_scratch_pad_1);
6162		/* Check max MSI-X vectors */
6163		if (fusion) {
6164			if (instance->adapter_type == THUNDERBOLT_SERIES) {
6165				/* Thunderbolt Series*/
6166				instance->msix_vectors = (scratch_pad_1
6167					& MR_MAX_REPLY_QUEUES_OFFSET) + 1;
6168			} else {
6169				instance->msix_vectors = ((scratch_pad_1
6170					& MR_MAX_REPLY_QUEUES_EXT_OFFSET)
6171					>> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1;
6172
6173				/*
6174				 * For Invader series, > 8 MSI-x vectors
6175				 * supported by FW/HW implies combined
6176				 * reply queue mode is enabled.
6177				 * For Ventura series, > 16 MSI-x vectors
6178				 * supported by FW/HW implies combined
6179				 * reply queue mode is enabled.
6180				 */
6181				switch (instance->adapter_type) {
6182				case INVADER_SERIES:
6183					if (instance->msix_vectors > 8)
6184						instance->msix_combined = true;
6185					break;
6186				case AERO_SERIES:
6187				case VENTURA_SERIES:
6188					if (instance->msix_vectors > 16)
6189						instance->msix_combined = true;
6190					break;
6191				}
6192
6193				if (rdpq_enable)
6194					instance->is_rdpq = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ?
6195								1 : 0;
6196
6197				if (instance->adapter_type >= INVADER_SERIES &&
6198				    !instance->msix_combined) {
6199					instance->msix_load_balance = true;
6200					instance->smp_affinity_enable = false;
6201				}
6202
6203				/* Save 1-15 reply post index address to local memory
6204				 * Index 0 is already saved from reg offset
6205				 * MPI2_REPLY_POST_HOST_INDEX_OFFSET
6206				 */
6207				for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) {
6208					instance->reply_post_host_index_addr[loop] =
6209						(u32 __iomem *)
6210						((u8 __iomem *)instance->reg_set +
6211						MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET
6212						+ (loop * 0x10));
6213				}
6214			}
6215
6216			dev_info(&instance->pdev->dev,
6217				 "firmware supports msix\t: (%d)",
6218				 instance->msix_vectors);
6219			if (msix_vectors)
6220				instance->msix_vectors = min(msix_vectors,
6221					instance->msix_vectors);
6222		} else /* MFI adapters */
6223			instance->msix_vectors = 1;
6224
6225
6226		/*
6227		 * For Aero (if some conditions are met), driver will configure a
6228		 * few additional reply queues with interrupt coalescing enabled.
6229		 * These queues with interrupt coalescing enabled are called
6230		 * High IOPS queues and rest of reply queues (based on number of
6231		 * logical CPUs) are termed as Low latency queues.
6232		 *
6233		 * Total Number of reply queues = High IOPS queues + low latency queues
6234		 *
6235		 * For rest of fusion adapters, 1 additional reply queue will be
6236		 * reserved for management commands, rest of reply queues
6237		 * (based on number of logical CPUs) will be used for IOs and
6238		 * referenced as IO queues.
6239		 * Total Number of reply queues = 1 + IO queues
6240		 *
6241		 * MFI adapters supports single MSI-x so single reply queue
6242		 * will be used for IO and management commands.
6243		 */
6244
6245		intr_coalescing = (scratch_pad_1 & MR_INTR_COALESCING_SUPPORT_OFFSET) ?
6246								true : false;
6247		if (intr_coalescing &&
6248			(blk_mq_num_online_queues(0) >= MR_HIGH_IOPS_QUEUE_COUNT) &&
6249			(instance->msix_vectors == MEGASAS_MAX_MSIX_QUEUES))
6250			instance->perf_mode = MR_BALANCED_PERF_MODE;
6251		else
6252			instance->perf_mode = MR_LATENCY_PERF_MODE;
6253
6254
6255		if (instance->adapter_type == AERO_SERIES) {
6256			pcie_capability_read_word(instance->pdev, PCI_EXP_LNKSTA, &lnksta);
6257			speed = lnksta & PCI_EXP_LNKSTA_CLS;
6258
6259			/*
6260			 * For Aero, if PCIe link speed is <16 GT/s, then driver should operate
6261			 * in latency perf mode and enable R1 PCI bandwidth algorithm
6262			 */
6263			if (speed < 0x4) {
6264				instance->perf_mode = MR_LATENCY_PERF_MODE;
6265				fusion->pcie_bw_limitation = true;
6266			}
6267
6268			/*
6269			 * Performance mode settings provided through module parameter-perf_mode will
6270			 * take affect only for:
6271			 * 1. Aero family of adapters.
6272			 * 2. When user sets module parameter- perf_mode in range of 0-2.
6273			 */
6274			if ((perf_mode >= MR_BALANCED_PERF_MODE) &&
6275				(perf_mode <= MR_LATENCY_PERF_MODE))
6276				instance->perf_mode = perf_mode;
6277			/*
6278			 * If intr coalescing is not supported by controller FW, then IOPS
6279			 * and Balanced modes are not feasible.
6280			 */
6281			if (!intr_coalescing)
6282				instance->perf_mode = MR_LATENCY_PERF_MODE;
6283
6284		}
6285
6286		if (instance->perf_mode == MR_BALANCED_PERF_MODE)
6287			instance->low_latency_index_start =
6288				MR_HIGH_IOPS_QUEUE_COUNT;
6289		else
6290			instance->low_latency_index_start = 1;
6291
6292		num_msix_req = blk_mq_num_online_queues(0) +
6293			instance->low_latency_index_start;
6294
6295		instance->msix_vectors = min(num_msix_req,
6296				instance->msix_vectors);
6297
6298		megasas_alloc_irq_vectors(instance);
6299		if (!instance->msix_vectors)
6300			instance->msix_load_balance = false;
6301	}
6302	/*
6303	 * MSI-X host index 0 is common for all adapter.
6304	 * It is used for all MPT based Adapters.
6305	 */
6306	if (instance->msix_combined) {
6307		instance->reply_post_host_index_addr[0] =
6308				(u32 *)((u8 *)instance->reg_set +
6309				MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET);
6310	} else {
6311		instance->reply_post_host_index_addr[0] =
6312			(u32 *)((u8 *)instance->reg_set +
6313			MPI2_REPLY_POST_HOST_INDEX_OFFSET);
6314	}
6315
6316	if (!instance->msix_vectors) {
6317		i = pci_alloc_irq_vectors(instance->pdev, 1, 1, PCI_IRQ_INTX);
6318		if (i < 0)
6319			goto fail_init_adapter;
6320	}
6321
6322	megasas_setup_reply_map(instance);
6323
6324	dev_info(&instance->pdev->dev,
6325		"current msix/max num queues\t: (%d/%u)\n",
6326		instance->msix_vectors, blk_mq_num_online_queues(0));
6327	dev_info(&instance->pdev->dev,
6328		"RDPQ mode\t: (%s)\n", instance->is_rdpq ? "enabled" : "disabled");
6329
6330	tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
6331		(unsigned long)instance);
6332
6333	/*
6334	 * Below are default value for legacy Firmware.
6335	 * non-fusion based controllers
6336	 */
6337	instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
6338	instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
6339	/* Get operational params, sge flags, send init cmd to controller */
6340	if (instance->instancet->init_adapter(instance))
6341		goto fail_init_adapter;
6342
6343	if (instance->adapter_type >= VENTURA_SERIES) {
6344		scratch_pad_3 =
6345			megasas_readl(instance,
6346				      &instance->reg_set->outbound_scratch_pad_3);
6347		if ((scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK) >=
6348			MR_DEFAULT_NVME_PAGE_SHIFT)
6349			instance->nvme_page_size =
6350				(1 << (scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK));
6351
6352		dev_info(&instance->pdev->dev,
6353			 "NVME page size\t: (%d)\n", instance->nvme_page_size);
6354	}
6355
6356	if (instance->msix_vectors ?
6357		megasas_setup_irqs_msix(instance, 1) :
6358		megasas_setup_irqs_ioapic(instance))
6359		goto fail_init_adapter;
6360
6361	if (instance->adapter_type != MFI_SERIES)
6362		megasas_setup_irq_poll(instance);
6363
6364	instance->instancet->enable_intr(instance);
6365
6366	dev_info(&instance->pdev->dev, "INIT adapter done\n");
6367
6368	megasas_setup_jbod_map(instance);
6369
6370	if (megasas_get_device_list(instance) != SUCCESS) {
6371		dev_err(&instance->pdev->dev,
6372			"%s: megasas_get_device_list failed\n",
6373			__func__);
6374		goto fail_get_ld_pd_list;
6375	}
6376
6377	/* stream detection initialization */
6378	if (instance->adapter_type >= VENTURA_SERIES) {
6379		fusion->stream_detect_by_ld =
6380			kcalloc(MAX_LOGICAL_DRIVES_EXT,
6381				sizeof(struct LD_STREAM_DETECT *),
6382				GFP_KERNEL);
6383		if (!fusion->stream_detect_by_ld) {
6384			dev_err(&instance->pdev->dev,
6385				"unable to allocate stream detection for pool of LDs\n");
6386			goto fail_get_ld_pd_list;
6387		}
6388		for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) {
6389			fusion->stream_detect_by_ld[i] =
6390				kzalloc(sizeof(struct LD_STREAM_DETECT),
6391				GFP_KERNEL);
6392			if (!fusion->stream_detect_by_ld[i]) {
6393				dev_err(&instance->pdev->dev,
6394					"unable to allocate stream detect by LD\n");
6395				for (j = 0; j < i; ++j)
6396					kfree(fusion->stream_detect_by_ld[j]);
6397				kfree(fusion->stream_detect_by_ld);
6398				fusion->stream_detect_by_ld = NULL;
6399				goto fail_get_ld_pd_list;
6400			}
6401			fusion->stream_detect_by_ld[i]->mru_bit_map
6402				= MR_STREAM_BITMAP;
6403		}
6404	}
6405
6406	/*
6407	 * Compute the max allowed sectors per IO: The controller info has two
6408	 * limits on max sectors. Driver should use the minimum of these two.
6409	 *
6410	 * 1 << stripe_sz_ops.min = max sectors per strip
6411	 *
6412	 * Note that older firmwares ( < FW ver 30) didn't report information
6413	 * to calculate max_sectors_1. So the number ended up as zero always.
6414	 */
6415	tmp_sectors = 0;
6416	ctrl_info = instance->ctrl_info_buf;
6417
6418	max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
6419		le16_to_cpu(ctrl_info->max_strips_per_io);
6420	max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size);
6421
6422	tmp_sectors = min_t(u32, max_sectors_1, max_sectors_2);
6423
6424	instance->peerIsPresent = ctrl_info->cluster.peerIsPresent;
6425	instance->passive = ctrl_info->cluster.passive;
6426	memcpy(instance->clusterId, ctrl_info->clusterId, sizeof(instance->clusterId));
6427	instance->UnevenSpanSupport =
6428		ctrl_info->adapterOperations2.supportUnevenSpans;
6429	if (instance->UnevenSpanSupport) {
6430		struct fusion_context *fusion = instance->ctrl_context;
6431		if (MR_ValidateMapInfo(instance, instance->map_id))
6432			fusion->fast_path_io = 1;
6433		else
6434			fusion->fast_path_io = 0;
6435
6436	}
6437	if (ctrl_info->host_interface.SRIOV) {
6438		instance->requestorId = ctrl_info->iov.requestorId;
6439		if (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) {
6440			if (!ctrl_info->adapterOperations2.activePassive)
6441			    instance->PlasmaFW111 = 1;
6442
6443			dev_info(&instance->pdev->dev, "SR-IOV: firmware type: %s\n",
6444			    instance->PlasmaFW111 ? "1.11" : "new");
6445
6446			if (instance->PlasmaFW111) {
6447			    iovPtr = (struct IOV_111 *)
6448				((unsigned char *)ctrl_info + IOV_111_OFFSET);
6449			    instance->requestorId = iovPtr->requestorId;
6450			}
6451		}
6452		dev_info(&instance->pdev->dev, "SRIOV: VF requestorId %d\n",
6453			instance->requestorId);
6454	}
6455
6456	instance->crash_dump_fw_support =
6457		ctrl_info->adapterOperations3.supportCrashDump;
6458	instance->crash_dump_drv_support =
6459		(instance->crash_dump_fw_support &&
6460		instance->crash_dump_buf);
6461	if (instance->crash_dump_drv_support)
6462		megasas_set_crash_dump_params(instance,
6463			MR_CRASH_BUF_TURN_OFF);
6464
6465	else {
6466		if (instance->crash_dump_buf)
6467			dma_free_coherent(&instance->pdev->dev,
6468				CRASH_DMA_BUF_SIZE,
6469				instance->crash_dump_buf,
6470				instance->crash_dump_h);
6471		instance->crash_dump_buf = NULL;
6472	}
6473
6474	if (instance->snapdump_wait_time) {
6475		megasas_get_snapdump_properties(instance);
6476		dev_info(&instance->pdev->dev, "Snap dump wait time\t: %d\n",
6477			 instance->snapdump_wait_time);
6478	}
6479
6480	dev_info(&instance->pdev->dev,
6481		"pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n",
6482		le16_to_cpu(ctrl_info->pci.vendor_id),
6483		le16_to_cpu(ctrl_info->pci.device_id),
6484		le16_to_cpu(ctrl_info->pci.sub_vendor_id),
6485		le16_to_cpu(ctrl_info->pci.sub_device_id));
6486	dev_info(&instance->pdev->dev, "unevenspan support	: %s\n",
6487		instance->UnevenSpanSupport ? "yes" : "no");
6488	dev_info(&instance->pdev->dev, "firmware crash dump	: %s\n",
6489		instance->crash_dump_drv_support ? "yes" : "no");
6490	dev_info(&instance->pdev->dev, "JBOD sequence map	: %s\n",
6491		instance->use_seqnum_jbod_fp ? "enabled" : "disabled");
6492
6493	instance->max_sectors_per_req = instance->max_num_sge *
6494						SGE_BUFFER_SIZE / 512;
6495	if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
6496		instance->max_sectors_per_req = tmp_sectors;
6497
6498	/* Check for valid throttlequeuedepth module parameter */
6499	if (throttlequeuedepth &&
6500			throttlequeuedepth <= instance->max_scsi_cmds)
6501		instance->throttlequeuedepth = throttlequeuedepth;
6502	else
6503		instance->throttlequeuedepth =
6504				MEGASAS_THROTTLE_QUEUE_DEPTH;
6505
6506	if ((resetwaittime < 1) ||
6507	    (resetwaittime > MEGASAS_RESET_WAIT_TIME))
6508		resetwaittime = MEGASAS_RESET_WAIT_TIME;
6509
6510	if ((scmd_timeout < 10) || (scmd_timeout > MEGASAS_DEFAULT_CMD_TIMEOUT))
6511		scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT;
6512
6513	/* Launch SR-IOV heartbeat timer */
6514	if (instance->requestorId) {
6515		if (!megasas_sriov_start_heartbeat(instance, 1)) {
6516			megasas_start_timer(instance);
6517		} else {
6518			instance->skip_heartbeat_timer_del = 1;
6519			goto fail_get_ld_pd_list;
6520		}
6521	}
6522
6523	/*
6524	 * Create and start watchdog thread which will monitor
6525	 * controller state every 1 sec and trigger OCR when
6526	 * it enters fault state
6527	 */
6528	if (instance->adapter_type != MFI_SERIES)
6529		if (megasas_fusion_start_watchdog(instance) != SUCCESS)
6530			goto fail_start_watchdog;
6531
6532	return 0;
6533
6534fail_start_watchdog:
6535	if (instance->requestorId && !instance->skip_heartbeat_timer_del)
6536		timer_delete_sync(&instance->sriov_heartbeat_timer);
6537fail_get_ld_pd_list:
6538	instance->instancet->disable_intr(instance);
6539	megasas_destroy_irqs(instance);
6540fail_init_adapter:
6541	if (instance->msix_vectors)
6542		pci_free_irq_vectors(instance->pdev);
6543	instance->msix_vectors = 0;
6544fail_alloc_dma_buf:
6545	megasas_free_ctrl_dma_buffers(instance);
6546	megasas_free_ctrl_mem(instance);
6547fail_ready_state:
6548	iounmap(instance->reg_set);
6549
6550fail_ioremap:
6551	pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6552
6553	dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6554		__func__, __LINE__);
6555	return -EINVAL;
6556}
6557
6558/**
6559 * megasas_release_mfi -	Reverses the FW initialization
6560 * @instance:			Adapter soft state
6561 */
6562static void megasas_release_mfi(struct megasas_instance *instance)
6563{
6564	u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
6565
6566	if (instance->reply_queue)
6567		dma_free_coherent(&instance->pdev->dev, reply_q_sz,
6568			    instance->reply_queue, instance->reply_queue_h);
6569
6570	megasas_free_cmds(instance);
6571
6572	iounmap(instance->reg_set);
6573
6574	pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6575}
6576
6577/**
6578 * megasas_get_seq_num -	Gets latest event sequence numbers
6579 * @instance:			Adapter soft state
6580 * @eli:			FW event log sequence numbers information
6581 *
6582 * FW maintains a log of all events in a non-volatile area. Upper layers would
6583 * usually find out the latest sequence number of the events, the seq number at
6584 * the boot etc. They would "read" all the events below the latest seq number
6585 * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
6586 * number), they would subsribe to AEN (asynchronous event notification) and
6587 * wait for the events to happen.
6588 */
6589static int
6590megasas_get_seq_num(struct megasas_instance *instance,
6591		    struct megasas_evt_log_info *eli)
6592{
6593	struct megasas_cmd *cmd;
6594	struct megasas_dcmd_frame *dcmd;
6595	struct megasas_evt_log_info *el_info;
6596	dma_addr_t el_info_h = 0;
6597	int ret;
6598
6599	cmd = megasas_get_cmd(instance);
6600
6601	if (!cmd) {
6602		return -ENOMEM;
6603	}
6604
6605	dcmd = &cmd->frame->dcmd;
6606	el_info = dma_alloc_coherent(&instance->pdev->dev,
6607				     sizeof(struct megasas_evt_log_info),
6608				     &el_info_h, GFP_KERNEL);
6609	if (!el_info) {
6610		megasas_return_cmd(instance, cmd);
6611		return -ENOMEM;
6612	}
6613
6614	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6615
6616	dcmd->cmd = MFI_CMD_DCMD;
6617	dcmd->cmd_status = 0x0;
6618	dcmd->sge_count = 1;
6619	dcmd->flags = MFI_FRAME_DIR_READ;
6620	dcmd->timeout = 0;
6621	dcmd->pad_0 = 0;
6622	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_log_info));
6623	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_GET_INFO);
6624
6625	megasas_set_dma_settings(instance, dcmd, el_info_h,
6626				 sizeof(struct megasas_evt_log_info));
6627
6628	ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
6629	if (ret != DCMD_SUCCESS) {
6630		dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6631			__func__, __LINE__);
6632		goto dcmd_failed;
6633	}
6634
6635	/*
6636	 * Copy the data back into callers buffer
6637	 */
6638	eli->newest_seq_num = el_info->newest_seq_num;
6639	eli->oldest_seq_num = el_info->oldest_seq_num;
6640	eli->clear_seq_num = el_info->clear_seq_num;
6641	eli->shutdown_seq_num = el_info->shutdown_seq_num;
6642	eli->boot_seq_num = el_info->boot_seq_num;
6643
6644dcmd_failed:
6645	dma_free_coherent(&instance->pdev->dev,
6646			sizeof(struct megasas_evt_log_info),
6647			el_info, el_info_h);
6648
6649	megasas_return_cmd(instance, cmd);
6650
6651	return ret;
6652}
6653
6654/**
6655 * megasas_register_aen -	Registers for asynchronous event notification
6656 * @instance:			Adapter soft state
6657 * @seq_num:			The starting sequence number
6658 * @class_locale_word:		Class of the event
6659 *
6660 * This function subscribes for AEN for events beyond the @seq_num. It requests
6661 * to be notified if and only if the event is of type @class_locale
6662 */
6663static int
6664megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
6665		     u32 class_locale_word)
6666{
6667	int ret_val;
6668	struct megasas_cmd *cmd;
6669	struct megasas_dcmd_frame *dcmd;
6670	union megasas_evt_class_locale curr_aen;
6671	union megasas_evt_class_locale prev_aen;
6672
6673	/*
6674	 * If there an AEN pending already (aen_cmd), check if the
6675	 * class_locale of that pending AEN is inclusive of the new
6676	 * AEN request we currently have. If it is, then we don't have
6677	 * to do anything. In other words, whichever events the current
6678	 * AEN request is subscribing to, have already been subscribed
6679	 * to.
6680	 *
6681	 * If the old_cmd is _not_ inclusive, then we have to abort
6682	 * that command, form a class_locale that is superset of both
6683	 * old and current and re-issue to the FW
6684	 */
6685
6686	curr_aen.word = class_locale_word;
6687
6688	if (instance->aen_cmd) {
6689
6690		prev_aen.word =
6691			le32_to_cpu(instance->aen_cmd->frame->dcmd.mbox.w[1]);
6692
6693		if ((curr_aen.members.class < MFI_EVT_CLASS_DEBUG) ||
6694		    (curr_aen.members.class > MFI_EVT_CLASS_DEAD)) {
6695			dev_info(&instance->pdev->dev,
6696				 "%s %d out of range class %d send by application\n",
6697				 __func__, __LINE__, curr_aen.members.class);
6698			return 0;
6699		}
6700
6701		/*
6702		 * A class whose enum value is smaller is inclusive of all
6703		 * higher values. If a PROGRESS (= -1) was previously
6704		 * registered, then a new registration requests for higher
6705		 * classes need not be sent to FW. They are automatically
6706		 * included.
6707		 *
6708		 * Locale numbers don't have such hierarchy. They are bitmap
6709		 * values
6710		 */
6711		if ((prev_aen.members.class <= curr_aen.members.class) &&
6712		    !((prev_aen.members.locale & curr_aen.members.locale) ^
6713		      curr_aen.members.locale)) {
6714			/*
6715			 * Previously issued event registration includes
6716			 * current request. Nothing to do.
6717			 */
6718			return 0;
6719		} else {
6720			curr_aen.members.locale |= prev_aen.members.locale;
6721
6722			if (prev_aen.members.class < curr_aen.members.class)
6723				curr_aen.members.class = prev_aen.members.class;
6724
6725			instance->aen_cmd->abort_aen = 1;
6726			ret_val = megasas_issue_blocked_abort_cmd(instance,
6727								  instance->
6728								  aen_cmd, 30);
6729
6730			if (ret_val) {
6731				dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to abort "
6732				       "previous AEN command\n");
6733				return ret_val;
6734			}
6735		}
6736	}
6737
6738	cmd = megasas_get_cmd(instance);
6739
6740	if (!cmd)
6741		return -ENOMEM;
6742
6743	dcmd = &cmd->frame->dcmd;
6744
6745	memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
6746
6747	/*
6748	 * Prepare DCMD for aen registration
6749	 */
6750	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6751
6752	dcmd->cmd = MFI_CMD_DCMD;
6753	dcmd->cmd_status = 0x0;
6754	dcmd->sge_count = 1;
6755	dcmd->flags = MFI_FRAME_DIR_READ;
6756	dcmd->timeout = 0;
6757	dcmd->pad_0 = 0;
6758	dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_detail));
6759	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_WAIT);
6760	dcmd->mbox.w[0] = cpu_to_le32(seq_num);
6761	instance->last_seq_num = seq_num;
6762	dcmd->mbox.w[1] = cpu_to_le32(curr_aen.word);
6763
6764	megasas_set_dma_settings(instance, dcmd, instance->evt_detail_h,
6765				 sizeof(struct megasas_evt_detail));
6766
6767	if (instance->aen_cmd != NULL) {
6768		megasas_return_cmd(instance, cmd);
6769		return 0;
6770	}
6771
6772	/*
6773	 * Store reference to the cmd used to register for AEN. When an
6774	 * application wants us to register for AEN, we have to abort this
6775	 * cmd and re-register with a new EVENT LOCALE supplied by that app
6776	 */
6777	instance->aen_cmd = cmd;
6778
6779	/*
6780	 * Issue the aen registration frame
6781	 */
6782	instance->instancet->issue_dcmd(instance, cmd);
6783
6784	return 0;
6785}
6786
6787/* megasas_get_target_prop - Send DCMD with below details to firmware.
6788 *
6789 * This DCMD will fetch few properties of LD/system PD defined
6790 * in MR_TARGET_DEV_PROPERTIES. eg. Queue Depth, MDTS value.
6791 *
6792 * DCMD send by drivers whenever new target is added to the OS.
6793 *
6794 * dcmd.opcode         - MR_DCMD_DEV_GET_TARGET_PROP
6795 * dcmd.mbox.b[0]      - DCMD is to be fired for LD or system PD.
6796 *                       0 = system PD, 1 = LD.
6797 * dcmd.mbox.s[1]      - TargetID for LD/system PD.
6798 * dcmd.sge IN         - Pointer to return MR_TARGET_DEV_PROPERTIES.
6799 *
6800 * @instance:		Adapter soft state
6801 * @sdev:		OS provided scsi device
6802 *
6803 * Returns 0 on success non-zero on failure.
6804 */
6805int
6806megasas_get_target_prop(struct megasas_instance *instance,
6807			struct scsi_device *sdev)
6808{
6809	int ret;
6810	struct megasas_cmd *cmd;
6811	struct megasas_dcmd_frame *dcmd;
6812	u16 targetId = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL) +
6813			sdev->id;
6814
6815	cmd = megasas_get_cmd(instance);
6816
6817	if (!cmd) {
6818		dev_err(&instance->pdev->dev,
6819			"Failed to get cmd %s\n", __func__);
6820		return -ENOMEM;
6821	}
6822
6823	dcmd = &cmd->frame->dcmd;
6824
6825	memset(instance->tgt_prop, 0, sizeof(*instance->tgt_prop));
6826	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6827	dcmd->mbox.b[0] = MEGASAS_IS_LOGICAL(sdev);
6828
6829	dcmd->mbox.s[1] = cpu_to_le16(targetId);
6830	dcmd->cmd = MFI_CMD_DCMD;
6831	dcmd->cmd_status = 0xFF;
6832	dcmd->sge_count = 1;
6833	dcmd->flags = MFI_FRAME_DIR_READ;
6834	dcmd->timeout = 0;
6835	dcmd->pad_0 = 0;
6836	dcmd->data_xfer_len =
6837		cpu_to_le32(sizeof(struct MR_TARGET_PROPERTIES));
6838	dcmd->opcode = cpu_to_le32(MR_DCMD_DRV_GET_TARGET_PROP);
6839
6840	megasas_set_dma_settings(instance, dcmd, instance->tgt_prop_h,
6841				 sizeof(struct MR_TARGET_PROPERTIES));
6842
6843	if ((instance->adapter_type != MFI_SERIES) &&
6844	    !instance->mask_interrupts)
6845		ret = megasas_issue_blocked_cmd(instance,
6846						cmd, MFI_IO_TIMEOUT_SECS);
6847	else
6848		ret = megasas_issue_polled(instance, cmd);
6849
6850	switch (ret) {
6851	case DCMD_TIMEOUT:
6852		switch (dcmd_timeout_ocr_possible(instance)) {
6853		case INITIATE_OCR:
6854			cmd->flags |= DRV_DCMD_SKIP_REFIRE;
6855			mutex_unlock(&instance->reset_mutex);
6856			megasas_reset_fusion(instance->host,
6857					     MFI_IO_TIMEOUT_OCR);
6858			mutex_lock(&instance->reset_mutex);
6859			break;
6860		case KILL_ADAPTER:
6861			megaraid_sas_kill_hba(instance);
6862			break;
6863		case IGNORE_TIMEOUT:
6864			dev_info(&instance->pdev->dev,
6865				 "Ignore DCMD timeout: %s %d\n",
6866				 __func__, __LINE__);
6867			break;
6868		}
6869		break;
6870
6871	default:
6872		megasas_return_cmd(instance, cmd);
6873	}
6874	if (ret != DCMD_SUCCESS)
6875		dev_err(&instance->pdev->dev,
6876			"return from %s %d return value %d\n",
6877			__func__, __LINE__, ret);
6878
6879	return ret;
6880}
6881
6882/**
6883 * megasas_start_aen -	Subscribes to AEN during driver load time
6884 * @instance:		Adapter soft state
6885 */
6886static int megasas_start_aen(struct megasas_instance *instance)
6887{
6888	struct megasas_evt_log_info eli;
6889	union megasas_evt_class_locale class_locale;
6890
6891	/*
6892	 * Get the latest sequence number from FW
6893	 */
6894	memset(&eli, 0, sizeof(eli));
6895
6896	if (megasas_get_seq_num(instance, &eli))
6897		return -1;
6898
6899	/*
6900	 * Register AEN with FW for latest sequence number plus 1
6901	 */
6902	class_locale.members.reserved = 0;
6903	class_locale.members.locale = MR_EVT_LOCALE_ALL;
6904	class_locale.members.class = MR_EVT_CLASS_DEBUG;
6905
6906	return megasas_register_aen(instance,
6907			le32_to_cpu(eli.newest_seq_num) + 1,
6908			class_locale.word);
6909}
6910
6911/**
6912 * megasas_io_attach -	Attaches this driver to SCSI mid-layer
6913 * @instance:		Adapter soft state
6914 */
6915static int megasas_io_attach(struct megasas_instance *instance)
6916{
6917	struct Scsi_Host *host = instance->host;
6918
6919	/*
6920	 * Export parameters required by SCSI mid-layer
6921	 */
6922	host->unique_id = instance->unique_id;
6923	host->can_queue = instance->max_scsi_cmds;
6924	host->this_id = instance->init_id;
6925	host->sg_tablesize = instance->max_num_sge;
6926
6927	if (instance->fw_support_ieee)
6928		instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
6929
6930	/*
6931	 * Check if the module parameter value for max_sectors can be used
6932	 */
6933	if (max_sectors && max_sectors < instance->max_sectors_per_req)
6934		instance->max_sectors_per_req = max_sectors;
6935	else {
6936		if (max_sectors) {
6937			if (((instance->pdev->device ==
6938				PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
6939				(instance->pdev->device ==
6940				PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
6941				(max_sectors <= MEGASAS_MAX_SECTORS)) {
6942				instance->max_sectors_per_req = max_sectors;
6943			} else {
6944			dev_info(&instance->pdev->dev, "max_sectors should be > 0"
6945				"and <= %d (or < 1MB for GEN2 controller)\n",
6946				instance->max_sectors_per_req);
6947			}
6948		}
6949	}
6950
6951	host->max_sectors = instance->max_sectors_per_req;
6952	host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
6953	host->max_channel = MEGASAS_MAX_CHANNELS - 1;
6954	host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
6955	host->max_lun = MEGASAS_MAX_LUN;
6956	host->max_cmd_len = 16;
6957
6958	/* Use shared host tagset only for fusion adaptors
6959	 * if there are managed interrupts (smp affinity enabled case).
6960	 * Single msix_vectors in kdump, so shared host tag is also disabled.
6961	 */
6962
6963	host->host_tagset = 0;
6964	host->nr_hw_queues = 1;
6965
6966	if ((instance->adapter_type != MFI_SERIES) &&
6967		(instance->msix_vectors > instance->low_latency_index_start) &&
6968		host_tagset_enable &&
6969		instance->smp_affinity_enable) {
6970		host->host_tagset = 1;
6971		host->nr_hw_queues = instance->msix_vectors -
6972			instance->low_latency_index_start + instance->iopoll_q_count;
6973		if (instance->iopoll_q_count)
6974			host->nr_maps = 3;
6975	} else {
6976		instance->iopoll_q_count = 0;
6977	}
6978
6979	dev_info(&instance->pdev->dev,
6980		"Max firmware commands: %d shared with default "
6981		"hw_queues = %d poll_queues %d\n", instance->max_fw_cmds,
6982		host->nr_hw_queues - instance->iopoll_q_count,
6983		instance->iopoll_q_count);
6984	/*
6985	 * Notify the mid-layer about the new controller
6986	 */
6987	if (scsi_add_host(host, &instance->pdev->dev)) {
6988		dev_err(&instance->pdev->dev,
6989			"Failed to add host from %s %d\n",
6990			__func__, __LINE__);
6991		return -ENODEV;
6992	}
6993
6994	return 0;
6995}
6996
6997/**
6998 * megasas_set_dma_mask -	Set DMA mask for supported controllers
6999 *
7000 * @instance:		Adapter soft state
7001 * Description:
7002 *
7003 * For Ventura, driver/FW will operate in 63bit DMA addresses.
7004 *
7005 * For invader-
7006 *	By default, driver/FW will operate in 32bit DMA addresses
7007 *	for consistent DMA mapping but if 32 bit consistent
7008 *	DMA mask fails, driver will try with 63 bit consistent
7009 *	mask provided FW is true 63bit DMA capable
7010 *
7011 * For older controllers(Thunderbolt and MFI based adapters)-
7012 *	driver/FW will operate in 32 bit consistent DMA addresses.
7013 */
7014static int
7015megasas_set_dma_mask(struct megasas_instance *instance)
7016{
7017	u64 consistent_mask;
7018	struct pci_dev *pdev;
7019	u32 scratch_pad_1;
7020
7021	pdev = instance->pdev;
7022	consistent_mask = (instance->adapter_type >= VENTURA_SERIES) ?
7023				DMA_BIT_MASK(63) : DMA_BIT_MASK(32);
7024
7025	if (IS_DMA64) {
7026		if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(63)) &&
7027		    dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
7028			goto fail_set_dma_mask;
7029
7030		if ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) &&
7031		    (dma_set_coherent_mask(&pdev->dev, consistent_mask) &&
7032		     dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))) {
7033			/*
7034			 * If 32 bit DMA mask fails, then try for 64 bit mask
7035			 * for FW capable of handling 64 bit DMA.
7036			 */
7037			scratch_pad_1 = megasas_readl
7038				(instance, &instance->reg_set->outbound_scratch_pad_1);
7039
7040			if (!(scratch_pad_1 & MR_CAN_HANDLE_64_BIT_DMA_OFFSET))
7041				goto fail_set_dma_mask;
7042			else if (dma_set_mask_and_coherent(&pdev->dev,
7043							   DMA_BIT_MASK(63)))
7044				goto fail_set_dma_mask;
7045		}
7046	} else if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
7047		goto fail_set_dma_mask;
7048
7049	if (pdev->dev.coherent_dma_mask == DMA_BIT_MASK(32))
7050		instance->consistent_mask_64bit = false;
7051	else
7052		instance->consistent_mask_64bit = true;
7053
7054	dev_info(&pdev->dev, "%s bit DMA mask and %s bit consistent mask\n",
7055		 ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) ? "63" : "32"),
7056		 (instance->consistent_mask_64bit ? "63" : "32"));
7057
7058	return 0;
7059
7060fail_set_dma_mask:
7061	dev_err(&pdev->dev, "Failed to set DMA mask\n");
7062	return -1;
7063
7064}
7065
7066/*
7067 * megasas_set_adapter_type -	Set adapter type.
7068 *				Supported controllers can be divided in
7069 *				different categories-
7070 *					enum MR_ADAPTER_TYPE {
7071 *						MFI_SERIES = 1,
7072 *						THUNDERBOLT_SERIES = 2,
7073 *						INVADER_SERIES = 3,
7074 *						VENTURA_SERIES = 4,
7075 *						AERO_SERIES = 5,
7076 *					};
7077 * @instance:			Adapter soft state
7078 * return:			void
7079 */
7080static inline void megasas_set_adapter_type(struct megasas_instance *instance)
7081{
7082	if ((instance->pdev->vendor == PCI_VENDOR_ID_DELL) &&
7083	    (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5)) {
7084		instance->adapter_type = MFI_SERIES;
7085	} else {
7086		switch (instance->pdev->device) {
7087		case PCI_DEVICE_ID_LSI_AERO_10E1:
7088		case PCI_DEVICE_ID_LSI_AERO_10E2:
7089		case PCI_DEVICE_ID_LSI_AERO_10E5:
7090		case PCI_DEVICE_ID_LSI_AERO_10E6:
7091			instance->adapter_type = AERO_SERIES;
7092			break;
7093		case PCI_DEVICE_ID_LSI_VENTURA:
7094		case PCI_DEVICE_ID_LSI_CRUSADER:
7095		case PCI_DEVICE_ID_LSI_HARPOON:
7096		case PCI_DEVICE_ID_LSI_TOMCAT:
7097		case PCI_DEVICE_ID_LSI_VENTURA_4PORT:
7098		case PCI_DEVICE_ID_LSI_CRUSADER_4PORT:
7099			instance->adapter_type = VENTURA_SERIES;
7100			break;
7101		case PCI_DEVICE_ID_LSI_FUSION:
7102		case PCI_DEVICE_ID_LSI_PLASMA:
7103			instance->adapter_type = THUNDERBOLT_SERIES;
7104			break;
7105		case PCI_DEVICE_ID_LSI_INVADER:
7106		case PCI_DEVICE_ID_LSI_INTRUDER:
7107		case PCI_DEVICE_ID_LSI_INTRUDER_24:
7108		case PCI_DEVICE_ID_LSI_CUTLASS_52:
7109		case PCI_DEVICE_ID_LSI_CUTLASS_53:
7110		case PCI_DEVICE_ID_LSI_FURY:
7111			instance->adapter_type = INVADER_SERIES;
7112			break;
7113		default: /* For all other supported controllers */
7114			instance->adapter_type = MFI_SERIES;
7115			break;
7116		}
7117	}
7118}
7119
7120static inline int megasas_alloc_mfi_ctrl_mem(struct megasas_instance *instance)
7121{
7122	instance->producer = dma_alloc_coherent(&instance->pdev->dev,
7123			sizeof(u32), &instance->producer_h, GFP_KERNEL);
7124	instance->consumer = dma_alloc_coherent(&instance->pdev->dev,
7125			sizeof(u32), &instance->consumer_h, GFP_KERNEL);
7126
7127	if (!instance->producer || !instance->consumer) {
7128		dev_err(&instance->pdev->dev,
7129			"Failed to allocate memory for producer, consumer\n");
7130		return -1;
7131	}
7132
7133	*instance->producer = 0;
7134	*instance->consumer = 0;
7135	return 0;
7136}
7137
7138/**
7139 * megasas_alloc_ctrl_mem -	Allocate per controller memory for core data
7140 *				structures which are not common across MFI
7141 *				adapters and fusion adapters.
7142 *				For MFI based adapters, allocate producer and
7143 *				consumer buffers. For fusion adapters, allocate
7144 *				memory for fusion context.
7145 * @instance:			Adapter soft state
7146 * return:			0 for SUCCESS
7147 */
7148static int megasas_alloc_ctrl_mem(struct megasas_instance *instance)
7149{
7150	instance->reply_map = kcalloc(nr_cpu_ids, sizeof(unsigned int),
7151				      GFP_KERNEL);
7152	if (!instance->reply_map)
7153		return -ENOMEM;
7154
7155	switch (instance->adapter_type) {
7156	case MFI_SERIES:
7157		if (megasas_alloc_mfi_ctrl_mem(instance))
7158			return -ENOMEM;
7159		break;
7160	case AERO_SERIES:
7161	case VENTURA_SERIES:
7162	case THUNDERBOLT_SERIES:
7163	case INVADER_SERIES:
7164		if (megasas_alloc_fusion_context(instance))
7165			return -ENOMEM;
7166		break;
7167	}
7168
7169	return 0;
7170}
7171
7172/*
7173 * megasas_free_ctrl_mem -	Free fusion context for fusion adapters and
7174 *				producer, consumer buffers for MFI adapters
7175 *
7176 * @instance -			Adapter soft instance
7177 *
7178 */
7179static inline void megasas_free_ctrl_mem(struct megasas_instance *instance)
7180{
7181	kfree(instance->reply_map);
7182	if (instance->adapter_type == MFI_SERIES) {
7183		if (instance->producer)
7184			dma_free_coherent(&instance->pdev->dev, sizeof(u32),
7185					    instance->producer,
7186					    instance->producer_h);
7187		if (instance->consumer)
7188			dma_free_coherent(&instance->pdev->dev, sizeof(u32),
7189					    instance->consumer,
7190					    instance->consumer_h);
7191	} else {
7192		megasas_free_fusion_context(instance);
7193	}
7194}
7195
7196/**
7197 * megasas_alloc_ctrl_dma_buffers -	Allocate consistent DMA buffers during
7198 *					driver load time
7199 *
7200 * @instance:				Adapter soft instance
7201 *
7202 * @return:				O for SUCCESS
7203 */
7204static inline
7205int megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance)
7206{
7207	struct pci_dev *pdev = instance->pdev;
7208	struct fusion_context *fusion = instance->ctrl_context;
7209
7210	instance->evt_detail = dma_alloc_coherent(&pdev->dev,
7211			sizeof(struct megasas_evt_detail),
7212			&instance->evt_detail_h, GFP_KERNEL);
7213
7214	if (!instance->evt_detail) {
7215		dev_err(&instance->pdev->dev,
7216			"Failed to allocate event detail buffer\n");
7217		return -ENOMEM;
7218	}
7219
7220	if (fusion) {
7221		fusion->ioc_init_request =
7222			dma_alloc_coherent(&pdev->dev,
7223					   sizeof(struct MPI2_IOC_INIT_REQUEST),
7224					   &fusion->ioc_init_request_phys,
7225					   GFP_KERNEL);
7226
7227		if (!fusion->ioc_init_request) {
7228			dev_err(&pdev->dev,
7229				"Failed to allocate ioc init request\n");
7230			return -ENOMEM;
7231		}
7232
7233		instance->snapdump_prop = dma_alloc_coherent(&pdev->dev,
7234				sizeof(struct MR_SNAPDUMP_PROPERTIES),
7235				&instance->snapdump_prop_h, GFP_KERNEL);
7236
7237		if (!instance->snapdump_prop)
7238			dev_err(&pdev->dev,
7239				"Failed to allocate snapdump properties buffer\n");
7240
7241		instance->host_device_list_buf = dma_alloc_coherent(&pdev->dev,
7242							HOST_DEVICE_LIST_SZ,
7243							&instance->host_device_list_buf_h,
7244							GFP_KERNEL);
7245
7246		if (!instance->host_device_list_buf) {
7247			dev_err(&pdev->dev,
7248				"Failed to allocate targetid list buffer\n");
7249			return -ENOMEM;
7250		}
7251
7252	}
7253
7254	instance->pd_list_buf =
7255		dma_alloc_coherent(&pdev->dev,
7256				     MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
7257				     &instance->pd_list_buf_h, GFP_KERNEL);
7258
7259	if (!instance->pd_list_buf) {
7260		dev_err(&pdev->dev, "Failed to allocate PD list buffer\n");
7261		return -ENOMEM;
7262	}
7263
7264	instance->ctrl_info_buf =
7265		dma_alloc_coherent(&pdev->dev,
7266				     sizeof(struct megasas_ctrl_info),
7267				     &instance->ctrl_info_buf_h, GFP_KERNEL);
7268
7269	if (!instance->ctrl_info_buf) {
7270		dev_err(&pdev->dev,
7271			"Failed to allocate controller info buffer\n");
7272		return -ENOMEM;
7273	}
7274
7275	instance->ld_list_buf =
7276		dma_alloc_coherent(&pdev->dev,
7277				     sizeof(struct MR_LD_LIST),
7278				     &instance->ld_list_buf_h, GFP_KERNEL);
7279
7280	if (!instance->ld_list_buf) {
7281		dev_err(&pdev->dev, "Failed to allocate LD list buffer\n");
7282		return -ENOMEM;
7283	}
7284
7285	instance->ld_targetid_list_buf =
7286		dma_alloc_coherent(&pdev->dev,
7287				sizeof(struct MR_LD_TARGETID_LIST),
7288				&instance->ld_targetid_list_buf_h, GFP_KERNEL);
7289
7290	if (!instance->ld_targetid_list_buf) {
7291		dev_err(&pdev->dev,
7292			"Failed to allocate LD targetid list buffer\n");
7293		return -ENOMEM;
7294	}
7295
7296	if (!reset_devices) {
7297		instance->system_info_buf =
7298			dma_alloc_coherent(&pdev->dev,
7299					sizeof(struct MR_DRV_SYSTEM_INFO),
7300					&instance->system_info_h, GFP_KERNEL);
7301		instance->pd_info =
7302			dma_alloc_coherent(&pdev->dev,
7303					sizeof(struct MR_PD_INFO),
7304					&instance->pd_info_h, GFP_KERNEL);
7305		instance->tgt_prop =
7306			dma_alloc_coherent(&pdev->dev,
7307					sizeof(struct MR_TARGET_PROPERTIES),
7308					&instance->tgt_prop_h, GFP_KERNEL);
7309		instance->crash_dump_buf =
7310			dma_alloc_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
7311					&instance->crash_dump_h, GFP_KERNEL);
7312
7313		if (!instance->system_info_buf)
7314			dev_err(&instance->pdev->dev,
7315				"Failed to allocate system info buffer\n");
7316
7317		if (!instance->pd_info)
7318			dev_err(&instance->pdev->dev,
7319				"Failed to allocate pd_info buffer\n");
7320
7321		if (!instance->tgt_prop)
7322			dev_err(&instance->pdev->dev,
7323				"Failed to allocate tgt_prop buffer\n");
7324
7325		if (!instance->crash_dump_buf)
7326			dev_err(&instance->pdev->dev,
7327				"Failed to allocate crash dump buffer\n");
7328	}
7329
7330	return 0;
7331}
7332
7333/*
7334 * megasas_free_ctrl_dma_buffers -	Free consistent DMA buffers allocated
7335 *					during driver load time
7336 *
7337 * @instance-				Adapter soft instance
7338 *
7339 */
7340static inline
7341void megasas_free_ctrl_dma_buffers(struct megasas_instance *instance)
7342{
7343	struct pci_dev *pdev = instance->pdev;
7344	struct fusion_context *fusion = instance->ctrl_context;
7345
7346	if (instance->evt_detail)
7347		dma_free_coherent(&pdev->dev, sizeof(struct megasas_evt_detail),
7348				    instance->evt_detail,
7349				    instance->evt_detail_h);
7350
7351	if (fusion && fusion->ioc_init_request)
7352		dma_free_coherent(&pdev->dev,
7353				  sizeof(struct MPI2_IOC_INIT_REQUEST),
7354				  fusion->ioc_init_request,
7355				  fusion->ioc_init_request_phys);
7356
7357	if (instance->pd_list_buf)
7358		dma_free_coherent(&pdev->dev,
7359				    MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
7360				    instance->pd_list_buf,
7361				    instance->pd_list_buf_h);
7362
7363	if (instance->ld_list_buf)
7364		dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_LIST),
7365				    instance->ld_list_buf,
7366				    instance->ld_list_buf_h);
7367
7368	if (instance->ld_targetid_list_buf)
7369		dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_TARGETID_LIST),
7370				    instance->ld_targetid_list_buf,
7371				    instance->ld_targetid_list_buf_h);
7372
7373	if (instance->ctrl_info_buf)
7374		dma_free_coherent(&pdev->dev, sizeof(struct megasas_ctrl_info),
7375				    instance->ctrl_info_buf,
7376				    instance->ctrl_info_buf_h);
7377
7378	if (instance->system_info_buf)
7379		dma_free_coherent(&pdev->dev, sizeof(struct MR_DRV_SYSTEM_INFO),
7380				    instance->system_info_buf,
7381				    instance->system_info_h);
7382
7383	if (instance->pd_info)
7384		dma_free_coherent(&pdev->dev, sizeof(struct MR_PD_INFO),
7385				    instance->pd_info, instance->pd_info_h);
7386
7387	if (instance->tgt_prop)
7388		dma_free_coherent(&pdev->dev, sizeof(struct MR_TARGET_PROPERTIES),
7389				    instance->tgt_prop, instance->tgt_prop_h);
7390
7391	if (instance->crash_dump_buf)
7392		dma_free_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
7393				    instance->crash_dump_buf,
7394				    instance->crash_dump_h);
7395
7396	if (instance->snapdump_prop)
7397		dma_free_coherent(&pdev->dev,
7398				  sizeof(struct MR_SNAPDUMP_PROPERTIES),
7399				  instance->snapdump_prop,
7400				  instance->snapdump_prop_h);
7401
7402	if (instance->host_device_list_buf)
7403		dma_free_coherent(&pdev->dev,
7404				  HOST_DEVICE_LIST_SZ,
7405				  instance->host_device_list_buf,
7406				  instance->host_device_list_buf_h);
7407
7408}
7409
7410/*
7411 * megasas_init_ctrl_params -		Initialize controller's instance
7412 *					parameters before FW init
7413 * @instance -				Adapter soft instance
7414 * @return -				void
7415 */
7416static inline void megasas_init_ctrl_params(struct megasas_instance *instance)
7417{
7418	instance->fw_crash_state = UNAVAILABLE;
7419
7420	megasas_poll_wait_aen = 0;
7421	instance->issuepend_done = 1;
7422	atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
7423
7424	/*
7425	 * Initialize locks and queues
7426	 */
7427	INIT_LIST_HEAD(&instance->cmd_pool);
7428	INIT_LIST_HEAD(&instance->internal_reset_pending_q);
7429
7430	atomic_set(&instance->fw_outstanding, 0);
7431	atomic64_set(&instance->total_io_count, 0);
7432
7433	init_waitqueue_head(&instance->int_cmd_wait_q);
7434	init_waitqueue_head(&instance->abort_cmd_wait_q);
7435
7436	mutex_init(&instance->crashdump_lock);
7437	spin_lock_init(&instance->mfi_pool_lock);
7438	spin_lock_init(&instance->hba_lock);
7439	spin_lock_init(&instance->stream_lock);
7440	spin_lock_init(&instance->completion_lock);
7441
7442	mutex_init(&instance->reset_mutex);
7443
7444	if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
7445	    (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY))
7446		instance->flag_ieee = 1;
7447
7448	instance->flag = 0;
7449	instance->unload = 1;
7450	instance->last_time = 0;
7451	instance->disableOnlineCtrlReset = 1;
7452	instance->UnevenSpanSupport = 0;
7453	instance->smp_affinity_enable = smp_affinity_enable ? true : false;
7454	instance->msix_load_balance = false;
7455
7456	if (instance->adapter_type != MFI_SERIES)
7457		INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
7458	else
7459		INIT_WORK(&instance->work_init, process_fw_state_change_wq);
7460}
7461
7462/**
7463 * megasas_probe_one -	PCI hotplug entry point
7464 * @pdev:		PCI device structure
7465 * @id:			PCI ids of supported hotplugged adapter
7466 */
7467static int megasas_probe_one(struct pci_dev *pdev,
7468			     const struct pci_device_id *id)
7469{
7470	int rval, pos;
7471	struct Scsi_Host *host;
7472	struct megasas_instance *instance;
7473	u16 control = 0;
7474
7475	switch (pdev->device) {
7476	case PCI_DEVICE_ID_LSI_AERO_10E0:
7477	case PCI_DEVICE_ID_LSI_AERO_10E3:
7478	case PCI_DEVICE_ID_LSI_AERO_10E4:
7479	case PCI_DEVICE_ID_LSI_AERO_10E7:
7480		dev_err(&pdev->dev, "Adapter is in non secure mode\n");
7481		return 1;
7482	case PCI_DEVICE_ID_LSI_AERO_10E1:
7483	case PCI_DEVICE_ID_LSI_AERO_10E5:
7484		dev_info(&pdev->dev, "Adapter is in configurable secure mode\n");
7485		break;
7486	}
7487
7488	/* Reset MSI-X in the kdump kernel */
7489	if (reset_devices) {
7490		pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
7491		if (pos) {
7492			pci_read_config_word(pdev, pos + PCI_MSIX_FLAGS,
7493					     &control);
7494			if (control & PCI_MSIX_FLAGS_ENABLE) {
7495				dev_info(&pdev->dev, "resetting MSI-X\n");
7496				pci_write_config_word(pdev,
7497						      pos + PCI_MSIX_FLAGS,
7498						      control &
7499						      ~PCI_MSIX_FLAGS_ENABLE);
7500			}
7501		}
7502	}
7503
7504	/*
7505	 * PCI prepping: enable device set bus mastering and dma mask
7506	 */
7507	rval = pci_enable_device_mem(pdev);
7508
7509	if (rval) {
7510		return rval;
7511	}
7512
7513	pci_set_master(pdev);
7514
7515	host = scsi_host_alloc(&megasas_template,
7516			       sizeof(struct megasas_instance));
7517
7518	if (!host) {
7519		dev_printk(KERN_DEBUG, &pdev->dev, "scsi_host_alloc failed\n");
7520		goto fail_alloc_instance;
7521	}
7522
7523	instance = (struct megasas_instance *)host->hostdata;
7524	memset(instance, 0, sizeof(*instance));
7525	atomic_set(&instance->fw_reset_no_pci_access, 0);
7526
7527	/*
7528	 * Initialize PCI related and misc parameters
7529	 */
7530	instance->pdev = pdev;
7531	instance->host = host;
7532	instance->unique_id = pci_dev_id(pdev);
7533	instance->init_id = MEGASAS_DEFAULT_INIT_ID;
7534
7535	megasas_set_adapter_type(instance);
7536
7537	/*
7538	 * Initialize MFI Firmware
7539	 */
7540	if (megasas_init_fw(instance))
7541		goto fail_init_mfi;
7542
7543	if (instance->requestorId) {
7544		if (instance->PlasmaFW111) {
7545			instance->vf_affiliation_111 =
7546				dma_alloc_coherent(&pdev->dev,
7547					sizeof(struct MR_LD_VF_AFFILIATION_111),
7548					&instance->vf_affiliation_111_h,
7549					GFP_KERNEL);
7550			if (!instance->vf_affiliation_111)
7551				dev_warn(&pdev->dev, "Can't allocate "
7552				       "memory for VF affiliation buffer\n");
7553		} else {
7554			instance->vf_affiliation =
7555				dma_alloc_coherent(&pdev->dev,
7556					(MAX_LOGICAL_DRIVES + 1) *
7557					sizeof(struct MR_LD_VF_AFFILIATION),
7558					&instance->vf_affiliation_h,
7559					GFP_KERNEL);
7560			if (!instance->vf_affiliation)
7561				dev_warn(&pdev->dev, "Can't allocate "
7562				       "memory for VF affiliation buffer\n");
7563		}
7564	}
7565
7566	/*
7567	 * Store instance in PCI softstate
7568	 */
7569	pci_set_drvdata(pdev, instance);
7570
7571	/*
7572	 * Add this controller to megasas_mgmt_info structure so that it
7573	 * can be exported to management applications
7574	 */
7575	megasas_mgmt_info.count++;
7576	megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
7577	megasas_mgmt_info.max_index++;
7578
7579	/*
7580	 * Register with SCSI mid-layer
7581	 */
7582	if (megasas_io_attach(instance))
7583		goto fail_io_attach;
7584
7585	instance->unload = 0;
7586	/*
7587	 * Trigger SCSI to scan our drives
7588	 */
7589	if (!instance->enable_fw_dev_list ||
7590	    (instance->host_device_list_buf->count > 0))
7591		scsi_scan_host(host);
7592
7593	/*
7594	 * Initiate AEN (Asynchronous Event Notification)
7595	 */
7596	if (megasas_start_aen(instance)) {
7597		dev_printk(KERN_DEBUG, &pdev->dev, "start aen failed\n");
7598		goto fail_start_aen;
7599	}
7600
7601	megasas_setup_debugfs(instance);
7602
7603	/* Get current SR-IOV LD/VF affiliation */
7604	if (instance->requestorId)
7605		megasas_get_ld_vf_affiliation(instance, 1);
7606
7607	return 0;
7608
7609fail_start_aen:
7610	instance->unload = 1;
7611	scsi_remove_host(instance->host);
7612fail_io_attach:
7613	megasas_mgmt_info.count--;
7614	megasas_mgmt_info.max_index--;
7615	megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
7616
7617	if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7618		timer_delete_sync(&instance->sriov_heartbeat_timer);
7619
7620	instance->instancet->disable_intr(instance);
7621	megasas_destroy_irqs(instance);
7622
7623	if (instance->adapter_type != MFI_SERIES)
7624		megasas_release_fusion(instance);
7625	else
7626		megasas_release_mfi(instance);
7627
7628	if (instance->msix_vectors)
7629		pci_free_irq_vectors(instance->pdev);
7630	instance->msix_vectors = 0;
7631
7632	if (instance->fw_crash_state != UNAVAILABLE)
7633		megasas_free_host_crash_buffer(instance);
7634
7635	if (instance->adapter_type != MFI_SERIES)
7636		megasas_fusion_stop_watchdog(instance);
7637fail_init_mfi:
7638	scsi_host_put(host);
7639fail_alloc_instance:
7640	pci_disable_device(pdev);
7641
7642	return -ENODEV;
7643}
7644
7645/**
7646 * megasas_flush_cache -	Requests FW to flush all its caches
7647 * @instance:			Adapter soft state
7648 */
7649static void megasas_flush_cache(struct megasas_instance *instance)
7650{
7651	struct megasas_cmd *cmd;
7652	struct megasas_dcmd_frame *dcmd;
7653
7654	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7655		return;
7656
7657	cmd = megasas_get_cmd(instance);
7658
7659	if (!cmd)
7660		return;
7661
7662	dcmd = &cmd->frame->dcmd;
7663
7664	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7665
7666	dcmd->cmd = MFI_CMD_DCMD;
7667	dcmd->cmd_status = 0x0;
7668	dcmd->sge_count = 0;
7669	dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7670	dcmd->timeout = 0;
7671	dcmd->pad_0 = 0;
7672	dcmd->data_xfer_len = 0;
7673	dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_CACHE_FLUSH);
7674	dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
7675
7676	if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7677			!= DCMD_SUCCESS) {
7678		dev_err(&instance->pdev->dev,
7679			"return from %s %d\n", __func__, __LINE__);
7680		return;
7681	}
7682
7683	megasas_return_cmd(instance, cmd);
7684}
7685
7686/**
7687 * megasas_shutdown_controller -	Instructs FW to shutdown the controller
7688 * @instance:				Adapter soft state
7689 * @opcode:				Shutdown/Hibernate
7690 */
7691static void megasas_shutdown_controller(struct megasas_instance *instance,
7692					u32 opcode)
7693{
7694	struct megasas_cmd *cmd;
7695	struct megasas_dcmd_frame *dcmd;
7696
7697	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7698		return;
7699
7700	cmd = megasas_get_cmd(instance);
7701
7702	if (!cmd)
7703		return;
7704
7705	if (instance->aen_cmd)
7706		megasas_issue_blocked_abort_cmd(instance,
7707			instance->aen_cmd, MFI_IO_TIMEOUT_SECS);
7708	if (instance->map_update_cmd)
7709		megasas_issue_blocked_abort_cmd(instance,
7710			instance->map_update_cmd, MFI_IO_TIMEOUT_SECS);
7711	if (instance->jbod_seq_cmd)
7712		megasas_issue_blocked_abort_cmd(instance,
7713			instance->jbod_seq_cmd, MFI_IO_TIMEOUT_SECS);
7714
7715	dcmd = &cmd->frame->dcmd;
7716
7717	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7718
7719	dcmd->cmd = MFI_CMD_DCMD;
7720	dcmd->cmd_status = 0x0;
7721	dcmd->sge_count = 0;
7722	dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7723	dcmd->timeout = 0;
7724	dcmd->pad_0 = 0;
7725	dcmd->data_xfer_len = 0;
7726	dcmd->opcode = cpu_to_le32(opcode);
7727
7728	if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7729			!= DCMD_SUCCESS) {
7730		dev_err(&instance->pdev->dev,
7731			"return from %s %d\n", __func__, __LINE__);
7732		return;
7733	}
7734
7735	megasas_return_cmd(instance, cmd);
7736}
7737
7738/**
7739 * megasas_suspend -	driver suspend entry point
7740 * @dev:		Device structure
7741 */
7742static int __maybe_unused
7743megasas_suspend(struct device *dev)
7744{
7745	struct megasas_instance *instance;
7746
7747	instance = dev_get_drvdata(dev);
7748
7749	if (!instance)
7750		return 0;
7751
7752	instance->unload = 1;
7753
7754	dev_info(dev, "%s is called\n", __func__);
7755
7756	/* Shutdown SR-IOV heartbeat timer */
7757	if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7758		timer_delete_sync(&instance->sriov_heartbeat_timer);
7759
7760	/* Stop the FW fault detection watchdog */
7761	if (instance->adapter_type != MFI_SERIES)
7762		megasas_fusion_stop_watchdog(instance);
7763
7764	megasas_flush_cache(instance);
7765	megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
7766
7767	/* cancel the delayed work if this work still in queue */
7768	if (instance->ev != NULL) {
7769		struct megasas_aen_event *ev = instance->ev;
7770		cancel_delayed_work_sync(&ev->hotplug_work);
7771		instance->ev = NULL;
7772	}
7773
7774	tasklet_kill(&instance->isr_tasklet);
7775
7776	pci_set_drvdata(instance->pdev, instance);
7777	instance->instancet->disable_intr(instance);
7778
7779	megasas_destroy_irqs(instance);
7780
7781	if (instance->msix_vectors)
7782		pci_free_irq_vectors(instance->pdev);
7783
7784	return 0;
7785}
7786
7787/**
7788 * megasas_resume-      driver resume entry point
7789 * @dev:		Device structure
7790 */
7791static int __maybe_unused
7792megasas_resume(struct device *dev)
7793{
7794	int rval;
7795	struct Scsi_Host *host;
7796	struct megasas_instance *instance;
7797	u32 status_reg;
7798
7799	instance = dev_get_drvdata(dev);
7800
7801	if (!instance)
7802		return 0;
7803
7804	host = instance->host;
7805
7806	dev_info(dev, "%s is called\n", __func__);
7807
7808	/*
7809	 * We expect the FW state to be READY
7810	 */
7811
7812	if (megasas_transition_to_ready(instance, 0)) {
7813		dev_info(&instance->pdev->dev,
7814			 "Failed to transition controller to ready from %s!\n",
7815			 __func__);
7816		if (instance->adapter_type != MFI_SERIES) {
7817			status_reg =
7818				instance->instancet->read_fw_status_reg(instance);
7819			if (!(status_reg & MFI_RESET_ADAPTER) ||
7820				((megasas_adp_reset_wait_for_ready
7821				(instance, true, 0)) == FAILED))
7822				goto fail_ready_state;
7823		} else {
7824			atomic_set(&instance->fw_reset_no_pci_access, 1);
7825			instance->instancet->adp_reset
7826				(instance, instance->reg_set);
7827			atomic_set(&instance->fw_reset_no_pci_access, 0);
7828
7829			/* waiting for about 30 seconds before retry */
7830			ssleep(30);
7831
7832			if (megasas_transition_to_ready(instance, 0))
7833				goto fail_ready_state;
7834		}
7835
7836		dev_info(&instance->pdev->dev,
7837			 "FW restarted successfully from %s!\n",
7838			 __func__);
7839	}
7840	if (megasas_set_dma_mask(instance))
7841		goto fail_set_dma_mask;
7842
7843	/*
7844	 * Initialize MFI Firmware
7845	 */
7846
7847	atomic_set(&instance->fw_outstanding, 0);
7848	atomic_set(&instance->ldio_outstanding, 0);
7849
7850	/* Now re-enable MSI-X */
7851	if (instance->msix_vectors)
7852		megasas_alloc_irq_vectors(instance);
7853
7854	if (!instance->msix_vectors) {
7855		rval = pci_alloc_irq_vectors(instance->pdev, 1, 1,
7856					     PCI_IRQ_INTX);
7857		if (rval < 0)
7858			goto fail_reenable_msix;
7859	}
7860
7861	megasas_setup_reply_map(instance);
7862
7863	if (instance->adapter_type != MFI_SERIES) {
7864		megasas_reset_reply_desc(instance);
7865		if (megasas_ioc_init_fusion(instance)) {
7866			megasas_free_cmds(instance);
7867			megasas_free_cmds_fusion(instance);
7868			goto fail_init_mfi;
7869		}
7870		if (!megasas_get_map_info(instance))
7871			megasas_sync_map_info(instance);
7872	} else {
7873		*instance->producer = 0;
7874		*instance->consumer = 0;
7875		if (megasas_issue_init_mfi(instance))
7876			goto fail_init_mfi;
7877	}
7878
7879	if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS)
7880		goto fail_init_mfi;
7881
7882	tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
7883		     (unsigned long)instance);
7884
7885	if (instance->msix_vectors ?
7886			megasas_setup_irqs_msix(instance, 0) :
7887			megasas_setup_irqs_ioapic(instance))
7888		goto fail_init_mfi;
7889
7890	if (instance->adapter_type != MFI_SERIES)
7891		megasas_setup_irq_poll(instance);
7892
7893	/* Re-launch SR-IOV heartbeat timer */
7894	if (instance->requestorId) {
7895		if (!megasas_sriov_start_heartbeat(instance, 0))
7896			megasas_start_timer(instance);
7897		else {
7898			instance->skip_heartbeat_timer_del = 1;
7899			goto fail_init_mfi;
7900		}
7901	}
7902
7903	instance->instancet->enable_intr(instance);
7904	megasas_setup_jbod_map(instance);
7905	instance->unload = 0;
7906
7907	/*
7908	 * Initiate AEN (Asynchronous Event Notification)
7909	 */
7910	if (megasas_start_aen(instance))
7911		dev_err(&instance->pdev->dev, "Start AEN failed\n");
7912
7913	/* Re-launch FW fault watchdog */
7914	if (instance->adapter_type != MFI_SERIES)
7915		if (megasas_fusion_start_watchdog(instance) != SUCCESS)
7916			goto fail_start_watchdog;
7917
7918	return 0;
7919
7920fail_start_watchdog:
7921	if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7922		timer_delete_sync(&instance->sriov_heartbeat_timer);
7923fail_init_mfi:
7924	megasas_free_ctrl_dma_buffers(instance);
7925	megasas_free_ctrl_mem(instance);
7926	scsi_host_put(host);
7927
7928fail_reenable_msix:
7929fail_set_dma_mask:
7930fail_ready_state:
7931
7932	return -ENODEV;
7933}
7934
7935static inline int
7936megasas_wait_for_adapter_operational(struct megasas_instance *instance)
7937{
7938	int wait_time = MEGASAS_RESET_WAIT_TIME * 2;
7939	int i;
7940	u8 adp_state;
7941
7942	for (i = 0; i < wait_time; i++) {
7943		adp_state = atomic_read(&instance->adprecovery);
7944		if ((adp_state == MEGASAS_HBA_OPERATIONAL) ||
7945		    (adp_state == MEGASAS_HW_CRITICAL_ERROR))
7946			break;
7947
7948		if (!(i % MEGASAS_RESET_NOTICE_INTERVAL))
7949			dev_notice(&instance->pdev->dev, "waiting for controller reset to finish\n");
7950
7951		msleep(1000);
7952	}
7953
7954	if (adp_state != MEGASAS_HBA_OPERATIONAL) {
7955		dev_info(&instance->pdev->dev,
7956			 "%s HBA failed to become operational, adp_state %d\n",
7957			 __func__, adp_state);
7958		return 1;
7959	}
7960
7961	return 0;
7962}
7963
7964/**
7965 * megasas_detach_one -	PCI hot"un"plug entry point
7966 * @pdev:		PCI device structure
7967 */
7968static void megasas_detach_one(struct pci_dev *pdev)
7969{
7970	int i;
7971	struct Scsi_Host *host;
7972	struct megasas_instance *instance;
7973	struct fusion_context *fusion;
7974	size_t pd_seq_map_sz;
7975
7976	instance = pci_get_drvdata(pdev);
7977
7978	if (!instance)
7979		return;
7980
7981	host = instance->host;
7982	fusion = instance->ctrl_context;
7983
7984	/* Shutdown SR-IOV heartbeat timer */
7985	if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7986		timer_delete_sync(&instance->sriov_heartbeat_timer);
7987
7988	/* Stop the FW fault detection watchdog */
7989	if (instance->adapter_type != MFI_SERIES)
7990		megasas_fusion_stop_watchdog(instance);
7991
7992	if (instance->fw_crash_state != UNAVAILABLE)
7993		megasas_free_host_crash_buffer(instance);
7994	scsi_remove_host(instance->host);
7995	instance->unload = 1;
7996
7997	if (megasas_wait_for_adapter_operational(instance))
7998		goto skip_firing_dcmds;
7999
8000	megasas_flush_cache(instance);
8001	megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
8002
8003skip_firing_dcmds:
8004	/* cancel the delayed work if this work still in queue*/
8005	if (instance->ev != NULL) {
8006		struct megasas_aen_event *ev = instance->ev;
8007		cancel_delayed_work_sync(&ev->hotplug_work);
8008		instance->ev = NULL;
8009	}
8010
8011	/* cancel all wait events */
8012	wake_up_all(&instance->int_cmd_wait_q);
8013
8014	tasklet_kill(&instance->isr_tasklet);
8015
8016	/*
8017	 * Take the instance off the instance array. Note that we will not
8018	 * decrement the max_index. We let this array be sparse array
8019	 */
8020	for (i = 0; i < megasas_mgmt_info.max_index; i++) {
8021		if (megasas_mgmt_info.instance[i] == instance) {
8022			megasas_mgmt_info.count--;
8023			megasas_mgmt_info.instance[i] = NULL;
8024
8025			break;
8026		}
8027	}
8028
8029	instance->instancet->disable_intr(instance);
8030
8031	megasas_destroy_irqs(instance);
8032
8033	if (instance->msix_vectors)
8034		pci_free_irq_vectors(instance->pdev);
8035
8036	if (instance->adapter_type >= VENTURA_SERIES) {
8037		for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i)
8038			kfree(fusion->stream_detect_by_ld[i]);
8039		kfree(fusion->stream_detect_by_ld);
8040		fusion->stream_detect_by_ld = NULL;
8041	}
8042
8043
8044	if (instance->adapter_type != MFI_SERIES) {
8045		megasas_release_fusion(instance);
8046		pd_seq_map_sz =
8047			struct_size_t(struct MR_PD_CFG_SEQ_NUM_SYNC,
8048				      seq, MAX_PHYSICAL_DEVICES);
8049		for (i = 0; i < 2 ; i++) {
8050			if (fusion->ld_map[i])
8051				dma_free_coherent(&instance->pdev->dev,
8052						  fusion->max_map_sz,
8053						  fusion->ld_map[i],
8054						  fusion->ld_map_phys[i]);
8055			if (fusion->ld_drv_map[i]) {
8056				if (is_vmalloc_addr(fusion->ld_drv_map[i]))
8057					vfree(fusion->ld_drv_map[i]);
8058				else
8059					free_pages((ulong)fusion->ld_drv_map[i],
8060						   fusion->drv_map_pages);
8061			}
8062
8063			if (fusion->pd_seq_sync[i])
8064				dma_free_coherent(&instance->pdev->dev,
8065					pd_seq_map_sz,
8066					fusion->pd_seq_sync[i],
8067					fusion->pd_seq_phys[i]);
8068		}
8069	} else {
8070		megasas_release_mfi(instance);
8071	}
8072
8073	if (instance->vf_affiliation)
8074		dma_free_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) *
8075				    sizeof(struct MR_LD_VF_AFFILIATION),
8076				    instance->vf_affiliation,
8077				    instance->vf_affiliation_h);
8078
8079	if (instance->vf_affiliation_111)
8080		dma_free_coherent(&pdev->dev,
8081				    sizeof(struct MR_LD_VF_AFFILIATION_111),
8082				    instance->vf_affiliation_111,
8083				    instance->vf_affiliation_111_h);
8084
8085	if (instance->hb_host_mem)
8086		dma_free_coherent(&pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM),
8087				    instance->hb_host_mem,
8088				    instance->hb_host_mem_h);
8089
8090	megasas_free_ctrl_dma_buffers(instance);
8091
8092	megasas_free_ctrl_mem(instance);
8093
8094	megasas_destroy_debugfs(instance);
8095
8096	scsi_host_put(host);
8097
8098	pci_disable_device(pdev);
8099}
8100
8101/**
8102 * megasas_shutdown -	Shutdown entry point
8103 * @pdev:		PCI device structure
8104 */
8105static void megasas_shutdown(struct pci_dev *pdev)
8106{
8107	struct megasas_instance *instance = pci_get_drvdata(pdev);
8108
8109	if (!instance)
8110		return;
8111
8112	instance->unload = 1;
8113
8114	if (megasas_wait_for_adapter_operational(instance))
8115		goto skip_firing_dcmds;
8116
8117	megasas_flush_cache(instance);
8118	megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
8119
8120skip_firing_dcmds:
8121	instance->instancet->disable_intr(instance);
8122	megasas_destroy_irqs(instance);
8123
8124	if (instance->msix_vectors)
8125		pci_free_irq_vectors(instance->pdev);
8126}
8127
8128/*
8129 * megasas_mgmt_open -	char node "open" entry point
8130 * @inode:	char node inode
8131 * @filep:	char node file
8132 */
8133static int megasas_mgmt_open(struct inode *inode, struct file *filep)
8134{
8135	/*
8136	 * Allow only those users with admin rights
8137	 */
8138	if (!capable(CAP_SYS_ADMIN))
8139		return -EACCES;
8140
8141	return 0;
8142}
8143
8144/*
8145 * megasas_mgmt_fasync -	Async notifier registration from applications
8146 * @fd:		char node file descriptor number
8147 * @filep:	char node file
8148 * @mode:	notifier on/off
8149 *
8150 * This function adds the calling process to a driver global queue. When an
8151 * event occurs, SIGIO will be sent to all processes in this queue.
8152 */
8153static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
8154{
8155	int rc;
8156
8157	mutex_lock(&megasas_async_queue_mutex);
8158
8159	rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
8160
8161	mutex_unlock(&megasas_async_queue_mutex);
8162
8163	if (rc >= 0) {
8164		/* For sanity check when we get ioctl */
8165		filep->private_data = filep;
8166		return 0;
8167	}
8168
8169	printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
8170
8171	return rc;
8172}
8173
8174/*
8175 * megasas_mgmt_poll -  char node "poll" entry point
8176 * @filep:	char node file
8177 * @wait:	Events to poll for
8178 */
8179static __poll_t megasas_mgmt_poll(struct file *file, poll_table *wait)
8180{
8181	__poll_t mask;
8182	unsigned long flags;
8183
8184	poll_wait(file, &megasas_poll_wait, wait);
8185	spin_lock_irqsave(&poll_aen_lock, flags);
8186	if (megasas_poll_wait_aen)
8187		mask = (EPOLLIN | EPOLLRDNORM);
8188	else
8189		mask = 0;
8190	megasas_poll_wait_aen = 0;
8191	spin_unlock_irqrestore(&poll_aen_lock, flags);
8192	return mask;
8193}
8194
8195/*
8196 * megasas_set_crash_dump_params_ioctl:
8197 *		Send CRASH_DUMP_MODE DCMD to all controllers
8198 * @cmd:	MFI command frame
8199 */
8200
8201static int megasas_set_crash_dump_params_ioctl(struct megasas_cmd *cmd)
8202{
8203	struct megasas_instance *local_instance;
8204	int i, error = 0;
8205	int crash_support;
8206
8207	crash_support = cmd->frame->dcmd.mbox.w[0];
8208
8209	for (i = 0; i < megasas_mgmt_info.max_index; i++) {
8210		local_instance = megasas_mgmt_info.instance[i];
8211		if (local_instance && local_instance->crash_dump_drv_support) {
8212			if ((atomic_read(&local_instance->adprecovery) ==
8213				MEGASAS_HBA_OPERATIONAL) &&
8214				!megasas_set_crash_dump_params(local_instance,
8215					crash_support)) {
8216				local_instance->crash_dump_app_support =
8217					crash_support;
8218				dev_info(&local_instance->pdev->dev,
8219					"Application firmware crash "
8220					"dump mode set success\n");
8221				error = 0;
8222			} else {
8223				dev_info(&local_instance->pdev->dev,
8224					"Application firmware crash "
8225					"dump mode set failed\n");
8226				error = -1;
8227			}
8228		}
8229	}
8230	return error;
8231}
8232
8233/**
8234 * megasas_mgmt_fw_ioctl -	Issues management ioctls to FW
8235 * @instance:			Adapter soft state
8236 * @user_ioc:			User's ioctl packet
8237 * @ioc:			ioctl packet
8238 */
8239static int
8240megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
8241		      struct megasas_iocpacket __user * user_ioc,
8242		      struct megasas_iocpacket *ioc)
8243{
8244	struct megasas_sge64 *kern_sge64 = NULL;
8245	struct megasas_sge32 *kern_sge32 = NULL;
8246	struct megasas_cmd *cmd;
8247	void *kbuff_arr[MAX_IOCTL_SGE];
8248	dma_addr_t buf_handle = 0;
8249	int error = 0, i;
8250	void *sense = NULL;
8251	dma_addr_t sense_handle;
8252	void *sense_ptr;
8253	u32 opcode = 0;
8254	int ret = DCMD_SUCCESS;
8255
8256	memset(kbuff_arr, 0, sizeof(kbuff_arr));
8257
8258	if (ioc->sge_count > MAX_IOCTL_SGE) {
8259		dev_printk(KERN_DEBUG, &instance->pdev->dev, "SGE count [%d] >  max limit [%d]\n",
8260		       ioc->sge_count, MAX_IOCTL_SGE);
8261		return -EINVAL;
8262	}
8263
8264	if ((ioc->frame.hdr.cmd >= MFI_CMD_OP_COUNT) ||
8265	    ((ioc->frame.hdr.cmd == MFI_CMD_NVME) &&
8266	    !instance->support_nvme_passthru) ||
8267	    ((ioc->frame.hdr.cmd == MFI_CMD_TOOLBOX) &&
8268	    !instance->support_pci_lane_margining)) {
8269		dev_err(&instance->pdev->dev,
8270			"Received invalid ioctl command 0x%x\n",
8271			ioc->frame.hdr.cmd);
8272		return -ENOTSUPP;
8273	}
8274
8275	cmd = megasas_get_cmd(instance);
8276	if (!cmd) {
8277		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a cmd packet\n");
8278		return -ENOMEM;
8279	}
8280
8281	/*
8282	 * User's IOCTL packet has 2 frames (maximum). Copy those two
8283	 * frames into our cmd's frames. cmd->frame's context will get
8284	 * overwritten when we copy from user's frames. So set that value
8285	 * alone separately
8286	 */
8287	memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
8288	cmd->frame->hdr.context = cpu_to_le32(cmd->index);
8289	cmd->frame->hdr.pad_0 = 0;
8290
8291	cmd->frame->hdr.flags &= (~MFI_FRAME_IEEE);
8292
8293	if (instance->consistent_mask_64bit)
8294		cmd->frame->hdr.flags |= cpu_to_le16((MFI_FRAME_SGL64 |
8295				       MFI_FRAME_SENSE64));
8296	else
8297		cmd->frame->hdr.flags &= cpu_to_le16(~(MFI_FRAME_SGL64 |
8298					       MFI_FRAME_SENSE64));
8299
8300	if (cmd->frame->hdr.cmd == MFI_CMD_DCMD)
8301		opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
8302
8303	if (opcode == MR_DCMD_CTRL_SHUTDOWN) {
8304		mutex_lock(&instance->reset_mutex);
8305		if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS) {
8306			megasas_return_cmd(instance, cmd);
8307			mutex_unlock(&instance->reset_mutex);
8308			return -1;
8309		}
8310		mutex_unlock(&instance->reset_mutex);
8311	}
8312
8313	if (opcode == MR_DRIVER_SET_APP_CRASHDUMP_MODE) {
8314		error = megasas_set_crash_dump_params_ioctl(cmd);
8315		megasas_return_cmd(instance, cmd);
8316		return error;
8317	}
8318
8319	/*
8320	 * The management interface between applications and the fw uses
8321	 * MFI frames. E.g, RAID configuration changes, LD property changes
8322	 * etc are accomplishes through different kinds of MFI frames. The
8323	 * driver needs to care only about substituting user buffers with
8324	 * kernel buffers in SGLs. The location of SGL is embedded in the
8325	 * struct iocpacket itself.
8326	 */
8327	if (instance->consistent_mask_64bit)
8328		kern_sge64 = (struct megasas_sge64 *)
8329			((unsigned long)cmd->frame + ioc->sgl_off);
8330	else
8331		kern_sge32 = (struct megasas_sge32 *)
8332			((unsigned long)cmd->frame + ioc->sgl_off);
8333
8334	/*
8335	 * For each user buffer, create a mirror buffer and copy in
8336	 */
8337	for (i = 0; i < ioc->sge_count; i++) {
8338		if (!ioc->sgl[i].iov_len)
8339			continue;
8340
8341		kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
8342						    ioc->sgl[i].iov_len,
8343						    &buf_handle, GFP_KERNEL);
8344		if (!kbuff_arr[i]) {
8345			dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to alloc "
8346			       "kernel SGL buffer for IOCTL\n");
8347			error = -ENOMEM;
8348			goto out;
8349		}
8350
8351		/*
8352		 * We don't change the dma_coherent_mask, so
8353		 * dma_alloc_coherent only returns 32bit addresses
8354		 */
8355		if (instance->consistent_mask_64bit) {
8356			kern_sge64[i].phys_addr = cpu_to_le64(buf_handle);
8357			kern_sge64[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
8358		} else {
8359			kern_sge32[i].phys_addr = cpu_to_le32(buf_handle);
8360			kern_sge32[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
8361		}
8362
8363		/*
8364		 * We created a kernel buffer corresponding to the
8365		 * user buffer. Now copy in from the user buffer
8366		 */
8367		if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
8368				   (u32) (ioc->sgl[i].iov_len))) {
8369			error = -EFAULT;
8370			goto out;
8371		}
8372	}
8373
8374	if (ioc->sense_len) {
8375		/* make sure the pointer is part of the frame */
8376		if (ioc->sense_off >
8377		    (sizeof(union megasas_frame) - sizeof(__le64))) {
8378			error = -EINVAL;
8379			goto out;
8380		}
8381
8382		sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
8383					     &sense_handle, GFP_KERNEL);
8384		if (!sense) {
8385			error = -ENOMEM;
8386			goto out;
8387		}
8388
8389		/* always store 64 bits regardless of addressing */
8390		sense_ptr = (void *)cmd->frame + ioc->sense_off;
8391		put_unaligned_le64(sense_handle, sense_ptr);
8392	}
8393
8394	/*
8395	 * Set the sync_cmd flag so that the ISR knows not to complete this
8396	 * cmd to the SCSI mid-layer
8397	 */
8398	cmd->sync_cmd = 1;
8399
8400	ret = megasas_issue_blocked_cmd(instance, cmd, 0);
8401	switch (ret) {
8402	case DCMD_INIT:
8403	case DCMD_BUSY:
8404		cmd->sync_cmd = 0;
8405		dev_err(&instance->pdev->dev,
8406			"return -EBUSY from %s %d cmd 0x%x opcode 0x%x cmd->cmd_status_drv 0x%x\n",
8407			 __func__, __LINE__, cmd->frame->hdr.cmd, opcode,
8408			 cmd->cmd_status_drv);
8409		error = -EBUSY;
8410		goto out;
8411	}
8412
8413	cmd->sync_cmd = 0;
8414
8415	if (instance->unload == 1) {
8416		dev_info(&instance->pdev->dev, "Driver unload is in progress "
8417			"don't submit data to application\n");
8418		goto out;
8419	}
8420	/*
8421	 * copy out the kernel buffers to user buffers
8422	 */
8423	for (i = 0; i < ioc->sge_count; i++) {
8424		if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
8425				 ioc->sgl[i].iov_len)) {
8426			error = -EFAULT;
8427			goto out;
8428		}
8429	}
8430
8431	/*
8432	 * copy out the sense
8433	 */
8434	if (ioc->sense_len) {
8435		void __user *uptr;
8436		/*
8437		 * sense_ptr points to the location that has the user
8438		 * sense buffer address
8439		 */
8440		sense_ptr = (void *)ioc->frame.raw + ioc->sense_off;
8441		if (in_compat_syscall())
8442			uptr = compat_ptr(get_unaligned((compat_uptr_t *)
8443							sense_ptr));
8444		else
8445			uptr = get_unaligned((void __user **)sense_ptr);
8446
8447		if (copy_to_user(uptr, sense, ioc->sense_len)) {
8448			dev_err(&instance->pdev->dev, "Failed to copy out to user "
8449					"sense data\n");
8450			error = -EFAULT;
8451			goto out;
8452		}
8453	}
8454
8455	/*
8456	 * copy the status codes returned by the fw
8457	 */
8458	if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
8459			 &cmd->frame->hdr.cmd_status, sizeof(u8))) {
8460		dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error copying out cmd_status\n");
8461		error = -EFAULT;
8462	}
8463
8464out:
8465	if (sense) {
8466		dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
8467				    sense, sense_handle);
8468	}
8469
8470	for (i = 0; i < ioc->sge_count; i++) {
8471		if (kbuff_arr[i]) {
8472			if (instance->consistent_mask_64bit)
8473				dma_free_coherent(&instance->pdev->dev,
8474					le32_to_cpu(kern_sge64[i].length),
8475					kbuff_arr[i],
8476					le64_to_cpu(kern_sge64[i].phys_addr));
8477			else
8478				dma_free_coherent(&instance->pdev->dev,
8479					le32_to_cpu(kern_sge32[i].length),
8480					kbuff_arr[i],
8481					le32_to_cpu(kern_sge32[i].phys_addr));
8482			kbuff_arr[i] = NULL;
8483		}
8484	}
8485
8486	megasas_return_cmd(instance, cmd);
8487	return error;
8488}
8489
8490static struct megasas_iocpacket *
8491megasas_compat_iocpacket_get_user(void __user *arg)
8492{
8493	struct megasas_iocpacket *ioc;
8494	struct compat_megasas_iocpacket __user *cioc = arg;
8495	size_t size;
8496	int err = -EFAULT;
8497	int i;
8498
8499	ioc = kzalloc(sizeof(*ioc), GFP_KERNEL);
8500	if (!ioc)
8501		return ERR_PTR(-ENOMEM);
8502	size = offsetof(struct megasas_iocpacket, frame) + sizeof(ioc->frame);
8503	if (copy_from_user(ioc, arg, size))
8504		goto out;
8505
8506	for (i = 0; i < MAX_IOCTL_SGE; i++) {
8507		compat_uptr_t iov_base;
8508
8509		if (get_user(iov_base, &cioc->sgl[i].iov_base) ||
8510		    get_user(ioc->sgl[i].iov_len, &cioc->sgl[i].iov_len))
8511			goto out;
8512
8513		ioc->sgl[i].iov_base = compat_ptr(iov_base);
8514	}
8515
8516	return ioc;
8517out:
8518	kfree(ioc);
8519	return ERR_PTR(err);
8520}
8521
8522static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
8523{
8524	struct megasas_iocpacket __user *user_ioc =
8525	    (struct megasas_iocpacket __user *)arg;
8526	struct megasas_iocpacket *ioc;
8527	struct megasas_instance *instance;
8528	int error;
8529
8530	if (in_compat_syscall())
8531		ioc = megasas_compat_iocpacket_get_user(user_ioc);
8532	else
8533		ioc = memdup_user(user_ioc, sizeof(struct megasas_iocpacket));
8534
8535	if (IS_ERR(ioc))
8536		return PTR_ERR(ioc);
8537
8538	instance = megasas_lookup_instance(ioc->host_no);
8539	if (!instance) {
8540		error = -ENODEV;
8541		goto out_kfree_ioc;
8542	}
8543
8544	/* Block ioctls in VF mode */
8545	if (instance->requestorId && !allow_vf_ioctls) {
8546		error = -ENODEV;
8547		goto out_kfree_ioc;
8548	}
8549
8550	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8551		dev_err(&instance->pdev->dev, "Controller in crit error\n");
8552		error = -ENODEV;
8553		goto out_kfree_ioc;
8554	}
8555
8556	if (instance->unload == 1) {
8557		error = -ENODEV;
8558		goto out_kfree_ioc;
8559	}
8560
8561	if (down_interruptible(&instance->ioctl_sem)) {
8562		error = -ERESTARTSYS;
8563		goto out_kfree_ioc;
8564	}
8565
8566	if  (megasas_wait_for_adapter_operational(instance)) {
8567		error = -ENODEV;
8568		goto out_up;
8569	}
8570
8571	error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
8572out_up:
8573	up(&instance->ioctl_sem);
8574
8575out_kfree_ioc:
8576	kfree(ioc);
8577	return error;
8578}
8579
8580static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
8581{
8582	struct megasas_instance *instance;
8583	struct megasas_aen aen;
8584	int error;
8585
8586	if (file->private_data != file) {
8587		printk(KERN_DEBUG "megasas: fasync_helper was not "
8588		       "called first\n");
8589		return -EINVAL;
8590	}
8591
8592	if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
8593		return -EFAULT;
8594
8595	instance = megasas_lookup_instance(aen.host_no);
8596
8597	if (!instance)
8598		return -ENODEV;
8599
8600	if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8601		return -ENODEV;
8602	}
8603
8604	if (instance->unload == 1) {
8605		return -ENODEV;
8606	}
8607
8608	if  (megasas_wait_for_adapter_operational(instance))
8609		return -ENODEV;
8610
8611	mutex_lock(&instance->reset_mutex);
8612	error = megasas_register_aen(instance, aen.seq_num,
8613				     aen.class_locale_word);
8614	mutex_unlock(&instance->reset_mutex);
8615	return error;
8616}
8617
8618/**
8619 * megasas_mgmt_ioctl -	char node ioctl entry point
8620 * @file:	char device file pointer
8621 * @cmd:	ioctl command
8622 * @arg:	ioctl command arguments address
8623 */
8624static long
8625megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
8626{
8627	switch (cmd) {
8628	case MEGASAS_IOC_FIRMWARE:
8629		return megasas_mgmt_ioctl_fw(file, arg);
8630
8631	case MEGASAS_IOC_GET_AEN:
8632		return megasas_mgmt_ioctl_aen(file, arg);
8633	}
8634
8635	return -ENOTTY;
8636}
8637
8638#ifdef CONFIG_COMPAT
8639static long
8640megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
8641			  unsigned long arg)
8642{
8643	switch (cmd) {
8644	case MEGASAS_IOC_FIRMWARE32:
8645		return megasas_mgmt_ioctl_fw(file, arg);
8646	case MEGASAS_IOC_GET_AEN:
8647		return megasas_mgmt_ioctl_aen(file, arg);
8648	}
8649
8650	return -ENOTTY;
8651}
8652#endif
8653
8654/*
8655 * File operations structure for management interface
8656 */
8657static const struct file_operations megasas_mgmt_fops = {
8658	.owner = THIS_MODULE,
8659	.open = megasas_mgmt_open,
8660	.fasync = megasas_mgmt_fasync,
8661	.unlocked_ioctl = megasas_mgmt_ioctl,
8662	.poll = megasas_mgmt_poll,
8663#ifdef CONFIG_COMPAT
8664	.compat_ioctl = megasas_mgmt_compat_ioctl,
8665#endif
8666	.llseek = noop_llseek,
8667};
8668
8669static SIMPLE_DEV_PM_OPS(megasas_pm_ops, megasas_suspend, megasas_resume);
8670
8671/*
8672 * PCI hotplug support registration structure
8673 */
8674static struct pci_driver megasas_pci_driver = {
8675
8676	.name = "megaraid_sas",
8677	.id_table = megasas_pci_table,
8678	.probe = megasas_probe_one,
8679	.remove = megasas_detach_one,
8680	.driver.pm = &megasas_pm_ops,
8681	.shutdown = megasas_shutdown,
8682};
8683
8684/*
8685 * Sysfs driver attributes
8686 */
8687static ssize_t version_show(struct device_driver *dd, char *buf)
8688{
8689	return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
8690			MEGASAS_VERSION);
8691}
8692static DRIVER_ATTR_RO(version);
8693
8694static ssize_t release_date_show(struct device_driver *dd, char *buf)
8695{
8696	return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
8697		MEGASAS_RELDATE);
8698}
8699static DRIVER_ATTR_RO(release_date);
8700
8701static ssize_t support_poll_for_event_show(struct device_driver *dd, char *buf)
8702{
8703	return sprintf(buf, "%u\n", support_poll_for_event);
8704}
8705static DRIVER_ATTR_RO(support_poll_for_event);
8706
8707static ssize_t support_device_change_show(struct device_driver *dd, char *buf)
8708{
8709	return sprintf(buf, "%u\n", support_device_change);
8710}
8711static DRIVER_ATTR_RO(support_device_change);
8712
8713static ssize_t dbg_lvl_show(struct device_driver *dd, char *buf)
8714{
8715	return sprintf(buf, "%u\n", megasas_dbg_lvl);
8716}
8717
8718static ssize_t dbg_lvl_store(struct device_driver *dd, const char *buf,
8719			     size_t count)
8720{
8721	int retval = count;
8722
8723	if (sscanf(buf, "%u", &megasas_dbg_lvl) < 1) {
8724		printk(KERN_ERR "megasas: could not set dbg_lvl\n");
8725		retval = -EINVAL;
8726	}
8727	return retval;
8728}
8729static DRIVER_ATTR_RW(dbg_lvl);
8730
8731static ssize_t
8732support_nvme_encapsulation_show(struct device_driver *dd, char *buf)
8733{
8734	return sprintf(buf, "%u\n", support_nvme_encapsulation);
8735}
8736
8737static DRIVER_ATTR_RO(support_nvme_encapsulation);
8738
8739static ssize_t
8740support_pci_lane_margining_show(struct device_driver *dd, char *buf)
8741{
8742	return sprintf(buf, "%u\n", support_pci_lane_margining);
8743}
8744
8745static DRIVER_ATTR_RO(support_pci_lane_margining);
8746
8747static inline void megasas_remove_scsi_device(struct scsi_device *sdev)
8748{
8749	sdev_printk(KERN_INFO, sdev, "SCSI device is removed\n");
8750	scsi_remove_device(sdev);
8751	scsi_device_put(sdev);
8752}
8753
8754/**
8755 * megasas_update_device_list -	Update the PD and LD device list from FW
8756 *				after an AEN event notification
8757 * @instance:			Adapter soft state
8758 * @event_type:			Indicates type of event (PD or LD event)
8759 *
8760 * @return:			Success or failure
8761 *
8762 * Issue DCMDs to Firmware to update the internal device list in driver.
8763 * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
8764 * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
8765 */
8766static
8767int megasas_update_device_list(struct megasas_instance *instance,
8768			       int event_type)
8769{
8770	int dcmd_ret;
8771
8772	if (instance->enable_fw_dev_list) {
8773		return megasas_host_device_list_query(instance, false);
8774	} else {
8775		if (event_type & SCAN_PD_CHANNEL) {
8776			dcmd_ret = megasas_get_pd_list(instance);
8777			if (dcmd_ret != DCMD_SUCCESS)
8778				return dcmd_ret;
8779		}
8780
8781		if (event_type & SCAN_VD_CHANNEL) {
8782			if (!instance->requestorId ||
8783			megasas_get_ld_vf_affiliation(instance, 0)) {
8784				return megasas_ld_list_query(instance,
8785						MR_LD_QUERY_TYPE_EXPOSED_TO_HOST);
8786			}
8787		}
8788	}
8789	return DCMD_SUCCESS;
8790}
8791
8792/**
8793 * megasas_add_remove_devices -	Add/remove devices to SCSI mid-layer
8794 *				after an AEN event notification
8795 * @instance:			Adapter soft state
8796 * @scan_type:			Indicates type of devices (PD/LD) to add
8797 * @return			void
8798 */
8799static
8800void megasas_add_remove_devices(struct megasas_instance *instance,
8801				int scan_type)
8802{
8803	int i, j;
8804	u16 pd_index = 0;
8805	u16 ld_index = 0;
8806	u16 channel = 0, id = 0;
8807	struct Scsi_Host *host;
8808	struct scsi_device *sdev1;
8809	struct MR_HOST_DEVICE_LIST *targetid_list = NULL;
8810	struct MR_HOST_DEVICE_LIST_ENTRY *targetid_entry = NULL;
8811
8812	host = instance->host;
8813
8814	if (instance->enable_fw_dev_list) {
8815		targetid_list = instance->host_device_list_buf;
8816		for (i = 0; i < targetid_list->count; i++) {
8817			targetid_entry = &targetid_list->host_device_list[i];
8818			if (targetid_entry->flags.u.bits.is_sys_pd) {
8819				channel = le16_to_cpu(targetid_entry->target_id) /
8820						MEGASAS_MAX_DEV_PER_CHANNEL;
8821				id = le16_to_cpu(targetid_entry->target_id) %
8822						MEGASAS_MAX_DEV_PER_CHANNEL;
8823			} else {
8824				channel = MEGASAS_MAX_PD_CHANNELS +
8825					  (le16_to_cpu(targetid_entry->target_id) /
8826					   MEGASAS_MAX_DEV_PER_CHANNEL);
8827				id = le16_to_cpu(targetid_entry->target_id) %
8828						MEGASAS_MAX_DEV_PER_CHANNEL;
8829			}
8830			sdev1 = scsi_device_lookup(host, channel, id, 0);
8831			if (!sdev1) {
8832				scsi_add_device(host, channel, id, 0);
8833			} else {
8834				scsi_device_put(sdev1);
8835			}
8836		}
8837	}
8838
8839	if (scan_type & SCAN_PD_CHANNEL) {
8840		for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
8841			for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8842				pd_index = i * MEGASAS_MAX_DEV_PER_CHANNEL + j;
8843				sdev1 = scsi_device_lookup(host, i, j, 0);
8844				if (instance->pd_list[pd_index].driveState ==
8845							MR_PD_STATE_SYSTEM) {
8846					if (!sdev1)
8847						scsi_add_device(host, i, j, 0);
8848					else
8849						scsi_device_put(sdev1);
8850				} else {
8851					if (sdev1)
8852						megasas_remove_scsi_device(sdev1);
8853				}
8854			}
8855		}
8856	}
8857
8858	if (scan_type & SCAN_VD_CHANNEL) {
8859		for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
8860			for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8861				ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
8862				sdev1 = scsi_device_lookup(host,
8863						MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8864				if (instance->ld_ids[ld_index] != 0xff) {
8865					if (!sdev1)
8866						scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8867					else
8868						scsi_device_put(sdev1);
8869				} else {
8870					if (sdev1)
8871						megasas_remove_scsi_device(sdev1);
8872				}
8873			}
8874		}
8875	}
8876
8877}
8878
8879static void
8880megasas_aen_polling(struct work_struct *work)
8881{
8882	struct megasas_aen_event *ev =
8883		container_of(work, struct megasas_aen_event, hotplug_work.work);
8884	struct megasas_instance *instance = ev->instance;
8885	union megasas_evt_class_locale class_locale;
8886	int event_type = 0;
8887	u32 seq_num;
8888	u16 ld_target_id;
8889	int error;
8890	u8  dcmd_ret = DCMD_SUCCESS;
8891	struct scsi_device *sdev1;
8892
8893	if (!instance) {
8894		printk(KERN_ERR "invalid instance!\n");
8895		kfree(ev);
8896		return;
8897	}
8898
8899	/* Don't run the event workqueue thread if OCR is running */
8900	mutex_lock(&instance->reset_mutex);
8901
8902	instance->ev = NULL;
8903	if (instance->evt_detail) {
8904		megasas_decode_evt(instance);
8905
8906		switch (le32_to_cpu(instance->evt_detail->code)) {
8907
8908		case MR_EVT_PD_INSERTED:
8909		case MR_EVT_PD_REMOVED:
8910			event_type = SCAN_PD_CHANNEL;
8911			break;
8912
8913		case MR_EVT_LD_OFFLINE:
8914		case MR_EVT_LD_DELETED:
8915			ld_target_id = instance->evt_detail->args.ld.target_id;
8916			sdev1 = scsi_device_lookup(instance->host,
8917						   MEGASAS_MAX_PD_CHANNELS +
8918						   (ld_target_id / MEGASAS_MAX_DEV_PER_CHANNEL),
8919						   (ld_target_id % MEGASAS_MAX_DEV_PER_CHANNEL),
8920						   0);
8921			if (sdev1) {
8922				mutex_unlock(&instance->reset_mutex);
8923				megasas_remove_scsi_device(sdev1);
8924				mutex_lock(&instance->reset_mutex);
8925			}
8926
8927			event_type = SCAN_VD_CHANNEL;
8928			break;
8929		case MR_EVT_LD_CREATED:
8930			event_type = SCAN_VD_CHANNEL;
8931			break;
8932
8933		case MR_EVT_CFG_CLEARED:
8934		case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
8935		case MR_EVT_FOREIGN_CFG_IMPORTED:
8936		case MR_EVT_LD_STATE_CHANGE:
8937			event_type = SCAN_PD_CHANNEL | SCAN_VD_CHANNEL;
8938			dev_info(&instance->pdev->dev, "scanning for scsi%d...\n",
8939				instance->host->host_no);
8940			break;
8941
8942		case MR_EVT_CTRL_PROP_CHANGED:
8943			dcmd_ret = megasas_get_ctrl_info(instance);
8944			if (dcmd_ret == DCMD_SUCCESS &&
8945			    instance->snapdump_wait_time) {
8946				megasas_get_snapdump_properties(instance);
8947				dev_info(&instance->pdev->dev,
8948					 "Snap dump wait time\t: %d\n",
8949					 instance->snapdump_wait_time);
8950			}
8951			break;
8952		default:
8953			event_type = 0;
8954			break;
8955		}
8956	} else {
8957		dev_err(&instance->pdev->dev, "invalid evt_detail!\n");
8958		mutex_unlock(&instance->reset_mutex);
8959		kfree(ev);
8960		return;
8961	}
8962
8963	if (event_type)
8964		dcmd_ret = megasas_update_device_list(instance, event_type);
8965
8966	mutex_unlock(&instance->reset_mutex);
8967
8968	if (event_type && dcmd_ret == DCMD_SUCCESS)
8969		megasas_add_remove_devices(instance, event_type);
8970
8971	if (dcmd_ret == DCMD_SUCCESS)
8972		seq_num = le32_to_cpu(instance->evt_detail->seq_num) + 1;
8973	else
8974		seq_num = instance->last_seq_num;
8975
8976	/* Register AEN with FW for latest sequence number plus 1 */
8977	class_locale.members.reserved = 0;
8978	class_locale.members.locale = MR_EVT_LOCALE_ALL;
8979	class_locale.members.class = MR_EVT_CLASS_DEBUG;
8980
8981	if (instance->aen_cmd != NULL) {
8982		kfree(ev);
8983		return;
8984	}
8985
8986	mutex_lock(&instance->reset_mutex);
8987	error = megasas_register_aen(instance, seq_num,
8988					class_locale.word);
8989	if (error)
8990		dev_err(&instance->pdev->dev,
8991			"register aen failed error %x\n", error);
8992
8993	mutex_unlock(&instance->reset_mutex);
8994	kfree(ev);
8995}
8996
8997/**
8998 * megasas_init - Driver load entry point
8999 */
9000static int __init megasas_init(void)
9001{
9002	int rval;
9003
9004	/*
9005	 * Booted in kdump kernel, minimize memory footprints by
9006	 * disabling few features
9007	 */
9008	if (reset_devices) {
9009		msix_vectors = 1;
9010		rdpq_enable = 0;
9011		dual_qdepth_disable = 1;
9012		poll_queues = 0;
9013	}
9014
9015	/*
9016	 * Announce driver version and other information
9017	 */
9018	pr_info("megasas: %s\n", MEGASAS_VERSION);
9019
9020	megasas_dbg_lvl = 0;
9021	support_poll_for_event = 2;
9022	support_device_change = 1;
9023	support_nvme_encapsulation = true;
9024	support_pci_lane_margining = true;
9025
9026	memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
9027
9028	/*
9029	 * Register character device node
9030	 */
9031	rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
9032
9033	if (rval < 0) {
9034		printk(KERN_DEBUG "megasas: failed to open device node\n");
9035		return rval;
9036	}
9037
9038	megasas_mgmt_majorno = rval;
9039
9040	megasas_init_debugfs();
9041
9042	/*
9043	 * Register ourselves as PCI hotplug module
9044	 */
9045	rval = pci_register_driver(&megasas_pci_driver);
9046
9047	if (rval) {
9048		printk(KERN_DEBUG "megasas: PCI hotplug registration failed \n");
9049		goto err_pcidrv;
9050	}
9051
9052	if ((event_log_level < MFI_EVT_CLASS_DEBUG) ||
9053	    (event_log_level > MFI_EVT_CLASS_DEAD)) {
9054		pr_warn("megaraid_sas: provided event log level is out of range, setting it to default 2(CLASS_CRITICAL), permissible range is: -2 to 4\n");
9055		event_log_level = MFI_EVT_CLASS_CRITICAL;
9056	}
9057
9058	rval = driver_create_file(&megasas_pci_driver.driver,
9059				  &driver_attr_version);
9060	if (rval)
9061		goto err_dcf_attr_ver;
9062
9063	rval = driver_create_file(&megasas_pci_driver.driver,
9064				  &driver_attr_release_date);
9065	if (rval)
9066		goto err_dcf_rel_date;
9067
9068	rval = driver_create_file(&megasas_pci_driver.driver,
9069				&driver_attr_support_poll_for_event);
9070	if (rval)
9071		goto err_dcf_support_poll_for_event;
9072
9073	rval = driver_create_file(&megasas_pci_driver.driver,
9074				  &driver_attr_dbg_lvl);
9075	if (rval)
9076		goto err_dcf_dbg_lvl;
9077	rval = driver_create_file(&megasas_pci_driver.driver,
9078				&driver_attr_support_device_change);
9079	if (rval)
9080		goto err_dcf_support_device_change;
9081
9082	rval = driver_create_file(&megasas_pci_driver.driver,
9083				  &driver_attr_support_nvme_encapsulation);
9084	if (rval)
9085		goto err_dcf_support_nvme_encapsulation;
9086
9087	rval = driver_create_file(&megasas_pci_driver.driver,
9088				  &driver_attr_support_pci_lane_margining);
9089	if (rval)
9090		goto err_dcf_support_pci_lane_margining;
9091
9092	return rval;
9093
9094err_dcf_support_pci_lane_margining:
9095	driver_remove_file(&megasas_pci_driver.driver,
9096			   &driver_attr_support_nvme_encapsulation);
9097
9098err_dcf_support_nvme_encapsulation:
9099	driver_remove_file(&megasas_pci_driver.driver,
9100			   &driver_attr_support_device_change);
9101
9102err_dcf_support_device_change:
9103	driver_remove_file(&megasas_pci_driver.driver,
9104			   &driver_attr_dbg_lvl);
9105err_dcf_dbg_lvl:
9106	driver_remove_file(&megasas_pci_driver.driver,
9107			&driver_attr_support_poll_for_event);
9108err_dcf_support_poll_for_event:
9109	driver_remove_file(&megasas_pci_driver.driver,
9110			   &driver_attr_release_date);
9111err_dcf_rel_date:
9112	driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
9113err_dcf_attr_ver:
9114	pci_unregister_driver(&megasas_pci_driver);
9115err_pcidrv:
9116	megasas_exit_debugfs();
9117	unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
9118	return rval;
9119}
9120
9121/**
9122 * megasas_exit - Driver unload entry point
9123 */
9124static void __exit megasas_exit(void)
9125{
9126	driver_remove_file(&megasas_pci_driver.driver,
9127			   &driver_attr_dbg_lvl);
9128	driver_remove_file(&megasas_pci_driver.driver,
9129			&driver_attr_support_poll_for_event);
9130	driver_remove_file(&megasas_pci_driver.driver,
9131			&driver_attr_support_device_change);
9132	driver_remove_file(&megasas_pci_driver.driver,
9133			   &driver_attr_release_date);
9134	driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
9135	driver_remove_file(&megasas_pci_driver.driver,
9136			   &driver_attr_support_nvme_encapsulation);
9137	driver_remove_file(&megasas_pci_driver.driver,
9138			   &driver_attr_support_pci_lane_margining);
9139
9140	pci_unregister_driver(&megasas_pci_driver);
9141	megasas_exit_debugfs();
9142	unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
9143}
9144
9145module_init(megasas_init);
9146module_exit(megasas_exit);
~/ Read-only file preview.