megaraid_sas_fusion.c 60.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/*
 *  Linux MegaRAID driver for SAS based RAID controllers
 *
 *  Copyright (c) 2009-2011  LSI Corporation.
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *  FILE: megaraid_sas_fusion.c
 *
 *  Authors: LSI Corporation
 *           Sumant Patro
 *           Adam Radford <linuxraid@lsi.com>
 *
 *  Send feedback to: <megaraidlinux@lsi.com>
 *
 *  Mail to: LSI Corporation, 1621 Barber Lane, Milpitas, CA 95035
 *     ATTN: Linuxraid
 */

#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/list.h>
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/uio.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/compat.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/poll.h>

#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>

#include "megaraid_sas_fusion.h"
#include "megaraid_sas.h"

extern void megasas_free_cmds(struct megasas_instance *instance);
extern struct megasas_cmd *megasas_get_cmd(struct megasas_instance
					   *instance);
extern void
megasas_complete_cmd(struct megasas_instance *instance,
		     struct megasas_cmd *cmd, u8 alt_status);
int megasas_is_ldio(struct scsi_cmnd *cmd);
int
wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd);

void
megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd);
int megasas_alloc_cmds(struct megasas_instance *instance);
int
megasas_clear_intr_fusion(struct megasas_register_set __iomem *regs);
int
megasas_issue_polled(struct megasas_instance *instance,
		     struct megasas_cmd *cmd);

u8
MR_BuildRaidContext(struct IO_REQUEST_INFO *io_info,
		    struct RAID_CONTEXT *pRAID_Context,
		    struct MR_FW_RAID_MAP_ALL *map);
u16 MR_TargetIdToLdGet(u32 ldTgtId, struct MR_FW_RAID_MAP_ALL *map);
struct MR_LD_RAID *MR_LdRaidGet(u32 ld, struct MR_FW_RAID_MAP_ALL *map);

u16 MR_GetLDTgtId(u32 ld, struct MR_FW_RAID_MAP_ALL *map);
84 85 86 87

void
megasas_check_and_restore_queue_depth(struct megasas_instance *instance);

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
u8 MR_ValidateMapInfo(struct MR_FW_RAID_MAP_ALL *map,
		      struct LD_LOAD_BALANCE_INFO *lbInfo);
u16 get_updated_dev_handle(struct LD_LOAD_BALANCE_INFO *lbInfo,
			   struct IO_REQUEST_INFO *in_info);
int megasas_transition_to_ready(struct megasas_instance *instance);
void megaraid_sas_kill_hba(struct megasas_instance *instance);

extern u32 megasas_dbg_lvl;

/**
 * megasas_enable_intr_fusion -	Enables interrupts
 * @regs:			MFI register set
 */
void
megasas_enable_intr_fusion(struct megasas_register_set __iomem *regs)
{
	writel(~MFI_FUSION_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);

	/* Dummy readl to force pci flush */
	readl(&regs->outbound_intr_mask);
}

/**
 * megasas_disable_intr_fusion - Disables interrupt
 * @regs:			 MFI register set
 */
void
megasas_disable_intr_fusion(struct megasas_register_set __iomem *regs)
{
	u32 mask = 0xFFFFFFFF;
	u32 status;

	writel(mask, &regs->outbound_intr_mask);
	/* Dummy readl to force pci flush */
	status = readl(&regs->outbound_intr_mask);
}

int
megasas_clear_intr_fusion(struct megasas_register_set __iomem *regs)
{
	u32 status;
	/*
	 * Check if it is our interrupt
	 */
	status = readl(&regs->outbound_intr_status);

	if (status & 1) {
		writel(status, &regs->outbound_intr_status);
		readl(&regs->outbound_intr_status);
		return 1;
	}
	if (!(status & MFI_FUSION_ENABLE_INTERRUPT_MASK))
		return 0;

	/*
	 * dummy read to flush PCI
	 */
	readl(&regs->outbound_intr_status);

	return 1;
}

/**
 * megasas_get_cmd_fusion -	Get a command from the free pool
 * @instance:		Adapter soft state
 *
 * Returns a free command from the pool
 */
struct megasas_cmd_fusion *megasas_get_cmd_fusion(struct megasas_instance
						  *instance)
{
	unsigned long flags;
	struct fusion_context *fusion =
		(struct fusion_context *)instance->ctrl_context;
	struct megasas_cmd_fusion *cmd = NULL;

	spin_lock_irqsave(&fusion->cmd_pool_lock, flags);

	if (!list_empty(&fusion->cmd_pool)) {
		cmd = list_entry((&fusion->cmd_pool)->next,
				 struct megasas_cmd_fusion, list);
		list_del_init(&cmd->list);
	} else {
		printk(KERN_ERR "megasas: Command pool (fusion) empty!\n");
	}

	spin_unlock_irqrestore(&fusion->cmd_pool_lock, flags);
	return cmd;
}

/**
 * megasas_return_cmd_fusion -	Return a cmd to free command pool
 * @instance:		Adapter soft state
 * @cmd:		Command packet to be returned to free command pool
 */
static inline void
megasas_return_cmd_fusion(struct megasas_instance *instance,
			  struct megasas_cmd_fusion *cmd)
{
	unsigned long flags;
	struct fusion_context *fusion =
		(struct fusion_context *)instance->ctrl_context;

	spin_lock_irqsave(&fusion->cmd_pool_lock, flags);

	cmd->scmd = NULL;
	cmd->sync_cmd_idx = (u32)ULONG_MAX;
	list_add_tail(&cmd->list, &fusion->cmd_pool);

	spin_unlock_irqrestore(&fusion->cmd_pool_lock, flags);
}

/**
 * megasas_teardown_frame_pool_fusion -	Destroy the cmd frame DMA pool
 * @instance:				Adapter soft state
 */
static void megasas_teardown_frame_pool_fusion(
	struct megasas_instance *instance)
{
	int i;
	struct fusion_context *fusion = instance->ctrl_context;

	u16 max_cmd = instance->max_fw_cmds;

	struct megasas_cmd_fusion *cmd;

	if (!fusion->sg_dma_pool || !fusion->sense_dma_pool) {
		printk(KERN_ERR "megasas: dma pool is null. SG Pool %p, "
		       "sense pool : %p\n", fusion->sg_dma_pool,
		       fusion->sense_dma_pool);
		return;
	}

	/*
	 * Return all frames to pool
	 */
	for (i = 0; i < max_cmd; i++) {

		cmd = fusion->cmd_list[i];

		if (cmd->sg_frame)
			pci_pool_free(fusion->sg_dma_pool, cmd->sg_frame,
				      cmd->sg_frame_phys_addr);

		if (cmd->sense)
			pci_pool_free(fusion->sense_dma_pool, cmd->sense,
				      cmd->sense_phys_addr);
	}

	/*
	 * Now destroy the pool itself
	 */
	pci_pool_destroy(fusion->sg_dma_pool);
	pci_pool_destroy(fusion->sense_dma_pool);

	fusion->sg_dma_pool = NULL;
	fusion->sense_dma_pool = NULL;
}

/**
 * megasas_free_cmds_fusion -	Free all the cmds in the free cmd pool
 * @instance:		Adapter soft state
 */
void
megasas_free_cmds_fusion(struct megasas_instance *instance)
{
	int i;
	struct fusion_context *fusion = instance->ctrl_context;

	u32 max_cmds, req_sz, reply_sz, io_frames_sz;


	req_sz = fusion->request_alloc_sz;
	reply_sz = fusion->reply_alloc_sz;
	io_frames_sz = fusion->io_frames_alloc_sz;

	max_cmds = instance->max_fw_cmds;

	/* Free descriptors and request Frames memory */
	if (fusion->req_frames_desc)
		dma_free_coherent(&instance->pdev->dev, req_sz,
				  fusion->req_frames_desc,
				  fusion->req_frames_desc_phys);

	if (fusion->reply_frames_desc) {
		pci_pool_free(fusion->reply_frames_desc_pool,
			      fusion->reply_frames_desc,
			      fusion->reply_frames_desc_phys);
		pci_pool_destroy(fusion->reply_frames_desc_pool);
	}

	if (fusion->io_request_frames) {
		pci_pool_free(fusion->io_request_frames_pool,
			      fusion->io_request_frames,
			      fusion->io_request_frames_phys);
		pci_pool_destroy(fusion->io_request_frames_pool);
	}

	/* Free the Fusion frame pool */
	megasas_teardown_frame_pool_fusion(instance);

	/* Free all the commands in the cmd_list */
	for (i = 0; i < max_cmds; i++)
		kfree(fusion->cmd_list[i]);

	/* Free the cmd_list buffer itself */
	kfree(fusion->cmd_list);
	fusion->cmd_list = NULL;

	INIT_LIST_HEAD(&fusion->cmd_pool);
}

/**
 * megasas_create_frame_pool_fusion -	Creates DMA pool for cmd frames
 * @instance:			Adapter soft state
 *
 */
static int megasas_create_frame_pool_fusion(struct megasas_instance *instance)
{
	int i;
	u32 max_cmd;
	struct fusion_context *fusion;
	struct megasas_cmd_fusion *cmd;
	u32 total_sz_chain_frame;

	fusion = instance->ctrl_context;
	max_cmd = instance->max_fw_cmds;

	total_sz_chain_frame = MEGASAS_MAX_SZ_CHAIN_FRAME;

	/*
	 * Use DMA pool facility provided by PCI layer
	 */

	fusion->sg_dma_pool = pci_pool_create("megasas sg pool fusion",
					      instance->pdev,
					      total_sz_chain_frame, 4,
					      0);
	if (!fusion->sg_dma_pool) {
		printk(KERN_DEBUG "megasas: failed to setup request pool "
		       "fusion\n");
		return -ENOMEM;
	}
	fusion->sense_dma_pool = pci_pool_create("megasas sense pool fusion",
						 instance->pdev,
						 SCSI_SENSE_BUFFERSIZE, 64, 0);

	if (!fusion->sense_dma_pool) {
		printk(KERN_DEBUG "megasas: failed to setup sense pool "
		       "fusion\n");
		pci_pool_destroy(fusion->sg_dma_pool);
		fusion->sg_dma_pool = NULL;
		return -ENOMEM;
	}

	/*
	 * Allocate and attach a frame to each of the commands in cmd_list
	 */
	for (i = 0; i < max_cmd; i++) {

		cmd = fusion->cmd_list[i];

		cmd->sg_frame = pci_pool_alloc(fusion->sg_dma_pool,
					       GFP_KERNEL,
					       &cmd->sg_frame_phys_addr);

		cmd->sense = pci_pool_alloc(fusion->sense_dma_pool,
					    GFP_KERNEL, &cmd->sense_phys_addr);
		/*
		 * megasas_teardown_frame_pool_fusion() takes care of freeing
		 * whatever has been allocated
		 */
		if (!cmd->sg_frame || !cmd->sense) {
			printk(KERN_DEBUG "megasas: pci_pool_alloc failed\n");
			megasas_teardown_frame_pool_fusion(instance);
			return -ENOMEM;
		}
	}
	return 0;
}

/**
 * megasas_alloc_cmds_fusion -	Allocates the command packets
 * @instance:		Adapter soft state
 *
 *
 * Each frame has a 32-bit field called context. This context is used to get
 * back the megasas_cmd_fusion from the frame when a frame gets completed
 * In this driver, the 32 bit values are the indices into an array cmd_list.
 * This array is used only to look up the megasas_cmd_fusion given the context.
 * The free commands themselves are maintained in a linked list called cmd_pool.
 *
 * cmds are formed in the io_request and sg_frame members of the
 * megasas_cmd_fusion. The context field is used to get a request descriptor
 * and is used as SMID of the cmd.
 * SMID value range is from 1 to max_fw_cmds.
 */
int
megasas_alloc_cmds_fusion(struct megasas_instance *instance)
{
	int i, j;
	u32 max_cmd, io_frames_sz;
	struct fusion_context *fusion;
	struct megasas_cmd_fusion *cmd;
	union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
	u32 offset;
	dma_addr_t io_req_base_phys;
	u8 *io_req_base;

	fusion = instance->ctrl_context;

	max_cmd = instance->max_fw_cmds;

	fusion->req_frames_desc =
		dma_alloc_coherent(&instance->pdev->dev,
				   fusion->request_alloc_sz,
				   &fusion->req_frames_desc_phys, GFP_KERNEL);

	if (!fusion->req_frames_desc) {
		printk(KERN_ERR "megasas; Could not allocate memory for "
		       "request_frames\n");
		goto fail_req_desc;
	}

	fusion->reply_frames_desc_pool =
		pci_pool_create("reply_frames pool", instance->pdev,
				fusion->reply_alloc_sz, 16, 0);

	if (!fusion->reply_frames_desc_pool) {
		printk(KERN_ERR "megasas; Could not allocate memory for "
		       "reply_frame pool\n");
		goto fail_reply_desc;
	}

	fusion->reply_frames_desc =
		pci_pool_alloc(fusion->reply_frames_desc_pool, GFP_KERNEL,
			       &fusion->reply_frames_desc_phys);
	if (!fusion->reply_frames_desc) {
		printk(KERN_ERR "megasas; Could not allocate memory for "
		       "reply_frame pool\n");
		pci_pool_destroy(fusion->reply_frames_desc_pool);
		goto fail_reply_desc;
	}

	reply_desc = fusion->reply_frames_desc;
	for (i = 0; i < fusion->reply_q_depth; i++, reply_desc++)
		reply_desc->Words = ULLONG_MAX;

	io_frames_sz = fusion->io_frames_alloc_sz;

	fusion->io_request_frames_pool =
		pci_pool_create("io_request_frames pool", instance->pdev,
				fusion->io_frames_alloc_sz, 16, 0);

	if (!fusion->io_request_frames_pool) {
		printk(KERN_ERR "megasas: Could not allocate memory for "
		       "io_request_frame pool\n");
		goto fail_io_frames;
	}

	fusion->io_request_frames =
		pci_pool_alloc(fusion->io_request_frames_pool, GFP_KERNEL,
			       &fusion->io_request_frames_phys);
	if (!fusion->io_request_frames) {
		printk(KERN_ERR "megasas: Could not allocate memory for "
		       "io_request_frames frames\n");
		pci_pool_destroy(fusion->io_request_frames_pool);
		goto fail_io_frames;
	}

	/*
	 * fusion->cmd_list is an array of struct megasas_cmd_fusion pointers.
	 * Allocate the dynamic array first and then allocate individual
	 * commands.
	 */
	fusion->cmd_list = kmalloc(sizeof(struct megasas_cmd_fusion *)
				   *max_cmd, GFP_KERNEL);

	if (!fusion->cmd_list) {
		printk(KERN_DEBUG "megasas: out of memory. Could not alloc "
		       "memory for cmd_list_fusion\n");
		goto fail_cmd_list;
	}

	memset(fusion->cmd_list, 0, sizeof(struct megasas_cmd_fusion *)
	       *max_cmd);

	max_cmd = instance->max_fw_cmds;
	for (i = 0; i < max_cmd; i++) {
		fusion->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd_fusion),
					      GFP_KERNEL);
		if (!fusion->cmd_list[i]) {
			printk(KERN_ERR "Could not alloc cmd list fusion\n");

			for (j = 0; j < i; j++)
				kfree(fusion->cmd_list[j]);

			kfree(fusion->cmd_list);
			fusion->cmd_list = NULL;
			goto fail_cmd_list;
		}
	}

	/* The first 256 bytes (SMID 0) is not used. Don't add to cmd list */
	io_req_base = fusion->io_request_frames +
		MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;
	io_req_base_phys = fusion->io_request_frames_phys +
		MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;

	/*
	 * Add all the commands to command pool (fusion->cmd_pool)
	 */

	/* SMID 0 is reserved. Set SMID/index from 1 */
	for (i = 0; i < max_cmd; i++) {
		cmd = fusion->cmd_list[i];
		offset = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE * i;
		memset(cmd, 0, sizeof(struct megasas_cmd_fusion));
		cmd->index = i + 1;
		cmd->scmd = NULL;
		cmd->sync_cmd_idx = (u32)ULONG_MAX; /* Set to Invalid */
		cmd->instance = instance;
		cmd->io_request =
			(struct MPI2_RAID_SCSI_IO_REQUEST *)
		  (io_req_base + offset);
		memset(cmd->io_request, 0,
		       sizeof(struct MPI2_RAID_SCSI_IO_REQUEST));
		cmd->io_request_phys_addr = io_req_base_phys + offset;

		list_add_tail(&cmd->list, &fusion->cmd_pool);
	}

	/*
	 * Create a frame pool and assign one frame to each cmd
	 */
	if (megasas_create_frame_pool_fusion(instance)) {
		printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
		megasas_free_cmds_fusion(instance);
		goto fail_req_desc;
	}

	return 0;

fail_cmd_list:
	pci_pool_free(fusion->io_request_frames_pool, fusion->io_request_frames,
		      fusion->io_request_frames_phys);
	pci_pool_destroy(fusion->io_request_frames_pool);
fail_io_frames:
	dma_free_coherent(&instance->pdev->dev, fusion->request_alloc_sz,
			  fusion->reply_frames_desc,
			  fusion->reply_frames_desc_phys);
	pci_pool_free(fusion->reply_frames_desc_pool,
		      fusion->reply_frames_desc,
		      fusion->reply_frames_desc_phys);
	pci_pool_destroy(fusion->reply_frames_desc_pool);

fail_reply_desc:
	dma_free_coherent(&instance->pdev->dev, fusion->request_alloc_sz,
			  fusion->req_frames_desc,
			  fusion->req_frames_desc_phys);
fail_req_desc:
	return -ENOMEM;
}

/**
 * wait_and_poll -	Issues a polling command
 * @instance:			Adapter soft state
 * @cmd:			Command packet to be issued
 *
 * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
 */
int
wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
	int i;
	struct megasas_header *frame_hdr = &cmd->frame->hdr;

	u32 msecs = MFI_POLL_TIMEOUT_SECS * 1000;

	/*
	 * Wait for cmd_status to change
	 */
	for (i = 0; (i < msecs) && (frame_hdr->cmd_status == 0xff); i += 20) {
		rmb();
		msleep(20);
	}

	if (frame_hdr->cmd_status == 0xff)
		return -ETIME;

	return 0;
}

/**
 * megasas_ioc_init_fusion -	Initializes the FW
 * @instance:		Adapter soft state
 *
 * Issues the IOC Init cmd
 */
int
megasas_ioc_init_fusion(struct megasas_instance *instance)
{
	struct megasas_init_frame *init_frame;
	struct MPI2_IOC_INIT_REQUEST *IOCInitMessage;
	dma_addr_t	ioc_init_handle;
	u32 context;
	struct megasas_cmd *cmd;
	u8 ret;
	struct fusion_context *fusion;
	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
	int i;
	struct megasas_header *frame_hdr;

	fusion = instance->ctrl_context;

	cmd = megasas_get_cmd(instance);

	if (!cmd) {
		printk(KERN_ERR "Could not allocate cmd for INIT Frame\n");
		ret = 1;
		goto fail_get_cmd;
	}

	IOCInitMessage =
	  dma_alloc_coherent(&instance->pdev->dev,
			     sizeof(struct MPI2_IOC_INIT_REQUEST),
			     &ioc_init_handle, GFP_KERNEL);

	if (!IOCInitMessage) {
		printk(KERN_ERR "Could not allocate memory for "
		       "IOCInitMessage\n");
		ret = 1;
		goto fail_fw_init;
	}

	memset(IOCInitMessage, 0, sizeof(struct MPI2_IOC_INIT_REQUEST));

	IOCInitMessage->Function = MPI2_FUNCTION_IOC_INIT;
	IOCInitMessage->WhoInit	= MPI2_WHOINIT_HOST_DRIVER;
	IOCInitMessage->MsgVersion = MPI2_VERSION;
	IOCInitMessage->HeaderVersion = MPI2_HEADER_VERSION;
	IOCInitMessage->SystemRequestFrameSize =
		MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE / 4;

	IOCInitMessage->ReplyDescriptorPostQueueDepth = fusion->reply_q_depth;
	IOCInitMessage->ReplyDescriptorPostQueueAddress	=
		fusion->reply_frames_desc_phys;
	IOCInitMessage->SystemRequestFrameBaseAddress =
		fusion->io_request_frames_phys;

	init_frame = (struct megasas_init_frame *)cmd->frame;
	memset(init_frame, 0, MEGAMFI_FRAME_SIZE);

	frame_hdr = &cmd->frame->hdr;
	context = init_frame->context;
	init_frame->context = context;

	frame_hdr->cmd_status = 0xFF;
	frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;

	init_frame->cmd	= MFI_CMD_INIT;
	init_frame->cmd_status = 0xFF;

	init_frame->queue_info_new_phys_addr_lo = ioc_init_handle;
	init_frame->data_xfer_len = sizeof(struct MPI2_IOC_INIT_REQUEST);

	req_desc =
	  (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)fusion->req_frames_desc;

	req_desc->Words = cmd->frame_phys_addr;
	req_desc->MFAIo.RequestFlags =
		(MEGASAS_REQ_DESCRIPT_FLAGS_MFA <<
		 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);

	/*
	 * disable the intr before firing the init frame
	 */
	instance->instancet->disable_intr(instance->reg_set);

	for (i = 0; i < (10 * 1000); i += 20) {
		if (readl(&instance->reg_set->doorbell) & 1)
			msleep(20);
		else
			break;
	}

	instance->instancet->fire_cmd(instance, req_desc->u.low,
				      req_desc->u.high, instance->reg_set);

	wait_and_poll(instance, cmd);

	frame_hdr = &cmd->frame->hdr;
	if (frame_hdr->cmd_status != 0) {
		ret = 1;
		goto fail_fw_init;
	}
	printk(KERN_ERR "megasas:IOC Init cmd success\n");

	ret = 0;

fail_fw_init:
	megasas_return_cmd(instance, cmd);
	if (IOCInitMessage)
		dma_free_coherent(&instance->pdev->dev,
				  sizeof(struct MPI2_IOC_INIT_REQUEST),
				  IOCInitMessage, ioc_init_handle);
fail_get_cmd:
	return ret;
}

/*
 * megasas_get_ld_map_info -	Returns FW's ld_map structure
 * @instance:				Adapter soft state
 * @pend:				Pend the command or not
 * Issues an internal command (DCMD) to get the FW's controller PD
 * list structure.  This information is mainly used to find out SYSTEM
 * supported by the FW.
 */
static int
megasas_get_ld_map_info(struct megasas_instance *instance)
{
	int ret = 0;
	struct megasas_cmd *cmd;
	struct megasas_dcmd_frame *dcmd;
	struct MR_FW_RAID_MAP_ALL *ci;
	dma_addr_t ci_h = 0;
	u32 size_map_info;
	struct fusion_context *fusion;

	cmd = megasas_get_cmd(instance);

	if (!cmd) {
		printk(KERN_DEBUG "megasas: Failed to get cmd for map info.\n");
		return -ENOMEM;
	}

	fusion = instance->ctrl_context;

	if (!fusion) {
		megasas_return_cmd(instance, cmd);
		return 1;
	}

	dcmd = &cmd->frame->dcmd;

	size_map_info = sizeof(struct MR_FW_RAID_MAP) +
		(sizeof(struct MR_LD_SPAN_MAP) *(MAX_LOGICAL_DRIVES - 1));

	ci = fusion->ld_map[(instance->map_id & 1)];
	ci_h = fusion->ld_map_phys[(instance->map_id & 1)];

	if (!ci) {
		printk(KERN_DEBUG "Failed to alloc mem for ld_map_info\n");
		megasas_return_cmd(instance, cmd);
		return -ENOMEM;
	}

	memset(ci, 0, sizeof(*ci));
	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);

	dcmd->cmd = MFI_CMD_DCMD;
	dcmd->cmd_status = 0xFF;
	dcmd->sge_count = 1;
	dcmd->flags = MFI_FRAME_DIR_READ;
	dcmd->timeout = 0;
	dcmd->pad_0 = 0;
	dcmd->data_xfer_len = size_map_info;
	dcmd->opcode = MR_DCMD_LD_MAP_GET_INFO;
	dcmd->sgl.sge32[0].phys_addr = ci_h;
	dcmd->sgl.sge32[0].length = size_map_info;

	if (!megasas_issue_polled(instance, cmd))
		ret = 0;
	else {
		printk(KERN_ERR "megasas: Get LD Map Info Failed\n");
		ret = -1;
	}

	megasas_return_cmd(instance, cmd);

	return ret;
}

u8
megasas_get_map_info(struct megasas_instance *instance)
{
	struct fusion_context *fusion = instance->ctrl_context;

	fusion->fast_path_io = 0;
	if (!megasas_get_ld_map_info(instance)) {
		if (MR_ValidateMapInfo(fusion->ld_map[(instance->map_id & 1)],
				       fusion->load_balance_info)) {
			fusion->fast_path_io = 1;
			return 0;
		}
	}
	return 1;
}

/*
 * megasas_sync_map_info -	Returns FW's ld_map structure
 * @instance:				Adapter soft state
 *
 * Issues an internal command (DCMD) to get the FW's controller PD
 * list structure.  This information is mainly used to find out SYSTEM
 * supported by the FW.
 */
int
megasas_sync_map_info(struct megasas_instance *instance)
{
	int ret = 0, i;
	struct megasas_cmd *cmd;
	struct megasas_dcmd_frame *dcmd;
	u32 size_sync_info, num_lds;
	struct fusion_context *fusion;
	struct MR_LD_TARGET_SYNC *ci = NULL;
	struct MR_FW_RAID_MAP_ALL *map;
	struct MR_LD_RAID  *raid;
	struct MR_LD_TARGET_SYNC *ld_sync;
	dma_addr_t ci_h = 0;
	u32 size_map_info;

	cmd = megasas_get_cmd(instance);

	if (!cmd) {
		printk(KERN_DEBUG "megasas: Failed to get cmd for sync"
		       "info.\n");
		return -ENOMEM;
	}

	fusion = instance->ctrl_context;

	if (!fusion) {
		megasas_return_cmd(instance, cmd);
		return 1;
	}

	map = fusion->ld_map[instance->map_id & 1];

	num_lds = map->raidMap.ldCount;

	dcmd = &cmd->frame->dcmd;

	size_sync_info = sizeof(struct MR_LD_TARGET_SYNC) *num_lds;

	memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);

	ci = (struct MR_LD_TARGET_SYNC *)
	  fusion->ld_map[(instance->map_id - 1) & 1];
	memset(ci, 0, sizeof(struct MR_FW_RAID_MAP_ALL));

	ci_h = fusion->ld_map_phys[(instance->map_id - 1) & 1];

	ld_sync = (struct MR_LD_TARGET_SYNC *)ci;

	for (i = 0; i < num_lds; i++, ld_sync++) {
		raid = MR_LdRaidGet(i, map);
		ld_sync->targetId = MR_GetLDTgtId(i, map);
		ld_sync->seqNum = raid->seqNum;
	}

	size_map_info = sizeof(struct MR_FW_RAID_MAP) +
		(sizeof(struct MR_LD_SPAN_MAP) *(MAX_LOGICAL_DRIVES - 1));

	dcmd->cmd = MFI_CMD_DCMD;
	dcmd->cmd_status = 0xFF;
	dcmd->sge_count = 1;
	dcmd->flags = MFI_FRAME_DIR_WRITE;
	dcmd->timeout = 0;
	dcmd->pad_0 = 0;
	dcmd->data_xfer_len = size_map_info;
	dcmd->mbox.b[0] = num_lds;
	dcmd->mbox.b[1] = MEGASAS_DCMD_MBOX_PEND_FLAG;
	dcmd->opcode = MR_DCMD_LD_MAP_GET_INFO;
	dcmd->sgl.sge32[0].phys_addr = ci_h;
	dcmd->sgl.sge32[0].length = size_map_info;

	instance->map_update_cmd = cmd;

	instance->instancet->issue_dcmd(instance, cmd);

	return ret;
}

/**
 * megasas_init_adapter_fusion -	Initializes the FW
 * @instance:		Adapter soft state
 *
 * This is the main function for initializing firmware.
 */
u32
megasas_init_adapter_fusion(struct megasas_instance *instance)
{
	struct megasas_register_set __iomem *reg_set;
	struct fusion_context *fusion;
	u32 max_cmd;
	int i = 0;

	fusion = instance->ctrl_context;

	reg_set = instance->reg_set;

	/*
	 * Get various operational parameters from status register
	 */
	instance->max_fw_cmds =
		instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
	instance->max_fw_cmds = min(instance->max_fw_cmds, (u16)1008);

	/*
	 * Reduce the max supported cmds by 1. This is to ensure that the
	 * reply_q_sz (1 more than the max cmd that driver may send)
	 * does not exceed max cmds that the FW can support
	 */
	instance->max_fw_cmds = instance->max_fw_cmds-1;
	/* Only internal cmds (DCMD) need to have MFI frames */
	instance->max_mfi_cmds = MEGASAS_INT_CMDS;

	max_cmd = instance->max_fw_cmds;

	fusion->reply_q_depth = ((max_cmd + 1 + 15)/16)*16;

	fusion->request_alloc_sz =
		sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) *max_cmd;
	fusion->reply_alloc_sz = sizeof(union MPI2_REPLY_DESCRIPTORS_UNION)
		*(fusion->reply_q_depth);
	fusion->io_frames_alloc_sz = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE +
		(MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE *
		 (max_cmd + 1)); /* Extra 1 for SMID 0 */

	fusion->max_sge_in_main_msg =
	  (MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE -
	   offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL))/16;

	fusion->max_sge_in_chain =
		MEGASAS_MAX_SZ_CHAIN_FRAME / sizeof(union MPI2_SGE_IO_UNION);

	instance->max_num_sge = fusion->max_sge_in_main_msg +
		fusion->max_sge_in_chain - 2;

	/* Used for pass thru MFI frame (DCMD) */
	fusion->chain_offset_mfi_pthru =
		offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL)/16;

	fusion->chain_offset_io_request =
		(MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE -
		 sizeof(union MPI2_SGE_IO_UNION))/16;

	fusion->last_reply_idx = 0;

	/*
	 * Allocate memory for descriptors
	 * Create a pool of commands
	 */
	if (megasas_alloc_cmds(instance))
		goto fail_alloc_mfi_cmds;
	if (megasas_alloc_cmds_fusion(instance))
		goto fail_alloc_cmds;

	if (megasas_ioc_init_fusion(instance))
		goto fail_ioc_init;

	instance->flag_ieee = 1;

	fusion->map_sz =  sizeof(struct MR_FW_RAID_MAP) +
	  (sizeof(struct MR_LD_SPAN_MAP) *(MAX_LOGICAL_DRIVES - 1));

	fusion->fast_path_io = 0;

	for (i = 0; i < 2; i++) {
		fusion->ld_map[i] = dma_alloc_coherent(&instance->pdev->dev,
						       fusion->map_sz,
						       &fusion->ld_map_phys[i],
						       GFP_KERNEL);
		if (!fusion->ld_map[i]) {
			printk(KERN_ERR "megasas: Could not allocate memory "
			       "for map info\n");
			goto fail_map_info;
		}
	}

	if (!megasas_get_map_info(instance))
		megasas_sync_map_info(instance);

	return 0;

fail_map_info:
	if (i == 1)
		dma_free_coherent(&instance->pdev->dev, fusion->map_sz,
				  fusion->ld_map[0], fusion->ld_map_phys[0]);
fail_ioc_init:
979 980 981 982
	megasas_free_cmds_fusion(instance);
fail_alloc_cmds:
	megasas_free_cmds(instance);
fail_alloc_mfi_cmds:
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
	return 1;
}

/**
 * megasas_fire_cmd_fusion -	Sends command to the FW
 * @frame_phys_addr :		Physical address of cmd
 * @frame_count :		Number of frames for the command
 * @regs :			MFI register set
 */
void
megasas_fire_cmd_fusion(struct megasas_instance *instance,
			dma_addr_t req_desc_lo,
			u32 req_desc_hi,
			struct megasas_register_set __iomem *regs)
{
	unsigned long flags;

	spin_lock_irqsave(&instance->hba_lock, flags);

	writel(req_desc_lo,
	       &(regs)->inbound_low_queue_port);
	writel(req_desc_hi, &(regs)->inbound_high_queue_port);
	spin_unlock_irqrestore(&instance->hba_lock, flags);
}

/**
 * map_cmd_status -	Maps FW cmd status to OS cmd status
 * @cmd :		Pointer to cmd
 * @status :		status of cmd returned by FW
 * @ext_status :	ext status of cmd returned by FW
 */

void
map_cmd_status(struct megasas_cmd_fusion *cmd, u8 status, u8 ext_status)
{

	switch (status) {

	case MFI_STAT_OK:
		cmd->scmd->result = DID_OK << 16;
		break;

	case MFI_STAT_SCSI_IO_FAILED:
	case MFI_STAT_LD_INIT_IN_PROGRESS:
		cmd->scmd->result = (DID_ERROR << 16) | ext_status;
		break;

	case MFI_STAT_SCSI_DONE_WITH_ERROR:

		cmd->scmd->result = (DID_OK << 16) | ext_status;
		if (ext_status == SAM_STAT_CHECK_CONDITION) {
			memset(cmd->scmd->sense_buffer, 0,
			       SCSI_SENSE_BUFFERSIZE);
			memcpy(cmd->scmd->sense_buffer, cmd->sense,
			       SCSI_SENSE_BUFFERSIZE);
			cmd->scmd->result |= DRIVER_SENSE << 24;
		}
		break;

	case MFI_STAT_LD_OFFLINE:
	case MFI_STAT_DEVICE_NOT_FOUND:
		cmd->scmd->result = DID_BAD_TARGET << 16;
		break;

	default:
		printk(KERN_DEBUG "megasas: FW status %#x\n", status);
		cmd->scmd->result = DID_ERROR << 16;
		break;
	}
}

/**
 * megasas_make_sgl_fusion -	Prepares 32-bit SGL
 * @instance:		Adapter soft state
 * @scp:		SCSI command from the mid-layer
 * @sgl_ptr:		SGL to be filled in
 * @cmd:		cmd we are working on
 *
 * If successful, this function returns the number of SG elements.
 */
static int
megasas_make_sgl_fusion(struct megasas_instance *instance,
			struct scsi_cmnd *scp,
			struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr,
			struct megasas_cmd_fusion *cmd)
{
	int i, sg_processed;
	int sge_count, sge_idx;
	struct scatterlist *os_sgl;
	struct fusion_context *fusion;

	fusion = instance->ctrl_context;

	cmd->io_request->ChainOffset = 0;

	sge_count = scsi_dma_map(scp);

	BUG_ON(sge_count < 0);

	if (sge_count > instance->max_num_sge || !sge_count)
		return sge_count;

	if (sge_count > fusion->max_sge_in_main_msg) {
		/* One element to store the chain info */
		sge_idx = fusion->max_sge_in_main_msg - 1;
	} else
		sge_idx = sge_count;

	scsi_for_each_sg(scp, os_sgl, sge_count, i) {
		sgl_ptr->Length = sg_dma_len(os_sgl);
		sgl_ptr->Address = sg_dma_address(os_sgl);
		sgl_ptr->Flags = 0;
		sgl_ptr++;

		sg_processed = i + 1;

		if ((sg_processed ==  (fusion->max_sge_in_main_msg - 1)) &&
		    (sge_count > fusion->max_sge_in_main_msg)) {

			struct MPI25_IEEE_SGE_CHAIN64 *sg_chain;
			cmd->io_request->ChainOffset =
				fusion->chain_offset_io_request;
			sg_chain = sgl_ptr;
			/* Prepare chain element */
			sg_chain->NextChainOffset = 0;
			sg_chain->Flags = (IEEE_SGE_FLAGS_CHAIN_ELEMENT |
					   MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR);
			sg_chain->Length =  (sizeof(union MPI2_SGE_IO_UNION)
					     *(sge_count - sg_processed));
			sg_chain->Address = cmd->sg_frame_phys_addr;

			sgl_ptr =
			  (struct MPI25_IEEE_SGE_CHAIN64 *)cmd->sg_frame;
		}
	}

	return sge_count;
}

/**
 * megasas_set_pd_lba -	Sets PD LBA
 * @cdb:		CDB
 * @cdb_len:		cdb length
 * @start_blk:		Start block of IO
 *
 * Used to set the PD LBA in CDB for FP IOs
 */
void
megasas_set_pd_lba(struct MPI2_RAID_SCSI_IO_REQUEST *io_request, u8 cdb_len,
		   struct IO_REQUEST_INFO *io_info, struct scsi_cmnd *scp,
		   struct MR_FW_RAID_MAP_ALL *local_map_ptr, u32 ref_tag)
{
	struct MR_LD_RAID *raid;
	u32 ld;
	u64 start_blk = io_info->pdBlock;
	u8 *cdb = io_request->CDB.CDB32;
	u32 num_blocks = io_info->numBlocks;
	u8 opcode, flagvals, groupnum, control;

	/* Check if T10 PI (DIF) is enabled for this LD */
	ld = MR_TargetIdToLdGet(io_info->ldTgtId, local_map_ptr);
	raid = MR_LdRaidGet(ld, local_map_ptr);
	if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER) {
		memset(cdb, 0, sizeof(io_request->CDB.CDB32));
		cdb[0] =  MEGASAS_SCSI_VARIABLE_LENGTH_CMD;
		cdb[7] =  MEGASAS_SCSI_ADDL_CDB_LEN;

		if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
			cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_READ32;
		else
			cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_WRITE32;
		cdb[10] = MEGASAS_RD_WR_PROTECT_CHECK_ALL;

		/* LBA */
		cdb[12] = (u8)((start_blk >> 56) & 0xff);
		cdb[13] = (u8)((start_blk >> 48) & 0xff);
		cdb[14] = (u8)((start_blk >> 40) & 0xff);
		cdb[15] = (u8)((start_blk >> 32) & 0xff);
		cdb[16] = (u8)((start_blk >> 24) & 0xff);
		cdb[17] = (u8)((start_blk >> 16) & 0xff);
		cdb[18] = (u8)((start_blk >> 8) & 0xff);
		cdb[19] = (u8)(start_blk & 0xff);

		/* Logical block reference tag */
		io_request->CDB.EEDP32.PrimaryReferenceTag =
			cpu_to_be32(ref_tag);
		io_request->CDB.EEDP32.PrimaryApplicationTagMask = 0xffff;

		io_request->DataLength = num_blocks * 512;
		io_request->IoFlags = 32; /* Specify 32-byte cdb */

		/* Transfer length */
		cdb[28] = (u8)((num_blocks >> 24) & 0xff);
		cdb[29] = (u8)((num_blocks >> 16) & 0xff);
		cdb[30] = (u8)((num_blocks >> 8) & 0xff);
		cdb[31] = (u8)(num_blocks & 0xff);

		/* set SCSI IO EEDPFlags */
		if (scp->sc_data_direction == PCI_DMA_FROMDEVICE) {
			io_request->EEDPFlags =
				MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG  |
				MPI2_SCSIIO_EEDPFLAGS_CHECK_REFTAG |
				MPI2_SCSIIO_EEDPFLAGS_CHECK_REMOVE_OP |
				MPI2_SCSIIO_EEDPFLAGS_CHECK_APPTAG |
				MPI2_SCSIIO_EEDPFLAGS_CHECK_GUARD;
		} else {
			io_request->EEDPFlags =
				MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG |
				MPI2_SCSIIO_EEDPFLAGS_INSERT_OP;
		}
		io_request->Control |= (0x4 << 26);
		io_request->EEDPBlockSize = MEGASAS_EEDPBLOCKSIZE;
	} else {
		/* Some drives don't support 16/12 byte CDB's, convert to 10 */
		if (((cdb_len == 12) || (cdb_len == 16)) &&
		    (start_blk <= 0xffffffff)) {
			if (cdb_len == 16) {
				opcode = cdb[0] == READ_16 ? READ_10 : WRITE_10;
				flagvals = cdb[1];
				groupnum = cdb[14];
				control = cdb[15];
			} else {
				opcode = cdb[0] == READ_12 ? READ_10 : WRITE_10;
				flagvals = cdb[1];
				groupnum = cdb[10];
				control = cdb[11];
			}

			memset(cdb, 0, sizeof(io_request->CDB.CDB32));

			cdb[0] = opcode;
			cdb[1] = flagvals;
			cdb[6] = groupnum;
			cdb[9] = control;

			/* Transfer length */
			cdb[8] = (u8)(num_blocks & 0xff);
			cdb[7] = (u8)((num_blocks >> 8) & 0xff);

			cdb_len = 10;
		}

		/* Normal case, just load LBA here */
		switch (cdb_len) {
		case 6:
		{
			u8 val = cdb[1] & 0xE0;
			cdb[3] = (u8)(start_blk & 0xff);
			cdb[2] = (u8)((start_blk >> 8) & 0xff);
			cdb[1] = val | ((u8)(start_blk >> 16) & 0x1f);
			break;
		}
		case 10:
			cdb[5] = (u8)(start_blk & 0xff);
			cdb[4] = (u8)((start_blk >> 8) & 0xff);
			cdb[3] = (u8)((start_blk >> 16) & 0xff);
			cdb[2] = (u8)((start_blk >> 24) & 0xff);
			break;
		case 12:
			cdb[5]    = (u8)(start_blk & 0xff);
			cdb[4]    = (u8)((start_blk >> 8) & 0xff);
			cdb[3]    = (u8)((start_blk >> 16) & 0xff);
			cdb[2]    = (u8)((start_blk >> 24) & 0xff);
			break;
		case 16:
			cdb[9]    = (u8)(start_blk & 0xff);
			cdb[8]    = (u8)((start_blk >> 8) & 0xff);
			cdb[7]    = (u8)((start_blk >> 16) & 0xff);
			cdb[6]    = (u8)((start_blk >> 24) & 0xff);
			cdb[5]    = (u8)((start_blk >> 32) & 0xff);
			cdb[4]    = (u8)((start_blk >> 40) & 0xff);
			cdb[3]    = (u8)((start_blk >> 48) & 0xff);
			cdb[2]    = (u8)((start_blk >> 56) & 0xff);
			break;
		}
	}
}

/**
 * megasas_build_ldio_fusion -	Prepares IOs to devices
 * @instance:		Adapter soft state
 * @scp:		SCSI command
 * @cmd:		Command to be prepared
 *
 * Prepares the io_request and chain elements (sg_frame) for IO
 * The IO can be for PD (Fast Path) or LD
 */
void
megasas_build_ldio_fusion(struct megasas_instance *instance,
			  struct scsi_cmnd *scp,
			  struct megasas_cmd_fusion *cmd)
{
	u8 fp_possible;
	u32 start_lba_lo, start_lba_hi, device_id;
	struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
	struct IO_REQUEST_INFO io_info;
	struct fusion_context *fusion;
	struct MR_FW_RAID_MAP_ALL *local_map_ptr;

	device_id = MEGASAS_DEV_INDEX(instance, scp);

	fusion = instance->ctrl_context;

	io_request = cmd->io_request;
	io_request->RaidContext.VirtualDiskTgtId = device_id;
	io_request->RaidContext.status = 0;
	io_request->RaidContext.exStatus = 0;

	req_desc = (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)cmd->request_desc;

	start_lba_lo = 0;
	start_lba_hi = 0;
	fp_possible = 0;

	/*
	 * 6-byte READ(0x08) or WRITE(0x0A) cdb
	 */
	if (scp->cmd_len == 6) {
		io_request->DataLength = (u32) scp->cmnd[4];
		start_lba_lo = ((u32) scp->cmnd[1] << 16) |
			((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];

		start_lba_lo &= 0x1FFFFF;
	}

	/*
	 * 10-byte READ(0x28) or WRITE(0x2A) cdb
	 */
	else if (scp->cmd_len == 10) {
		io_request->DataLength = (u32) scp->cmnd[8] |
			((u32) scp->cmnd[7] << 8);
		start_lba_lo = ((u32) scp->cmnd[2] << 24) |
			((u32) scp->cmnd[3] << 16) |
			((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
	}

	/*
	 * 12-byte READ(0xA8) or WRITE(0xAA) cdb
	 */
	else if (scp->cmd_len == 12) {
		io_request->DataLength = ((u32) scp->cmnd[6] << 24) |
			((u32) scp->cmnd[7] << 16) |
			((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
		start_lba_lo = ((u32) scp->cmnd[2] << 24) |
			((u32) scp->cmnd[3] << 16) |
			((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
	}

	/*
	 * 16-byte READ(0x88) or WRITE(0x8A) cdb
	 */
	else if (scp->cmd_len == 16) {
		io_request->DataLength = ((u32) scp->cmnd[10] << 24) |
			((u32) scp->cmnd[11] << 16) |
			((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
		start_lba_lo = ((u32) scp->cmnd[6] << 24) |
			((u32) scp->cmnd[7] << 16) |
			((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];

		start_lba_hi = ((u32) scp->cmnd[2] << 24) |
			((u32) scp->cmnd[3] << 16) |
			((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
	}

	memset(&io_info, 0, sizeof(struct IO_REQUEST_INFO));
	io_info.ldStartBlock = ((u64)start_lba_hi << 32) | start_lba_lo;
	io_info.numBlocks = io_request->DataLength;
	io_info.ldTgtId = device_id;

	if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
		io_info.isRead = 1;

	local_map_ptr = fusion->ld_map[(instance->map_id & 1)];

	if ((MR_TargetIdToLdGet(device_id, local_map_ptr) >=
	     MAX_LOGICAL_DRIVES) || (!fusion->fast_path_io)) {
		io_request->RaidContext.regLockFlags  = 0;
		fp_possible = 0;
	} else {
		if (MR_BuildRaidContext(&io_info, &io_request->RaidContext,
					local_map_ptr))
			fp_possible = io_info.fpOkForIo;
	}

	if (fp_possible) {
		megasas_set_pd_lba(io_request, scp->cmd_len, &io_info, scp,
				   local_map_ptr, start_lba_lo);
		io_request->DataLength = scsi_bufflen(scp);
		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
		cmd->request_desc->SCSIIO.RequestFlags =
			(MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY
			 << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
		if ((fusion->load_balance_info[device_id].loadBalanceFlag) &&
		    (io_info.isRead)) {
			io_info.devHandle =
				get_updated_dev_handle(
					&fusion->load_balance_info[device_id],
					&io_info);
			scp->SCp.Status |= MEGASAS_LOAD_BALANCE_FLAG;
		} else
			scp->SCp.Status &= ~MEGASAS_LOAD_BALANCE_FLAG;
		cmd->request_desc->SCSIIO.DevHandle = io_info.devHandle;
		io_request->DevHandle = io_info.devHandle;
	} else {
		io_request->RaidContext.timeoutValue =
			local_map_ptr->raidMap.fpPdIoTimeoutSec;
		io_request->Function = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
		io_request->DevHandle = device_id;
		cmd->request_desc->SCSIIO.RequestFlags =
			(MEGASAS_REQ_DESCRIPT_FLAGS_LD_IO
			 << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
	} /* Not FP */
}

/**
 * megasas_build_dcdb_fusion -	Prepares IOs to devices
 * @instance:		Adapter soft state
 * @scp:		SCSI command
 * @cmd:		Command to be prepared
 *
 * Prepares the io_request frame for non-io cmds
 */
static void
megasas_build_dcdb_fusion(struct megasas_instance *instance,
			  struct scsi_cmnd *scmd,
			  struct megasas_cmd_fusion *cmd)
{
	u32 device_id;
	struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
	u16 pd_index = 0;
	struct MR_FW_RAID_MAP_ALL *local_map_ptr;
	struct fusion_context *fusion = instance->ctrl_context;

	io_request = cmd->io_request;
	device_id = MEGASAS_DEV_INDEX(instance, scmd);
	pd_index = (scmd->device->channel * MEGASAS_MAX_DEV_PER_CHANNEL)
		+scmd->device->id;
	local_map_ptr = fusion->ld_map[(instance->map_id & 1)];

	/* Check if this is a system PD I/O */
1424
	if (instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) {
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
		io_request->Function = 0;
		io_request->DevHandle =
			local_map_ptr->raidMap.devHndlInfo[device_id].curDevHdl;
		io_request->RaidContext.timeoutValue =
			local_map_ptr->raidMap.fpPdIoTimeoutSec;
		io_request->RaidContext.regLockFlags = 0;
		io_request->RaidContext.regLockRowLBA = 0;
		io_request->RaidContext.regLockLength = 0;
		io_request->RaidContext.RAIDFlags =
			MR_RAID_FLAGS_IO_SUB_TYPE_SYSTEM_PD <<
			MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT;
		cmd->request_desc->SCSIIO.RequestFlags =
			(MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY <<
			 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
	} else {
		io_request->Function  = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
		io_request->DevHandle = device_id;
		cmd->request_desc->SCSIIO.RequestFlags =
			(MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
			 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
	}
	io_request->RaidContext.VirtualDiskTgtId = device_id;
1447
	io_request->LUN[1] = scmd->device->lun;
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
	io_request->DataLength = scsi_bufflen(scmd);
}

/**
 * megasas_build_io_fusion -	Prepares IOs to devices
 * @instance:		Adapter soft state
 * @scp:		SCSI command
 * @cmd:		Command to be prepared
 *
 * Invokes helper functions to prepare request frames
 * and sets flags appropriate for IO/Non-IO cmd
 */
int
megasas_build_io_fusion(struct megasas_instance *instance,
			struct scsi_cmnd *scp,
			struct megasas_cmd_fusion *cmd)
{
	u32 device_id, sge_count;
	struct MPI2_RAID_SCSI_IO_REQUEST *io_request = cmd->io_request;

	device_id = MEGASAS_DEV_INDEX(instance, scp);

	/* Zero out some fields so they don't get reused */
1471
	io_request->LUN[1] = 0;
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
	io_request->CDB.EEDP32.PrimaryReferenceTag = 0;
	io_request->CDB.EEDP32.PrimaryApplicationTagMask = 0;
	io_request->EEDPFlags = 0;
	io_request->Control = 0;
	io_request->EEDPBlockSize = 0;
	io_request->IoFlags = 0;
	io_request->RaidContext.RAIDFlags = 0;

	memcpy(io_request->CDB.CDB32, scp->cmnd, scp->cmd_len);
	/*
	 * Just the CDB length,rest of the Flags are zero
	 * This will be modified for FP in build_ldio_fusion
	 */
	io_request->IoFlags = scp->cmd_len;

	if (megasas_is_ldio(scp))
		megasas_build_ldio_fusion(instance, scp, cmd);
	else
		megasas_build_dcdb_fusion(instance, scp, cmd);

	/*
	 * Construct SGL
	 */

	sge_count =
		megasas_make_sgl_fusion(instance, scp,
					(struct MPI25_IEEE_SGE_CHAIN64 *)
					&io_request->SGL, cmd);

	if (sge_count > instance->max_num_sge) {
		printk(KERN_ERR "megasas: Error. sge_count (0x%x) exceeds "
		       "max (0x%x) allowed\n", sge_count,
		       instance->max_num_sge);
		return 1;
	}

	io_request->RaidContext.numSGE = sge_count;

	io_request->SGLFlags = MPI2_SGE_FLAGS_64_BIT_ADDRESSING;

	if (scp->sc_data_direction == PCI_DMA_TODEVICE)
		io_request->Control |= MPI2_SCSIIO_CONTROL_WRITE;
	else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
		io_request->Control |= MPI2_SCSIIO_CONTROL_READ;

	io_request->SGLOffset0 =
		offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL) / 4;

	io_request->SenseBufferLowAddress = cmd->sense_phys_addr;
	io_request->SenseBufferLength = SCSI_SENSE_BUFFERSIZE;

	cmd->scmd = scp;
	scp->SCp.ptr = (char *)cmd;

	return 0;
}

union MEGASAS_REQUEST_DESCRIPTOR_UNION *
megasas_get_request_descriptor(struct megasas_instance *instance, u16 index)
{
	u8 *p;
	struct fusion_context *fusion;

	if (index >= instance->max_fw_cmds) {
		printk(KERN_ERR "megasas: Invalid SMID (0x%x)request for "
		       "descriptor\n", index);
		return NULL;
	}
	fusion = instance->ctrl_context;
	p = fusion->req_frames_desc
		+sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) *index;

	return (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)p;
}

/**
 * megasas_build_and_issue_cmd_fusion -Main routine for building and
 *                                     issuing non IOCTL cmd
 * @instance:			Adapter soft state
 * @scmd:			pointer to scsi cmd from OS
 */
static u32
megasas_build_and_issue_cmd_fusion(struct megasas_instance *instance,
				   struct scsi_cmnd *scmd)
{
	struct megasas_cmd_fusion *cmd;
	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
	u32 index;
	struct fusion_context *fusion;

	fusion = instance->ctrl_context;

	cmd = megasas_get_cmd_fusion(instance);
	if (!cmd)
		return SCSI_MLQUEUE_HOST_BUSY;

	index = cmd->index;

	req_desc = megasas_get_request_descriptor(instance, index-1);
	if (!req_desc)
		return 1;

	req_desc->Words = 0;
	cmd->request_desc = req_desc;
	cmd->request_desc->Words = 0;

	if (megasas_build_io_fusion(instance, scmd, cmd)) {
		megasas_return_cmd_fusion(instance, cmd);
		printk(KERN_ERR "megasas: Error building command.\n");
		cmd->request_desc = NULL;
		return 1;
	}

	req_desc = cmd->request_desc;
	req_desc->SCSIIO.SMID = index;

	if (cmd->io_request->ChainOffset != 0 &&
	    cmd->io_request->ChainOffset != 0xF)
		printk(KERN_ERR "megasas: The chain offset value is not "
		       "correct : %x\n", cmd->io_request->ChainOffset);

	/*
	 * Issue the command to the FW
	 */
	atomic_inc(&instance->fw_outstanding);

	instance->instancet->fire_cmd(instance,
				      req_desc->u.low, req_desc->u.high,
				      instance->reg_set);

	return 0;
}

/**
 * complete_cmd_fusion -	Completes command
 * @instance:			Adapter soft state
 * Completes all commands that is in reply descriptor queue
 */
int
complete_cmd_fusion(struct megasas_instance *instance)
{
	union MPI2_REPLY_DESCRIPTORS_UNION *desc;
	struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *reply_desc;
	struct MPI2_RAID_SCSI_IO_REQUEST *scsi_io_req;
	struct fusion_context *fusion;
	struct megasas_cmd *cmd_mfi;
	struct megasas_cmd_fusion *cmd_fusion;
	u16 smid, num_completed;
	u8 reply_descript_type, arm;
	u32 status, extStatus, device_id;
	union desc_value d_val;
	struct LD_LOAD_BALANCE_INFO *lbinfo;

	fusion = instance->ctrl_context;

	if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
		return IRQ_HANDLED;

	desc = fusion->reply_frames_desc;
	desc += fusion->last_reply_idx;

	reply_desc = (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;

	d_val.word = desc->Words;

	reply_descript_type = reply_desc->ReplyFlags &
		MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;

	if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
		return IRQ_NONE;

	d_val.word = desc->Words;

	num_completed = 0;

	while ((d_val.u.low != UINT_MAX) && (d_val.u.high != UINT_MAX)) {
		smid = reply_desc->SMID;

		cmd_fusion = fusion->cmd_list[smid - 1];

		scsi_io_req =
			(struct MPI2_RAID_SCSI_IO_REQUEST *)
		  cmd_fusion->io_request;

		if (cmd_fusion->scmd)
			cmd_fusion->scmd->SCp.ptr = NULL;

		status = scsi_io_req->RaidContext.status;
		extStatus = scsi_io_req->RaidContext.exStatus;

		switch (scsi_io_req->Function) {
		case MPI2_FUNCTION_SCSI_IO_REQUEST:  /*Fast Path IO.*/
			/* Update load balancing info */
			device_id = MEGASAS_DEV_INDEX(instance,
						      cmd_fusion->scmd);
			lbinfo = &fusion->load_balance_info[device_id];
			if (cmd_fusion->scmd->SCp.Status &
			    MEGASAS_LOAD_BALANCE_FLAG) {
				arm = lbinfo->raid1DevHandle[0] ==
					cmd_fusion->io_request->DevHandle ? 0 :
					1;
				atomic_dec(&lbinfo->scsi_pending_cmds[arm]);
				cmd_fusion->scmd->SCp.Status &=
					~MEGASAS_LOAD_BALANCE_FLAG;
			}
			if (reply_descript_type ==
			    MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS) {
				if (megasas_dbg_lvl == 5)
					printk(KERN_ERR "\nmegasas: FAST Path "
					       "IO Success\n");
			}
			/* Fall thru and complete IO */
		case MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST: /* LD-IO Path */
			/* Map the FW Cmd Status */
			map_cmd_status(cmd_fusion, status, extStatus);
			scsi_dma_unmap(cmd_fusion->scmd);
			cmd_fusion->scmd->scsi_done(cmd_fusion->scmd);
			scsi_io_req->RaidContext.status = 0;
			scsi_io_req->RaidContext.exStatus = 0;
			megasas_return_cmd_fusion(instance, cmd_fusion);
			atomic_dec(&instance->fw_outstanding);

			break;
		case MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST: /*MFI command */
			cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
			megasas_complete_cmd(instance, cmd_mfi, DID_OK);
			cmd_fusion->flags = 0;
			megasas_return_cmd_fusion(instance, cmd_fusion);

			break;
		}

		fusion->last_reply_idx++;
		if (fusion->last_reply_idx >= fusion->reply_q_depth)
			fusion->last_reply_idx = 0;

		desc->Words = ULLONG_MAX;
		num_completed++;

		/* Get the next reply descriptor */
		if (!fusion->last_reply_idx)
			desc = fusion->reply_frames_desc;
		else
			desc++;

		reply_desc =
		  (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;

		d_val.word = desc->Words;

		reply_descript_type = reply_desc->ReplyFlags &
			MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;

		if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
			break;
	}

	if (!num_completed)
		return IRQ_NONE;

	wmb();
	writel(fusion->last_reply_idx,
	       &instance->reg_set->reply_post_host_index);
1735
	megasas_check_and_restore_queue_depth(instance);
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
	return IRQ_HANDLED;
}

/**
 * megasas_complete_cmd_dpc_fusion -	Completes command
 * @instance:			Adapter soft state
 *
 * Tasklet to complete cmds
 */
void
megasas_complete_cmd_dpc_fusion(unsigned long instance_addr)
{
	struct megasas_instance *instance =
		(struct megasas_instance *)instance_addr;
	unsigned long flags;

	/* If we have already declared adapter dead, donot complete cmds */
	spin_lock_irqsave(&instance->hba_lock, flags);
	if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
		spin_unlock_irqrestore(&instance->hba_lock, flags);
		return;
	}
	spin_unlock_irqrestore(&instance->hba_lock, flags);

	spin_lock_irqsave(&instance->completion_lock, flags);
	complete_cmd_fusion(instance);
	spin_unlock_irqrestore(&instance->completion_lock, flags);
}

/**
 * megasas_isr_fusion - isr entry point
 */
irqreturn_t megasas_isr_fusion(int irq, void *devp)
{
	struct megasas_instance *instance = (struct megasas_instance *)devp;
	u32 mfiStatus, fw_state;

	if (!instance->msi_flag) {
		mfiStatus = instance->instancet->clear_intr(instance->reg_set);
		if (!mfiStatus)
			return IRQ_NONE;
	}

	/* If we are resetting, bail */
	if (test_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags))
		return IRQ_HANDLED;

	if (!complete_cmd_fusion(instance)) {
		/* If we didn't complete any commands, check for FW fault */
		fw_state = instance->instancet->read_fw_status_reg(
			instance->reg_set) & MFI_STATE_MASK;
		if (fw_state == MFI_STATE_FAULT)
			schedule_work(&instance->work_init);
	}

	return IRQ_HANDLED;
}

/**
 * build_mpt_mfi_pass_thru - builds a cmd fo MFI Pass thru
 * @instance:			Adapter soft state
 * mfi_cmd:			megasas_cmd pointer
 *
 */
u8
build_mpt_mfi_pass_thru(struct megasas_instance *instance,
			struct megasas_cmd *mfi_cmd)
{
	struct MPI25_IEEE_SGE_CHAIN64 *mpi25_ieee_chain;
	struct MPI2_RAID_SCSI_IO_REQUEST *io_req;
	struct megasas_cmd_fusion *cmd;
	struct fusion_context *fusion;
	struct megasas_header *frame_hdr = &mfi_cmd->frame->hdr;

	cmd = megasas_get_cmd_fusion(instance);
	if (!cmd)
		return 1;

	/*  Save the smid. To be used for returning the cmd */
	mfi_cmd->context.smid = cmd->index;

	cmd->sync_cmd_idx = mfi_cmd->index;

	/*
	 * For cmds where the flag is set, store the flag and check
	 * on completion. For cmds with this flag, don't call
	 * megasas_complete_cmd
	 */

	if (frame_hdr->flags & MFI_FRAME_DONT_POST_IN_REPLY_QUEUE)
		cmd->flags = MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;

	fusion = instance->ctrl_context;
	io_req = cmd->io_request;
	mpi25_ieee_chain =
	  (struct MPI25_IEEE_SGE_CHAIN64 *)&io_req->SGL.IeeeChain;

	io_req->Function    = MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST;
	io_req->SGLOffset0  = offsetof(struct MPI2_RAID_SCSI_IO_REQUEST,
				       SGL) / 4;
	io_req->ChainOffset = fusion->chain_offset_mfi_pthru;

	mpi25_ieee_chain->Address = mfi_cmd->frame_phys_addr;

	mpi25_ieee_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
		MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR;

	mpi25_ieee_chain->Length = MEGASAS_MAX_SZ_CHAIN_FRAME;

	return 0;
}

/**
 * build_mpt_cmd - Calls helper function to build a cmd MFI Pass thru cmd
 * @instance:			Adapter soft state
 * @cmd:			mfi cmd to build
 *
 */
union MEGASAS_REQUEST_DESCRIPTOR_UNION *
build_mpt_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
{
	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
	u16 index;

	if (build_mpt_mfi_pass_thru(instance, cmd)) {
		printk(KERN_ERR "Couldn't build MFI pass thru cmd\n");
		return NULL;
	}

	index = cmd->context.smid;

	req_desc = megasas_get_request_descriptor(instance, index - 1);

	if (!req_desc)
		return NULL;

	req_desc->Words = 0;
	req_desc->SCSIIO.RequestFlags = (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
					 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);

	req_desc->SCSIIO.SMID = index;

	return req_desc;
}

/**
 * megasas_issue_dcmd_fusion - Issues a MFI Pass thru cmd
 * @instance:			Adapter soft state
 * @cmd:			mfi cmd pointer
 *
 */
void
megasas_issue_dcmd_fusion(struct megasas_instance *instance,
			  struct megasas_cmd *cmd)
{
	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
	union desc_value d_val;

	req_desc = build_mpt_cmd(instance, cmd);
	if (!req_desc) {
		printk(KERN_ERR "Couldn't issue MFI pass thru cmd\n");
		return;
	}
	d_val.word = req_desc->Words;

	instance->instancet->fire_cmd(instance, req_desc->u.low,
				      req_desc->u.high, instance->reg_set);
}

/**
 * megasas_release_fusion -	Reverses the FW initialization
 * @intance:			Adapter soft state
 */
void
megasas_release_fusion(struct megasas_instance *instance)
{
	megasas_free_cmds(instance);
	megasas_free_cmds_fusion(instance);

	iounmap(instance->reg_set);

	pci_release_selected_regions(instance->pdev, instance->bar);
}

/**
 * megasas_read_fw_status_reg_fusion - returns the current FW status value
 * @regs:			MFI register set
 */
static u32
megasas_read_fw_status_reg_fusion(struct megasas_register_set __iomem *regs)
{
	return readl(&(regs)->outbound_scratch_pad);
}

/**
 * megasas_adp_reset_fusion -	For controller reset
 * @regs:				MFI register set
 */
static int
megasas_adp_reset_fusion(struct megasas_instance *instance,
			 struct megasas_register_set __iomem *regs)
{
	return 0;
}

/**
 * megasas_check_reset_fusion -	For controller reset check
 * @regs:				MFI register set
 */
static int
megasas_check_reset_fusion(struct megasas_instance *instance,
			   struct megasas_register_set __iomem *regs)
{
	return 0;
}

/* This function waits for outstanding commands on fusion to complete */
int megasas_wait_for_outstanding_fusion(struct megasas_instance *instance)
{
	int i, outstanding, retval = 0;
	u32 fw_state, wait_time = MEGASAS_RESET_WAIT_TIME;

	for (i = 0; i < wait_time; i++) {
		/* Check if firmware is in fault state */
		fw_state = instance->instancet->read_fw_status_reg(
			instance->reg_set) & MFI_STATE_MASK;
		if (fw_state == MFI_STATE_FAULT) {
			printk(KERN_WARNING "megasas: Found FW in FAULT state,"
			       " will reset adapter.\n");
			retval = 1;
			goto out;
		}

		outstanding = atomic_read(&instance->fw_outstanding);
		if (!outstanding)
			goto out;

		if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
			printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
			       "commands to complete\n", i, outstanding);
			megasas_complete_cmd_dpc_fusion(
				(unsigned long)instance);
		}
		msleep(1000);
	}

	if (atomic_read(&instance->fw_outstanding)) {
		printk("megaraid_sas: pending commands remain after waiting, "
		       "will reset adapter.\n");
		retval = 1;
	}
out:
	return retval;
}

void  megasas_reset_reply_desc(struct megasas_instance *instance)
{
	int i;
	struct fusion_context *fusion;
	union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;

	fusion = instance->ctrl_context;
	fusion->last_reply_idx = 0;
	reply_desc = fusion->reply_frames_desc;
	for (i = 0 ; i < fusion->reply_q_depth; i++, reply_desc++)
		reply_desc->Words = ULLONG_MAX;
}

/* Core fusion reset function */
int megasas_reset_fusion(struct Scsi_Host *shost)
{
	int retval = SUCCESS, i, j, retry = 0;
	struct megasas_instance *instance;
	struct megasas_cmd_fusion *cmd_fusion;
	struct fusion_context *fusion;
	struct megasas_cmd *cmd_mfi;
	union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
	u32 host_diag, abs_state;

	instance = (struct megasas_instance *)shost->hostdata;
	fusion = instance->ctrl_context;

	mutex_lock(&instance->reset_mutex);
	set_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
	instance->adprecovery = MEGASAS_ADPRESET_SM_INFAULT;
	instance->instancet->disable_intr(instance->reg_set);
	msleep(1000);

	if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
		printk(KERN_WARNING "megaraid_sas: Hardware critical error, "
		       "returning FAILED.\n");
		retval = FAILED;
		goto out;
	}

	/* First try waiting for commands to complete */
	if (megasas_wait_for_outstanding_fusion(instance)) {
		printk(KERN_WARNING "megaraid_sas: resetting fusion "
		       "adapter.\n");
		/* Now return commands back to the OS */
		for (i = 0 ; i < instance->max_fw_cmds; i++) {
			cmd_fusion = fusion->cmd_list[i];
			if (cmd_fusion->scmd) {
				scsi_dma_unmap(cmd_fusion->scmd);
				cmd_fusion->scmd->result = (DID_RESET << 16);
				cmd_fusion->scmd->scsi_done(cmd_fusion->scmd);
				megasas_return_cmd_fusion(instance, cmd_fusion);
				atomic_dec(&instance->fw_outstanding);
			}
		}

		if (instance->disableOnlineCtrlReset == 1) {
			/* Reset not supported, kill adapter */
			printk(KERN_WARNING "megaraid_sas: Reset not supported"
			       ", killing adapter.\n");
			megaraid_sas_kill_hba(instance);
			instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR;
			retval = FAILED;
			goto out;
		}

		/* Now try to reset the chip */
		for (i = 0; i < MEGASAS_FUSION_MAX_RESET_TRIES; i++) {
			writel(MPI2_WRSEQ_FLUSH_KEY_VALUE,
			       &instance->reg_set->fusion_seq_offset);
			writel(MPI2_WRSEQ_1ST_KEY_VALUE,
			       &instance->reg_set->fusion_seq_offset);
			writel(MPI2_WRSEQ_2ND_KEY_VALUE,
			       &instance->reg_set->fusion_seq_offset);
			writel(MPI2_WRSEQ_3RD_KEY_VALUE,
			       &instance->reg_set->fusion_seq_offset);
			writel(MPI2_WRSEQ_4TH_KEY_VALUE,
			       &instance->reg_set->fusion_seq_offset);
			writel(MPI2_WRSEQ_5TH_KEY_VALUE,
			       &instance->reg_set->fusion_seq_offset);
			writel(MPI2_WRSEQ_6TH_KEY_VALUE,
			       &instance->reg_set->fusion_seq_offset);

			/* Check that the diag write enable (DRWE) bit is on */
			host_diag = readl(&instance->reg_set->fusion_host_diag);
			while (!(host_diag & HOST_DIAG_WRITE_ENABLE)) {
				msleep(100);
				host_diag =
				readl(&instance->reg_set->fusion_host_diag);
				if (retry++ == 100) {
					printk(KERN_WARNING "megaraid_sas: "
					       "Host diag unlock failed!\n");
					break;
				}
			}
			if (!(host_diag & HOST_DIAG_WRITE_ENABLE))
				continue;

			/* Send chip reset command */
			writel(host_diag | HOST_DIAG_RESET_ADAPTER,
			       &instance->reg_set->fusion_host_diag);
			msleep(3000);

			/* Make sure reset adapter bit is cleared */
			host_diag = readl(&instance->reg_set->fusion_host_diag);
			retry = 0;
			while (host_diag & HOST_DIAG_RESET_ADAPTER) {
				msleep(100);
				host_diag =
				readl(&instance->reg_set->fusion_host_diag);
				if (retry++ == 1000) {
					printk(KERN_WARNING "megaraid_sas: "
					       "Diag reset adapter never "
					       "cleared!\n");
					break;
				}
			}
			if (host_diag & HOST_DIAG_RESET_ADAPTER)
				continue;

			abs_state =
				instance->instancet->read_fw_status_reg(
					instance->reg_set);
			retry = 0;

			while ((abs_state <= MFI_STATE_FW_INIT) &&
			       (retry++ < 1000)) {
				msleep(100);
				abs_state =
				instance->instancet->read_fw_status_reg(
					instance->reg_set);
			}
			if (abs_state <= MFI_STATE_FW_INIT) {
				printk(KERN_WARNING "megaraid_sas: firmware "
				       "state < MFI_STATE_FW_INIT, state = "
				       "0x%x\n", abs_state);
				continue;
			}

			/* Wait for FW to become ready */
			if (megasas_transition_to_ready(instance)) {
				printk(KERN_WARNING "megaraid_sas: Failed to "
				       "transition controller to ready.\n");
				continue;
			}

			megasas_reset_reply_desc(instance);
			if (megasas_ioc_init_fusion(instance)) {
				printk(KERN_WARNING "megaraid_sas: "
				       "megasas_ioc_init_fusion() failed!\n");
				continue;
			}

			instance->instancet->enable_intr(instance->reg_set);
			instance->adprecovery = MEGASAS_HBA_OPERATIONAL;

			/* Re-fire management commands */
			for (j = 0 ; j < instance->max_fw_cmds; j++) {
				cmd_fusion = fusion->cmd_list[j];
				if (cmd_fusion->sync_cmd_idx !=
				    (u32)ULONG_MAX) {
					cmd_mfi =
					instance->
					cmd_list[cmd_fusion->sync_cmd_idx];
					if (cmd_mfi->frame->dcmd.opcode ==
					    MR_DCMD_LD_MAP_GET_INFO) {
						megasas_return_cmd(instance,
								   cmd_mfi);
						megasas_return_cmd_fusion(
							instance, cmd_fusion);
					} else  {
						req_desc =
						megasas_get_request_descriptor(
							instance,
							cmd_mfi->context.smid
							-1);
						if (!req_desc)
							printk(KERN_WARNING
							       "req_desc NULL"
							       "\n");
						else {
							instance->instancet->
							fire_cmd(instance,
								 req_desc->
								 u.low,
								 req_desc->
								 u.high,
								 instance->
								 reg_set);
						}
					}
				}
			}

			/* Reset load balance info */
			memset(fusion->load_balance_info, 0,
			       sizeof(struct LD_LOAD_BALANCE_INFO)
			       *MAX_LOGICAL_DRIVES);

			if (!megasas_get_map_info(instance))
				megasas_sync_map_info(instance);

			/* Adapter reset completed successfully */
			printk(KERN_WARNING "megaraid_sas: Reset "
			       "successful.\n");
			retval = SUCCESS;
			goto out;
		}
		/* Reset failed, kill the adapter */
		printk(KERN_WARNING "megaraid_sas: Reset failed, killing "
		       "adapter.\n");
		megaraid_sas_kill_hba(instance);
		retval = FAILED;
	} else {
		instance->instancet->enable_intr(instance->reg_set);
		instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
	}
out:
	clear_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
	mutex_unlock(&instance->reset_mutex);
	return retval;
}

/* Fusion OCR work queue */
void megasas_fusion_ocr_wq(struct work_struct *work)
{
	struct megasas_instance *instance =
		container_of(work, struct megasas_instance, work_init);

	megasas_reset_fusion(instance->host);
}

struct megasas_instance_template megasas_instance_template_fusion = {
	.fire_cmd = megasas_fire_cmd_fusion,
	.enable_intr = megasas_enable_intr_fusion,
	.disable_intr = megasas_disable_intr_fusion,
	.clear_intr = megasas_clear_intr_fusion,
	.read_fw_status_reg = megasas_read_fw_status_reg_fusion,
	.adp_reset = megasas_adp_reset_fusion,
	.check_reset = megasas_check_reset_fusion,
	.service_isr = megasas_isr_fusion,
	.tasklet = megasas_complete_cmd_dpc_fusion,
	.init_adapter = megasas_init_adapter_fusion,
	.build_and_issue_cmd = megasas_build_and_issue_cmd_fusion,
	.issue_dcmd = megasas_issue_dcmd_fusion,
};